Convert all uses of uint8/16/32 to _t in nmbd and the include file.
[samba.git] / source3 / nmbd / nmbd.c
index d6943b19e671e1797e21184af69de6bd1910fa31..c7e72de5530aaba9df4aa4947debcce3fd69291f 100644 (file)
@@ -4,26 +4,29 @@
    Copyright (C) Andrew Tridgell 1994-1998
    Copyright (C) Jeremy Allison 1997-2002
    Copyright (C) Jelmer Vernooij 2002,2003 (Conversion to popt)
-   
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-   
 */
 
 #include "includes.h"
+#include "system/filesys.h"
 #include "popt_common.h"
-#include "librpc/gen_ndr/messaging.h"
 #include "nmbd/nmbd.h"
+#include "serverid.h"
+#include "messages.h"
+#include "../lib/util/pidfile.h"
+#include "util_cluster.h"
 
 int ClientNMB       = -1;
 int ClientDGRAM     = -1;
@@ -41,35 +44,25 @@ bool found_lm_clients = False;
 
 time_t StartupTime = 0;
 
-struct event_context *nmbd_event_context(void)
+struct tevent_context *nmbd_event_context(void)
 {
        return server_event_context();
 }
 
-struct messaging_context *nmbd_messaging_context(void)
-{
-       struct messaging_context *msg_ctx = server_messaging_context();
-       if (likely(msg_ctx != NULL)) {
-               return msg_ctx;
-       }
-       smb_panic("Could not init nmbd's messaging context.\n");
-       return NULL;
-}
-
 /**************************************************************************** **
  Handle a SIGTERM in band.
  **************************************************************************** */
 
-static void terminate(void)
+static void terminate(struct messaging_context *msg)
 {
        DEBUG(0,("Got SIGTERM: going down...\n"));
-  
+
        /* Write out wins.dat file if samba is a WINS server */
        wins_write_database(0,False);
-  
+
        /* Remove all SELF registered names from WINS */
        release_wins_names();
-  
+
        /* Announce all server entries as 0 time-to-live, 0 type. */
        announce_my_servers_removed();
 
@@ -77,9 +70,9 @@ static void terminate(void)
        kill_async_dns_child();
 
        gencache_stabilize();
-       serverid_deregister(procid_self());
+       serverid_deregister(messaging_server_id(msg));
 
-       pidfile_unlink();
+       pidfile_unlink(lp_pid_directory(), "nmbd");
 
        exit(0);
 }
@@ -91,10 +84,31 @@ static void nmbd_sig_term_handler(struct tevent_context *ev,
                                  void *siginfo,
                                  void *private_data)
 {
-       terminate();
+       struct messaging_context *msg = talloc_get_type_abort(
+               private_data, struct messaging_context);
+
+       terminate(msg);
 }
 
-static bool nmbd_setup_sig_term_handler(void)
+/*
+  handle stdin becoming readable when we are in --foreground mode
+ */
+static void nmbd_stdin_handler(struct tevent_context *ev,
+                              struct tevent_fd *fde,
+                              uint16_t flags,
+                              void *private_data)
+{
+       char c;
+       if (read(0, &c, 1) != 1) {
+               struct messaging_context *msg = talloc_get_type_abort(
+                       private_data, struct messaging_context);
+               
+               DEBUG(0,("EOF on stdin\n"));
+               terminate(msg);
+       }
+}
+
+static bool nmbd_setup_sig_term_handler(struct messaging_context *msg)
 {
        struct tevent_signal *se;
 
@@ -102,7 +116,7 @@ static bool nmbd_setup_sig_term_handler(void)
                               nmbd_event_context(),
                               SIGTERM, 0,
                               nmbd_sig_term_handler,
-                              NULL);
+                              msg);
        if (!se) {
                DEBUG(0,("failed to setup SIGTERM handler"));
                return false;
@@ -111,6 +125,31 @@ static bool nmbd_setup_sig_term_handler(void)
        return true;
 }
 
+static bool nmbd_setup_stdin_handler(struct messaging_context *msg, bool foreground)
+{
+       if (foreground) {
+               /* if we are running in the foreground then look for
+                  EOF on stdin, and exit if it happens. This allows
+                  us to die if the parent process dies
+                  Only do this on a pipe or socket, no other device.
+               */
+               struct stat st;
+               if (fstat(0, &st) != 0) {
+                       return false;
+               }
+               if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
+                       tevent_add_fd(nmbd_event_context(),
+                               nmbd_event_context(),
+                               0,
+                               TEVENT_FD_READ,
+                               nmbd_stdin_handler,
+                               msg);
+               }
+       }
+
+       return true;
+}
+
 static void msg_reload_nmbd_services(struct messaging_context *msg,
                                     void *private_data,
                                     uint32_t msg_type,
@@ -124,13 +163,15 @@ static void nmbd_sig_hup_handler(struct tevent_context *ev,
                                 void *siginfo,
                                 void *private_data)
 {
+       struct messaging_context *msg = talloc_get_type_abort(
+               private_data, struct messaging_context);
+
        DEBUG(0,("Got SIGHUP dumping debug info.\n"));
-       msg_reload_nmbd_services(nmbd_messaging_context(),
-                                NULL, MSG_SMB_CONF_UPDATED,
-                                procid_self(), NULL);
+       msg_reload_nmbd_services(msg, NULL, MSG_SMB_CONF_UPDATED,
+                                messaging_server_id(msg), NULL);
 }
 
-static bool nmbd_setup_sig_hup_handler(void)
+static bool nmbd_setup_sig_hup_handler(struct messaging_context *msg)
 {
        struct tevent_signal *se;
 
@@ -138,7 +179,7 @@ static bool nmbd_setup_sig_hup_handler(void)
                               nmbd_event_context(),
                               SIGHUP, 0,
                               nmbd_sig_hup_handler,
-                              NULL);
+                              msg);
        if (!se) {
                DEBUG(0,("failed to setup SIGHUP handler"));
                return false;
@@ -157,16 +198,7 @@ static void nmbd_terminate(struct messaging_context *msg,
                           struct server_id server_id,
                           DATA_BLOB *data)
 {
-       terminate();
-}
-
-/**************************************************************************** **
- Possibly continue after a fault.
- **************************************************************************** */
-
-static void fault_continue(void)
-{
-       dump_core();
+       terminate(msg);
 }
 
 /**************************************************************************** **
@@ -176,7 +208,7 @@ static void fault_continue(void)
 static void expire_names_and_servers(time_t t)
 {
        static time_t lastrun = 0;
-  
+
        if ( !lastrun )
                lastrun = t;
        if ( t < (lastrun + 5) )
@@ -248,8 +280,8 @@ static void reload_interfaces(time_t t)
                        continue;
                }
 
-               ip = ((struct sockaddr_in *)(void *)&iface->ip)->sin_addr;
-               nmask = ((struct sockaddr_in *)(void *)
+               ip = ((const struct sockaddr_in *)(const void *)&iface->ip)->sin_addr;
+               nmask = ((const struct sockaddr_in *)(const void *)
                         &iface->netmask)->sin_addr;
 
                /*
@@ -258,7 +290,7 @@ static void reload_interfaces(time_t t)
                 * ignore it here. JRA.
                 */
 
-               if (is_loopback_addr((struct sockaddr *)(void *)&iface->ip)) {
+               if (is_loopback_addr((const struct sockaddr *)(const void *)&iface->ip)) {
                        DEBUG(2,("reload_interfaces: Ignoring loopback "
                                "interface %s\n",
                                print_sockaddr(str, sizeof(str), &iface->ip) ));
@@ -364,17 +396,18 @@ static bool reload_nmbd_services(bool test)
        set_remote_machine_name("nmbd", False);
 
        if ( lp_loaded() ) {
-               const char *fname = lp_configfile();
+               char *fname = lp_next_configfile(talloc_tos());
                if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
                        set_dyn_CONFIGFILE(fname);
                        test = False;
                }
+               TALLOC_FREE(fname);
        }
 
        if ( test && !lp_file_list_changed() )
                return(True);
 
-       ret = lp_load(get_dyn_CONFIGFILE(), True , False, False, True);
+       ret = lp_load_global(get_dyn_CONFIGFILE());
 
        /* perhaps the config filename is now set */
        if ( !test ) {
@@ -382,6 +415,8 @@ static bool reload_nmbd_services(bool test)
                reload_nmbd_services( True );
        }
 
+       reopen_logs();
+
        return(ret);
 }
 
@@ -467,7 +502,7 @@ static void msg_nmbd_send_packet(struct messaging_context *msg,
  The main select loop.
  **************************************************************************** */
 
-static void process(void)
+static void process(struct messaging_context *msg)
 {
        bool run_election;
 
@@ -488,7 +523,7 @@ static void process(void)
                 * (nmbd_packets.c)
                 */
 
-               if(listen_for_packets(run_election)) {
+               if (listen_for_packets(msg, run_election)) {
                        TALLOC_FREE(frame);
                        return;
                }
@@ -656,12 +691,6 @@ static void process(void)
                if (lp_enhanced_browsing())
                        sync_all_dmbs(t);
 
-               /*
-                * clear the unexpected packet queue 
-                */
-
-               clear_unexpected(t);
-
                /* check for new network interfaces */
 
                reload_interfaces(t);
@@ -678,7 +707,7 @@ static void process(void)
 static bool open_sockets(bool isdaemon, int port)
 {
        struct sockaddr_storage ss;
-       const char *sock_addr = lp_socket_address();
+       const char *sock_addr = lp_nbt_client_socket_address();
 
        /*
         * The sockets opened here will be used to receive broadcast
@@ -744,14 +773,15 @@ static bool open_sockets(bool isdaemon, int port)
 
  int main(int argc, const char *argv[])
 {
-       static bool is_daemon;
-       static bool opt_interactive;
-       static bool Fork = true;
-       static bool no_process_group;
-       static bool log_stdout;
+       bool is_daemon = false;
+       bool opt_interactive = false;
+       bool Fork = true;
+       bool no_process_group = false;
+       bool log_stdout = false;
        poptContext pc;
        char *p_lmhosts = NULL;
        int opt;
+       struct messaging_context *msg;
        enum {
                OPT_DAEMON = 1000,
                OPT_INTERACTIVE,
@@ -766,13 +796,14 @@ static bool open_sockets(bool isdaemon, int port)
        {"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" },
+       {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
+       {"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
        POPT_COMMON_SAMBA
        { NULL }
        };
        TALLOC_CTX *frame;
        NTSTATUS status;
+       bool ok;
 
        /*
         * Do this before any other talloc operation
@@ -780,7 +811,15 @@ static bool open_sockets(bool isdaemon, int port)
        talloc_enable_null_tracking();
        frame = talloc_stackframe();
 
-       load_case_tables();
+       /*
+        * We want total control over the permissions on created files,
+        * so set our umask to 0.
+        */
+       umask(0);
+
+       setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
+
+       smb_init_locale();
 
        global_nmb_port = NMB_PORT;
 
@@ -812,11 +851,11 @@ static bool open_sockets(bool isdaemon, int port)
        poptFreeContext(pc);
 
        global_in_nmbd = true;
-       
+
        StartupTime = time(NULL);
-       
-       sys_srandom(time(NULL) ^ sys_getpid());
-       
+
+       sys_srandom(time(NULL) ^ getpid());
+
        if (!override_logfile) {
                char *lfile = NULL;
                if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
@@ -825,10 +864,10 @@ static bool open_sockets(bool isdaemon, int port)
                lp_set_logfile(lfile);
                SAFE_FREE(lfile);
        }
-       
-       fault_setup((void (*)(void *))fault_continue );
-       dump_core_setup("nmbd");
-       
+
+       fault_setup();
+       dump_core_setup("nmbd", lp_logfile(talloc_tos()));
+
        /* POSIX demands that signals are inherited. If the invoking process has
         * these signals masked, we will have problems, as we won't receive them. */
        BlockSignals(False, SIGHUP);
@@ -845,6 +884,9 @@ static bool open_sockets(bool isdaemon, int port)
        BlockSignals(True, SIGUSR2);
 #endif
 
+       /* Ignore children - no zombies. */
+       CatchChild();
+
        if ( opt_interactive ) {
                Fork = False;
                log_stdout = True;
@@ -854,8 +896,9 @@ static bool open_sockets(bool isdaemon, int port)
                DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
                exit(1);
        }
+
        if (log_stdout) {
-               setup_logging( argv[0], DEBUG_STDOUT);
+               setup_logging(argv[0], DEBUG_STDOUT);
        } else {
                setup_logging( argv[0], DEBUG_FILE);
        }
@@ -866,11 +909,28 @@ static bool open_sockets(bool isdaemon, int port)
        DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
 
        if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
-               DEBUG(0, ("error opening config file\n"));
+               DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
                exit(1);
        }
 
-       if (nmbd_messaging_context() == NULL) {
+       reopen_logs();
+
+       if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
+           && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
+               /* TODO: when we have a merged set of defaults for
+                * loadparm, we could possibly check if the internal
+                * nbt server is in the list, and allow a startup if disabled */
+               DEBUG(0, ("server role = 'active directory domain controller' not compatible with running nmbd standalone. \n"));
+               DEBUGADD(0, ("You should start 'samba' instead, and it will control starting the internal nbt server\n"));
+               exit(1);
+       }
+
+       if (!cluster_probe_ok()) {
+               exit(1);
+       }
+
+       msg = messaging_init(NULL, server_event_context());
+       if (msg == NULL) {
                return 1;
        }
 
@@ -890,12 +950,12 @@ static bool open_sockets(bool isdaemon, int port)
        set_samba_nb_type();
 
        if (!is_daemon && !is_a_socket(0)) {
-               DEBUG(0,("standard input is not a socket, assuming -D option\n"));
+               DEBUG(3, ("standard input is not a socket, assuming -D option\n"));
                is_daemon = True;
        }
-  
+
        if (is_daemon && !opt_interactive) {
-               DEBUG( 2, ( "Becoming a daemon.\n" ) );
+               DEBUG(3, ("Becoming a daemon.\n"));
                become_daemon(Fork, no_process_group, log_stdout);
        }
 
@@ -908,59 +968,76 @@ static bool open_sockets(bool isdaemon, int port)
                setpgid( (pid_t)0, (pid_t)0 );
 #endif
 
-       if (nmbd_messaging_context() == NULL) {
-               return 1;
-       }
-
 #ifndef SYNC_DNS
        /* Setup the async dns. We do it here so it doesn't have all the other
                stuff initialised and thus chewing memory and sockets */
-       if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
-               start_async_dns();
+       if(lp_we_are_a_wins_server() && lp_wins_dns_proxy()) {
+               start_async_dns(msg);
        }
 #endif
 
-       if (!directory_exist(lp_lockdir())) {
-               mkdir(lp_lockdir(), 0755);
+       ok = directory_create_or_exist(lp_lock_directory(), 0755);
+       if (!ok) {
+               exit_daemon("Failed to create directory for lock files, check 'lock directory'", errno);
+       }
+
+       ok = directory_create_or_exist(lp_pid_directory(), 0755);
+       if (!ok) {
+               exit_daemon("Failed to create directory for pid files, check 'pid directory'", errno);
        }
 
-       pidfile_create("nmbd");
+       pidfile_create(lp_pid_directory(), "nmbd");
 
-       status = reinit_after_fork(nmbd_messaging_context(),
-                                  nmbd_event_context(),
-                                  procid_self(), false);
+       status = reinit_after_fork(msg, nmbd_event_context(),
+                                  false);
 
        if (!NT_STATUS_IS_OK(status)) {
-               DEBUG(0,("reinit_after_fork() failed\n"));
-               exit(1);
+               exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
        }
 
-       if (!nmbd_setup_sig_term_handler())
-               exit(1);
-       if (!nmbd_setup_sig_hup_handler())
+       /*
+        * Do not initialize the parent-child-pipe before becoming
+        * a daemon: this is used to detect a died parent in the child
+        * process.
+        */
+       status = init_before_fork();
+       if (!NT_STATUS_IS_OK(status)) {
+               exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
+       }
+
+       if (!nmbd_setup_sig_term_handler(msg))
+               exit_daemon("NMBD failed to setup signal handler", EINVAL);
+       if (!nmbd_setup_stdin_handler(msg, !Fork))
+               exit_daemon("NMBD failed to setup stdin handler", EINVAL);
+       if (!nmbd_setup_sig_hup_handler(msg))
+               exit_daemon("NMBD failed to setup SIGHUP handler", EINVAL);
+
+       if (!messaging_parent_dgm_cleanup_init(msg)) {
                exit(1);
+       }
 
        /* get broadcast messages */
 
-       if (!serverid_register(procid_self(),
-                              FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
-               DEBUG(1, ("Could not register myself in serverid.tdb\n"));
-               exit(1);
+       if (!serverid_register(messaging_server_id(msg),
+                               FLAG_MSG_GENERAL |
+                               FLAG_MSG_NMBD |
+                               FLAG_MSG_DBWRAP)) {
+               exit_daemon("Could not register NMBD process in serverid.tdb", EACCES);
        }
 
-       messaging_register(nmbd_messaging_context(), NULL,
-                          MSG_FORCE_ELECTION, nmbd_message_election);
+       messaging_register(msg, NULL, MSG_FORCE_ELECTION,
+                          nmbd_message_election);
 #if 0
        /* Until winsrepl is done. */
-       messaging_register(nmbd_messaging_context(), NULL,
-                          MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
+       messaging_register(msg, NULL, MSG_WINS_NEW_ENTRY,
+                          nmbd_wins_new_entry);
 #endif
-       messaging_register(nmbd_messaging_context(), NULL,
-                          MSG_SHUTDOWN, nmbd_terminate);
-       messaging_register(nmbd_messaging_context(), NULL,
-                          MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services);
-       messaging_register(nmbd_messaging_context(), NULL,
-                          MSG_SEND_PACKET, msg_nmbd_send_packet);
+       messaging_register(msg, NULL, MSG_SHUTDOWN,
+                          nmbd_terminate);
+       messaging_register(msg, NULL, MSG_SMB_CONF_UPDATED,
+                          msg_reload_nmbd_services);
+       messaging_register(msg, NULL, MSG_SEND_PACKET,
+                          msg_nmbd_send_packet);
 
        TimeInit();
 
@@ -976,9 +1053,8 @@ static bool open_sockets(bool isdaemon, int port)
 
        /* Create an nmbd subnet record for each of the above. */
        if( False == create_subnets() ) {
-               DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
                kill_async_dns_child();
-               exit(1);
+               exit_daemon("NMBD failed when creating subnet lists", EACCES);
        }
 
        /* Load in any static local names. */ 
@@ -990,9 +1066,8 @@ static bool open_sockets(bool isdaemon, int port)
 
        /* If we are acting as a WINS server, initialise data structures. */
        if( !initialise_wins() ) {
-               DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
                kill_async_dns_child();
-               exit(1);
+               exit_daemon( "NMBD failed when initialising WINS server.", EACCES);
        }
 
        /* 
@@ -1004,19 +1079,26 @@ static bool open_sockets(bool isdaemon, int port)
         */
 
        if( False == register_my_workgroup_and_names() ) {
-               DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
                kill_async_dns_child();
-               exit(1);
+               exit_daemon( "NMBD failed when creating my workgroup.", EACCES);
        }
 
        if (!initialize_nmbd_proxy_logon()) {
-               DEBUG(0,("ERROR: Failed setup nmbd_proxy_logon.\n"));
                kill_async_dns_child();
-               exit(1);
+               exit_daemon( "NMBD failed to setup nmbd_proxy_logon.", EACCES);
+       }
+
+       if (!nmbd_init_packet_server()) {
+               kill_async_dns_child();
+               exit_daemon( "NMBD failed to setup packet server.", EACCES);
+       }
+
+       if (is_daemon && !opt_interactive) {
+               daemon_ready("nmbd");
        }
 
        TALLOC_FREE(frame);
-       process();
+       process(msg);
 
        kill_async_dns_child();
        return(0);