s3:nmbd: as the sig_term() handler only sets a flag we don't need to block SIGTERM
[metze/samba/wip.git] / source3 / nmbd / nmbd.c
index 510e676e33a03dc0326c531cbe2e5991d6d0c74b..1b26c0a5ada8e01878141ab2b584b1fce12e1fb4 100644 (file)
@@ -52,9 +52,12 @@ struct messaging_context *nmbd_messaging_context(void)
 {
        static struct messaging_context *ctx;
 
-       if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
-                                          nmbd_event_context()))) {
-               smb_panic("Could not init nmbd messaging context");
+       if (ctx == NULL) {
+               ctx = messaging_init(NULL, server_id_self(),
+                                    nmbd_event_context());
+       }
+       if (ctx == NULL) {
+               DEBUG(0, ("Could not init nmbd messaging context.\n"));
        }
        return ctx;
 }
@@ -163,18 +166,27 @@ static void expire_names_and_servers(time_t t)
 
 /************************************************************************** **
  Reload the list of network interfaces.
+ Doesn't return until a network interface is up.
  ************************************************************************** */
 
-static bool reload_interfaces(time_t t)
+static void reload_interfaces(time_t t)
 {
        static time_t lastt;
        int n;
+       bool print_waiting_msg = true;
        struct subnet_record *subrec;
 
-       if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) return False;
+       if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
+               return;
+       }
+
        lastt = t;
 
-       if (!interfaces_changed()) return False;
+       if (!interfaces_changed()) {
+               return;
+       }
+
+  try_again:
 
        /* the list of probed interfaces has changed, we may need to add/remove
           some subnets */
@@ -207,24 +219,25 @@ static bool reload_interfaces(time_t t)
                 * ignore it here. JRA.
                 */
 
-               if (is_loopback_addr(&iface->ip)) {
+               if (is_loopback_addr((struct sockaddr *)&iface->ip)) {
                        DEBUG(2,("reload_interfaces: Ignoring loopback "
                                "interface %s\n",
-                               print_sockaddr(str, sizeof(str),
-                                       &iface->ip, sizeof(iface->ip)) ));
+                               print_sockaddr(str, sizeof(str), &iface->ip) ));
                        continue;
                }
 
                for (subrec=subnetlist; subrec; subrec=subrec->next) {
-                       if (ip_equal(ip, subrec->myip) &&
-                           ip_equal(nmask, subrec->mask_ip)) break;
+                       if (ip_equal_v4(ip, subrec->myip) &&
+                           ip_equal_v4(nmask, subrec->mask_ip)) {
+                               break;
+                       }
                }
 
                if (!subrec) {
                        /* it wasn't found! add it */
-                       DEBUG(2,("Found new interface %s\n", 
-                                print_sockaddr(str, sizeof(str),
-                                        &iface->ip, sizeof(iface->ip)) ));
+                       DEBUG(2,("Found new interface %s\n",
+                                print_sockaddr(str,
+                                        sizeof(str), &iface->ip) ));
                        subrec = make_normal_subnet(iface);
                        if (subrec)
                                register_my_workgroup_one_subnet(subrec);
@@ -247,8 +260,10 @@ static bool reload_interfaces(time_t t)
                        }
                        ip = ((struct sockaddr_in *)&iface->ip)->sin_addr;
                        nmask = ((struct sockaddr_in *)&iface->netmask)->sin_addr;
-                       if (ip_equal(ip, subrec->myip) &&
-                           ip_equal(nmask, subrec->mask_ip)) break;
+                       if (ip_equal_v4(ip, subrec->myip) &&
+                           ip_equal_v4(nmask, subrec->mask_ip)) {
+                               break;
+                       }
                }
                if (n == -1) {
                        /* oops, an interface has disapeared. This is
@@ -257,20 +272,44 @@ static bool reload_interfaces(time_t t)
                         instead we just wear the memory leak and
                         remove it from the list of interfaces without
                         freeing it */
-                       DEBUG(2,("Deleting dead interface %s\n", 
+                       DEBUG(2,("Deleting dead interface %s\n",
                                 inet_ntoa(subrec->myip)));
                        close_subnet(subrec);
                }
        }
-       
+
        rescan_listen_set = True;
 
-       /* We need to shutdown if there are no subnets... */
+       /* We need to wait if there are no subnets... */
        if (FIRST_SUBNET == NULL) {
-               DEBUG(0,("reload_interfaces: No subnets to listen to. Shutting down...\n"));
-               return True;
+               void (*saved_handler)(int);
+
+               if (print_waiting_msg) {
+                       DEBUG(0,("reload_interfaces: "
+                               "No subnets to listen to. Waiting..\n"));
+                       print_waiting_msg = false;
+               }
+
+               /*
+                * Whilst we're waiting for an interface, allow SIGTERM to
+                * cause us to exit.
+                */
+               saved_handler = CatchSignal( SIGTERM, SIGNAL_CAST SIG_DFL );
+
+               /* We only count IPv4, non-loopback interfaces here. */
+               while (iface_count_v4_nl() == 0) {
+                       sleep(5);
+                       load_interfaces();
+               }
+
+               CatchSignal( SIGTERM, SIGNAL_CAST saved_handler );
+
+               /*
+                * We got an interface, go back to blocking term.
+                */
+
+               goto try_again;
        }
-       return False;
 }
 
 /**************************************************************************** **
@@ -284,10 +323,9 @@ static bool reload_nmbd_services(bool test)
        set_remote_machine_name("nmbd", False);
 
        if ( lp_loaded() ) {
-               pstring fname;
-               pstrcpy( fname,lp_configfile());
-               if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
-                       pstrcpy(dyn_CONFIGFILE,fname);
+               const char *fname = lp_configfile();
+               if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
+                       set_dyn_CONFIGFILE(fname);
                        test = False;
                }
        }
@@ -295,7 +333,7 @@ static bool reload_nmbd_services(bool test)
        if ( test && !lp_file_list_changed() )
                return(True);
 
-       ret = lp_load( dyn_CONFIGFILE, True , False, False, True);
+       ret = lp_load(get_dyn_CONFIGFILE(), True , False, False, True);
 
        /* perhaps the config filename is now set */
        if ( !test ) {
@@ -308,8 +346,6 @@ static bool reload_nmbd_services(bool test)
 
 /**************************************************************************** **
  * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
- * We use buf here to return bool result to process() when reload_interfaces()
- * detects that there are no subnets.
  **************************************************************************** */
 
 static void msg_reload_nmbd_services(struct messaging_context *msg,
@@ -322,14 +358,7 @@ static void msg_reload_nmbd_services(struct messaging_context *msg,
        dump_all_namelists();
        reload_nmbd_services( True );
        reopen_logs();
-       
-       if (data->data) {
-               /* We were called from process() */
-               /* If reload_interfaces() returned True */
-               /* we need to shutdown if there are no subnets... */
-               /* pass this info back to process() */
-               *((bool *)data->data) = reload_interfaces(0);  
-       }
+       reload_interfaces(0);
 }
 
 static void msg_nmbd_send_packet(struct messaging_context *msg,
@@ -360,7 +389,7 @@ static void msg_nmbd_send_packet(struct messaging_context *msg,
        }
 
        in_addr_to_sockaddr_storage(&ss, p->ip);
-       pss = iface_ip(&ss);
+       pss = iface_ip((struct sockaddr *)&ss);
 
        if (pss == NULL) {
                DEBUG(2, ("Could not find ip for packet from %d\n",
@@ -376,7 +405,7 @@ static void msg_nmbd_send_packet(struct messaging_context *msg,
 
        for (subrec = FIRST_SUBNET; subrec != NULL;
             subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
-               if (ip_equal(*local_ip, subrec->myip)) {
+               if (ip_equal_v4(*local_ip, subrec->myip)) {
                        p->fd = (p->packet_type == NMB_PACKET) ?
                                subrec->nmb_sock : subrec->dgram_sock;
                        break;
@@ -399,16 +428,11 @@ static void msg_nmbd_send_packet(struct messaging_context *msg,
 static void process(void)
 {
        bool run_election;
-       bool no_subnets;
 
        while( True ) {
                time_t t = time(NULL);
                TALLOC_CTX *frame = talloc_stackframe();
 
-               /* Check for internal messages */
-
-               message_dispatch(nmbd_messaging_context());
-
                /*
                 * Check all broadcast subnets to see if
                 * we need to run an election on any of them.
@@ -610,26 +634,17 @@ static void process(void)
                 */
 
                if(reload_after_sighup) {
-                       DATA_BLOB blob = data_blob_const(&no_subnets,
-                                                        sizeof(no_subnets));
                        DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
                        msg_reload_nmbd_services(nmbd_messaging_context(),
                                                 NULL, MSG_SMB_CONF_UPDATED,
-                                                procid_self(), &blob);
+                                                procid_self(), NULL);
 
-                       if(no_subnets) {
-                               TALLOC_FREE(frame);
-                               return;
-                       }
                        reload_after_sighup = 0;
                }
 
                /* check for new network interfaces */
 
-               if(reload_interfaces(t)) {
-                       TALLOC_FREE(frame);
-                       return;
-               }
+               reload_interfaces(t);
 
                /* free up temp memory */
                TALLOC_FREE(frame);
@@ -642,6 +657,9 @@ static void process(void)
 
 static bool open_sockets(bool isdaemon, int port)
 {
+       struct sockaddr_storage ss;
+       const char *sock_addr = lp_socket_address();
+
        /*
         * The sockets opened here will be used to receive broadcast
         * packets *only*. Interface specific sockets are opened in
@@ -650,19 +668,41 @@ static bool open_sockets(bool isdaemon, int port)
         * now deprecated.
         */
 
-       if ( isdaemon )
+       if (!interpret_string_addr(&ss, sock_addr,
+                               AI_NUMERICHOST|AI_PASSIVE)) {
+               DEBUG(0,("open_sockets: unable to get socket address "
+                       "from string %s", sock_addr));
+               return false;
+       }
+       if (ss.ss_family != AF_INET) {
+               DEBUG(0,("open_sockets: unable to use IPv6 socket"
+                       "%s in nmbd\n",
+                       sock_addr));
+               return false;
+       }
+
+       if (isdaemon) {
                ClientNMB = open_socket_in(SOCK_DGRAM, port,
-                                          0, interpret_addr(lp_socket_address()),
-                                          True);
-       else
+                                          0, &ss,
+                                          true);
+       } else {
                ClientNMB = 0;
-  
+       }
+
+       if (ClientNMB == -1) {
+               return false;
+       }
+
        ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
-                                          3, interpret_addr(lp_socket_address()),
-                                          True);
+                                          3, &ss,
+                                          true);
 
-       if ( ClientNMB == -1 )
-               return( False );
+       if (ClientDGRAM == -1) {
+               if (ClientNMB != 0) {
+                       close(ClientNMB);
+               }
+               return false;
+       }
 
        /* we are never interested in SIGPIPE */
        BlockSignals(True,SIGPIPE);
@@ -681,29 +721,37 @@ static bool open_sockets(bool isdaemon, int port)
 /**************************************************************************** **
  main program
  **************************************************************************** */
+
  int main(int argc, const char *argv[])
 {
-       static int is_daemon;
-       static int Fork = True;
-       static int log_stdout;
-       pstring logfile;
-       static int opt_interactive;
+       static bool is_daemon;
+       static bool opt_interactive;
+       static bool Fork = true;
+       static bool no_process_group;
+       static bool log_stdout;
        poptContext pc;
-       static char *p_lmhosts = dyn_LMHOSTSFILE;
-       static int no_process_group = False;
+       char *p_lmhosts = NULL;
        int opt;
+       enum {
+               OPT_DAEMON = 1000,
+               OPT_INTERACTIVE,
+               OPT_FORK,
+               OPT_NO_PROCESS_GROUP,
+               OPT_LOG_STDOUT
+       };
        struct poptOption long_options[] = {
        POPT_AUTOHELP
-       {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon(default)" },
-       {"interactive", 'i', POPT_ARG_VAL, &opt_interactive, True, "Run interactive (not a daemon)" },
-       {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
-       {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
-       {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
+       {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
+       {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
+       {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
+       {"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
+       {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
        {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 'H', "Load a netbios hosts file"},
        {"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
        POPT_COMMON_SAMBA
        { NULL }
        };
+       TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
 
        load_case_tables();
 
@@ -712,6 +760,21 @@ static bool open_sockets(bool isdaemon, int port)
        pc = poptGetContext("nmbd", argc, argv, long_options, 0);
        while ((opt = poptGetNextOpt(pc)) != -1) {
                switch (opt) {
+               case OPT_DAEMON:
+                       is_daemon = true;
+                       break;
+               case OPT_INTERACTIVE:
+                       opt_interactive = true;
+                       break;
+               case OPT_FORK:
+                       Fork = false;
+                       break;
+               case OPT_NO_PROCESS_GROUP:
+                       no_process_group = true;
+                       break;
+               case OPT_LOG_STDOUT:
+                       log_stdout = true;
+                       break;
                default:
                        d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
                                  poptBadOption(pc, 0), poptStrerror(opt));
@@ -721,15 +784,19 @@ static bool open_sockets(bool isdaemon, int port)
        };
        poptFreeContext(pc);
 
-       global_in_nmbd = True;
+       global_in_nmbd = true;
        
        StartupTime = time(NULL);
        
        sys_srandom(time(NULL) ^ sys_getpid());
        
        if (!override_logfile) {
-               slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
-               lp_set_logfile(logfile);
+               char *lfile = NULL;
+               if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
+                       exit(1);
+               }
+               lp_set_logfile(lfile);
+               SAFE_FREE(lfile);
        }
        
        fault_setup((void (*)(void *))fault_continue );
@@ -768,8 +835,17 @@ static bool open_sockets(bool isdaemon, int port)
 
        reopen_logs();
 
-       DEBUG( 0, ( "Netbios nameserver version %s started.\n", SAMBA_VERSION_STRING) );
-       DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
+       DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
+       DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
+
+       if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
+               DEBUG(0, ("error opening config file\n"));
+               exit(1);
+       }
+
+       if (nmbd_messaging_context() == NULL) {
+               return 1;
+       }
 
        if ( !reload_nmbd_services(False) )
                return(-1);
@@ -817,11 +893,21 @@ static bool open_sockets(bool isdaemon, int port)
        }
 #endif
 
-       if (!directory_exist(lp_lockdir(), NULL)) {
+       if (!directory_exist(lp_lockdir())) {
                mkdir(lp_lockdir(), 0755);
        }
 
        pidfile_create("nmbd");
+
+       if (!reinit_after_fork(nmbd_messaging_context(),
+                              nmbd_event_context(), false)) {
+               DEBUG(0,("reinit_after_fork() failed\n"));
+               exit(1);
+       }
+
+       /* get broadcast messages */
+       claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
+
        messaging_register(nmbd_messaging_context(), NULL,
                           MSG_FORCE_ELECTION, nmbd_message_election);
 #if 0
@@ -856,8 +942,11 @@ static bool open_sockets(bool isdaemon, int port)
        }
 
        /* Load in any static local names. */ 
-       load_lmhosts_file(p_lmhosts);
-       DEBUG(3,("Loaded hosts file %s\n", p_lmhosts));
+       if (p_lmhosts) {
+               set_dyn_LMHOSTSFILE(p_lmhosts);
+       }
+       load_lmhosts_file(get_dyn_LMHOSTSFILE());
+       DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));
 
        /* If we are acting as a WINS server, initialise data structures. */
        if( !initialise_wins() ) {
@@ -880,9 +969,7 @@ static bool open_sockets(bool isdaemon, int port)
                exit(1);
        }
 
-       /* We can only take signals in the select. */
-       BlockSignals( True, SIGTERM );
-
+       TALLOC_FREE(frame);
        process();
 
        if (dbf)