2 Unix SMB/CIFS implementation.
3 NBT netbios routines and daemon - version 2
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 1997-2002
6 Copyright (C) Jelmer Vernooij 2002,2003 (Conversion to popt)
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 int global_nmb_port = -1;
30 extern BOOL rescan_listen_set;
31 extern struct in_addr loopback_ip;
32 extern BOOL global_in_nmbd;
34 extern BOOL override_logfile;
36 /* are we running as a daemon ? */
37 static BOOL is_daemon;
39 /* fork or run in foreground ? */
40 static BOOL Fork = True;
42 /* log to standard output ? */
43 static BOOL log_stdout;
45 /* have we found LanMan clients yet? */
46 BOOL found_lm_clients = False;
48 /* what server type are we currently */
50 time_t StartupTime = 0;
52 /**************************************************************************** **
53 Handle a SIGTERM in band.
54 **************************************************************************** */
56 static void terminate(void)
58 DEBUG(0,("Got SIGTERM: going down...\n"));
60 /* Write out wins.dat file if samba is a WINS server */
61 wins_write_database(0,False);
63 /* Remove all SELF registered names from WINS */
66 /* Announce all server entries as 0 time-to-live, 0 type. */
67 announce_my_servers_removed();
69 /* If there was an async dns child - kill it. */
70 kill_async_dns_child();
75 /**************************************************************************** **
76 Handle a SHUTDOWN message from smbcontrol.
77 **************************************************************************** */
79 static void nmbd_terminate(int msg_type, struct process_id src,
80 void *buf, size_t len, void *private_data)
85 /**************************************************************************** **
86 Catch a SIGTERM signal.
87 **************************************************************************** */
89 static SIG_ATOMIC_T got_sig_term;
91 static void sig_term(int sig)
94 sys_select_signal(SIGTERM);
97 /**************************************************************************** **
98 Catch a SIGHUP signal.
99 **************************************************************************** */
101 static SIG_ATOMIC_T reload_after_sighup;
103 static void sig_hup(int sig)
105 reload_after_sighup = 1;
106 sys_select_signal(SIGHUP);
109 /**************************************************************************** **
110 Possibly continue after a fault.
111 **************************************************************************** */
113 static void fault_continue(void)
118 /**************************************************************************** **
119 Expire old names from the namelist and server list.
120 **************************************************************************** */
122 static void expire_names_and_servers(time_t t)
124 static time_t lastrun = 0;
128 if ( t < (lastrun + 5) )
133 * Expire any timed out names on all the broadcast
134 * subnets and those registered with the WINS server.
135 * (nmbd_namelistdb.c)
141 * Go through all the broadcast subnets and for each
142 * workgroup known on that subnet remove any expired
143 * server names. If a workgroup has an empty serverlist
144 * and has itself timed out then remove the workgroup.
145 * (nmbd_workgroupdb.c)
148 expire_workgroups_and_servers(t);
151 /************************************************************************** **
152 Reload the list of network interfaces.
153 Doesn't return until a network interface is up.
154 ************************************************************************** */
156 static void reload_interfaces(time_t t)
160 struct subnet_record *subrec;
162 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
167 if (!interfaces_changed()) {
171 /* the list of probed interfaces has changed, we may need to add/remove
177 /* find any interfaces that need adding */
178 for (n=iface_count() - 1; n >= 0; n--) {
179 struct interface *iface = get_interface(n);
182 DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
187 * We don't want to add a loopback interface, in case
188 * someone has added 127.0.0.1 for smbd, nmbd needs to
189 * ignore it here. JRA.
192 if (ip_equal(iface->ip, loopback_ip)) {
193 DEBUG(2,("reload_interfaces: Ignoring loopback interface %s\n", inet_ntoa(iface->ip)));
197 for (subrec=subnetlist; subrec; subrec=subrec->next) {
198 if (ip_equal(iface->ip, subrec->myip) &&
199 ip_equal(iface->nmask, subrec->mask_ip)) break;
203 /* it wasn't found! add it */
204 DEBUG(2,("Found new interface %s\n",
205 inet_ntoa(iface->ip)));
206 subrec = make_normal_subnet(iface);
208 register_my_workgroup_one_subnet(subrec);
212 /* find any interfaces that need deleting */
213 for (subrec=subnetlist; subrec; subrec=subrec->next) {
214 for (n=iface_count() - 1; n >= 0; n--) {
215 struct interface *iface = get_interface(n);
216 if (ip_equal(iface->ip, subrec->myip) &&
217 ip_equal(iface->nmask, subrec->mask_ip)) break;
220 /* oops, an interface has disapeared. This is
221 tricky, we don't dare actually free the
222 interface as it could be being used, so
223 instead we just wear the memory leak and
224 remove it from the list of interfaces without
226 DEBUG(2,("Deleting dead interface %s\n",
227 inet_ntoa(subrec->myip)));
228 close_subnet(subrec);
232 rescan_listen_set = True;
234 /* We need to wait if there are no subnets... */
235 if (FIRST_SUBNET == NULL) {
236 void (*saved_handler)(int);
238 DEBUG(2,("reload_interfaces: "
239 "No subnets to listen to. Waiting..\n"));
242 * Whilst we're waiting for an interface, allow SIGTERM to
246 saved_handler = CatchSignal( SIGTERM, SIGNAL_CAST SIG_DFL );
248 while (iface_count() == 0) {
254 * We got an interface, restore our normal term handler.
257 CatchSignal( SIGTERM, SIGNAL_CAST saved_handler );
262 /**************************************************************************** **
263 Reload the services file.
264 **************************************************************************** */
266 static BOOL reload_nmbd_services(BOOL test)
270 set_remote_machine_name("nmbd", False);
274 pstrcpy( fname,lp_configfile());
275 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
276 pstrcpy(dyn_CONFIGFILE,fname);
281 if ( test && !lp_file_list_changed() )
284 ret = lp_load( dyn_CONFIGFILE, True , False, False, True);
286 /* perhaps the config filename is now set */
288 DEBUG( 3, ( "services not loaded\n" ) );
289 reload_nmbd_services( True );
295 /**************************************************************************** **
296 * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
297 **************************************************************************** */
299 static void msg_reload_nmbd_services(int msg_type, struct process_id src,
300 void *buf, size_t len, void *private_data)
302 write_browse_list( 0, True );
303 dump_all_namelists();
304 reload_nmbd_services( True );
306 reload_interfaces(0);
309 static void msg_nmbd_send_packet(int msg_type, struct process_id src,
310 void *buf, size_t len, void *private_data)
312 struct packet_struct *p = (struct packet_struct *)buf;
313 struct subnet_record *subrec;
314 struct in_addr *local_ip;
316 DEBUG(10, ("Received send_packet from %d\n", procid_to_pid(&src)));
318 if (len != sizeof(struct packet_struct)) {
319 DEBUG(2, ("Discarding invalid packet length from %d\n",
320 procid_to_pid(&src)));
324 if ((p->packet_type != NMB_PACKET) &&
325 (p->packet_type != DGRAM_PACKET)) {
326 DEBUG(2, ("Discarding invalid packet type from %d: %d\n",
327 procid_to_pid(&src), p->packet_type));
331 local_ip = iface_ip(p->ip);
333 if (local_ip == NULL) {
334 DEBUG(2, ("Could not find ip for packet from %d\n",
335 procid_to_pid(&src)));
339 subrec = FIRST_SUBNET;
341 p->fd = (p->packet_type == NMB_PACKET) ?
342 subrec->nmb_sock : subrec->dgram_sock;
344 for (subrec = FIRST_SUBNET; subrec != NULL;
345 subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
346 if (ip_equal(*local_ip, subrec->myip)) {
347 p->fd = (p->packet_type == NMB_PACKET) ?
348 subrec->nmb_sock : subrec->dgram_sock;
353 if (p->packet_type == DGRAM_PACKET) {
355 p->packet.dgram.header.source_ip.s_addr = local_ip->s_addr;
356 p->packet.dgram.header.source_port = 138;
362 /**************************************************************************** **
363 The main select loop.
364 **************************************************************************** */
366 static void process(void)
371 time_t t = time(NULL);
373 /* Check for internal messages */
378 * Check all broadcast subnets to see if
379 * we need to run an election on any of them.
383 run_election = check_elections();
386 * Read incoming UDP packets.
390 if(listen_for_packets(run_election))
394 * Handle termination inband.
403 * Process all incoming packets
404 * read above. This calls the success and
405 * failure functions registered when response
406 * packets arrrive, and also deals with request
407 * packets from other sources.
414 * Run any elections - initiate becoming
415 * a local master browser if we have won.
422 * Send out any broadcast announcements
423 * of our server names. This also announces
424 * the workgroup name if we are a local
426 * (nmbd_sendannounce.c)
429 announce_my_server_names(t);
432 * Send out any LanMan broadcast announcements
433 * of our server names.
434 * (nmbd_sendannounce.c)
437 announce_my_lm_server_names(t);
440 * If we are a local master browser, periodically
441 * announce ourselves to the domain master browser.
442 * This also deals with syncronising the domain master
443 * browser server lists with ourselves as a local
445 * (nmbd_sendannounce.c)
448 announce_myself_to_domain_master_browser(t);
451 * Fullfill any remote announce requests.
452 * (nmbd_sendannounce.c)
458 * Fullfill any remote browse sync announce requests.
459 * (nmbd_sendannounce.c)
462 browse_sync_remote(t);
465 * Scan the broadcast subnets, and WINS client
466 * namelists and refresh any that need refreshing.
473 * Scan the subnet namelists and server lists and
474 * expire thos that have timed out.
478 expire_names_and_servers(t);
481 * Write out a snapshot of our current browse list into
482 * the browse.dat file. This is used by smbd to service
483 * incoming NetServerEnum calls - used to synchronise
484 * browse lists over subnets.
485 * (nmbd_serverlistdb.c)
488 write_browse_list(t, False);
491 * If we are a domain master browser, we have a list of
492 * local master browsers we should synchronise browse
493 * lists with (these are added by an incoming local
494 * master browser announcement packet). Expire any of
495 * these that are no longer current, and pull the server
496 * lists from each of these known local master browsers.
497 * (nmbd_browsesync.c)
500 dmb_expire_and_sync_browser_lists(t);
503 * Check that there is a local master browser for our
504 * workgroup for all our broadcast subnets. If one
505 * is not found, start an election (which we ourselves
506 * may or may not participate in, depending on the
507 * setting of the 'local master' parameter.
511 check_master_browser_exists(t);
514 * If we are configured as a logon server, attempt to
515 * register the special NetBIOS names to become such
516 * (WORKGROUP<1c> name) on all broadcast subnets and
517 * with the WINS server (if used). If we are configured
518 * to become a domain master browser, attempt to register
519 * the special NetBIOS name (WORKGROUP<1b> name) to
521 * (nmbd_become_dmb.c)
527 * If we are a WINS server, do any timer dependent
528 * processing required.
529 * (nmbd_winsserver.c)
532 initiate_wins_processing(t);
535 * If we are a domain master browser, attempt to contact the
536 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
537 * This will only work to a Samba WINS server.
538 * (nmbd_browsesync.c)
541 if (lp_enhanced_browsing())
542 collect_all_workgroup_names_from_wins_server(t);
545 * Go through the response record queue and time out or re-transmit
546 * and expired entries.
550 retransmit_or_expire_response_records(t);
553 * check to see if any remote browse sync child processes have completed
556 sync_check_completion();
559 * regularly sync with any other DMBs we know about
562 if (lp_enhanced_browsing())
566 * clear the unexpected packet queue
572 * Reload the services file if we got a sighup.
575 if(reload_after_sighup) {
576 DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
577 msg_reload_nmbd_services(MSG_SMB_CONF_UPDATED,
578 pid_to_procid(0), NULL, 0, NULL);
579 reload_after_sighup = 0;
582 /* check for new network interfaces */
584 reload_interfaces(t);
586 /* free up temp memory */
591 /**************************************************************************** **
592 Open the socket communication.
593 **************************************************************************** */
595 static BOOL open_sockets(BOOL isdaemon, int port)
598 * The sockets opened here will be used to receive broadcast
599 * packets *only*. Interface specific sockets are opened in
600 * make_subnet() in namedbsubnet.c. Thus we bind to the
601 * address "0.0.0.0". The parameter 'socket address' is
606 ClientNMB = open_socket_in(SOCK_DGRAM, port,
607 0, interpret_addr(lp_socket_address()),
612 ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
613 3, interpret_addr(lp_socket_address()),
616 if ( ClientNMB == -1 )
619 /* we are never interested in SIGPIPE */
620 BlockSignals(True,SIGPIPE);
622 set_socket_options( ClientNMB, "SO_BROADCAST" );
623 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
625 /* Ensure we're non-blocking. */
626 set_blocking( ClientNMB, False);
627 set_blocking( ClientDGRAM, False);
629 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
633 /**************************************************************************** **
635 **************************************************************************** */
636 int main(int argc, const char *argv[])
639 static BOOL opt_interactive;
641 static char *p_lmhosts = dyn_LMHOSTSFILE;
642 static BOOL no_process_group = False;
643 struct poptOption long_options[] = {
645 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon(default)" },
646 {"interactive", 'i', POPT_ARG_VAL, &opt_interactive, True, "Run interactive (not a daemon)" },
647 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
648 {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
649 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
650 {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 'H', "Load a netbios hosts file"},
651 {"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
658 global_nmb_port = NMB_PORT;
660 pc = poptGetContext("nmbd", argc, argv, long_options, 0);
661 while (poptGetNextOpt(pc) != -1) {};
664 global_in_nmbd = True;
666 StartupTime = time(NULL);
668 sys_srandom(time(NULL) ^ sys_getpid());
670 if (!override_logfile) {
671 slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
672 lp_set_logfile(logfile);
675 fault_setup((void (*)(void *))fault_continue );
676 dump_core_setup("nmbd");
678 /* POSIX demands that signals are inherited. If the invoking process has
679 * these signals masked, we will have problems, as we won't receive them. */
680 BlockSignals(False, SIGHUP);
681 BlockSignals(False, SIGUSR1);
682 BlockSignals(False, SIGTERM);
684 CatchSignal( SIGHUP, SIGNAL_CAST sig_hup );
685 CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
688 /* we are never interested in SIGFPE */
689 BlockSignals(True,SIGFPE);
692 /* We no longer use USR2... */
694 BlockSignals(True, SIGUSR2);
697 if ( opt_interactive ) {
702 if ( log_stdout && Fork ) {
703 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
707 setup_logging( argv[0], log_stdout );
711 DEBUG( 0, ( "Netbios nameserver version %s started.\n", SAMBA_VERSION_STRING) );
712 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
714 if ( !reload_nmbd_services(False) )
720 reload_nmbd_services( True );
722 if (strequal(lp_workgroup(),"*")) {
723 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
729 if (!is_daemon && !is_a_socket(0)) {
730 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
734 if (is_daemon && !opt_interactive) {
735 DEBUG( 2, ( "Becoming a daemon.\n" ) );
736 become_daemon(Fork, no_process_group);
741 * If we're interactive we want to set our own process group for
744 if (opt_interactive && !no_process_group)
745 setpgid( (pid_t)0, (pid_t)0 );
749 /* Setup the async dns. We do it here so it doesn't have all the other
750 stuff initialised and thus chewing memory and sockets */
751 if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
756 if (!directory_exist(lp_lockdir(), NULL)) {
757 mkdir(lp_lockdir(), 0755);
760 pidfile_create("nmbd");
762 message_register(MSG_FORCE_ELECTION, nmbd_message_election, NULL);
764 /* Until winsrepl is done. */
765 message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry, NULL);
767 message_register(MSG_SHUTDOWN, nmbd_terminate, NULL);
768 message_register(MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services, NULL);
769 message_register(MSG_SEND_PACKET, msg_nmbd_send_packet, NULL);
773 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
775 if ( !open_sockets( is_daemon, global_nmb_port ) ) {
776 kill_async_dns_child();
780 /* Determine all the IP addresses we have. */
783 /* Create an nmbd subnet record for each of the above. */
784 if( False == create_subnets() ) {
785 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
786 kill_async_dns_child();
790 /* Load in any static local names. */
791 load_lmhosts_file(p_lmhosts);
792 DEBUG(3,("Loaded hosts file %s\n", p_lmhosts));
794 /* If we are acting as a WINS server, initialise data structures. */
795 if( !initialise_wins() ) {
796 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
797 kill_async_dns_child();
802 * Register nmbd primary workgroup and nmbd names on all
803 * the broadcast subnets, and on the WINS server (if specified).
804 * Also initiate the startup of our primary workgroup (start
805 * elections if we are setup as being able to be a local
809 if( False == register_my_workgroup_and_names() ) {
810 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
811 kill_async_dns_child();
815 /* We can only take signals in the select. */
816 BlockSignals( True, SIGTERM );
822 kill_async_dns_child();