r395: BUG 1232: patch from landonf@opendarwin.org (Landon Fuller) to fix
[Samba/gebeck_regimport.git] / source / nmbd / nmbd.c
blob880de7f91bf26ce4a318c0ff8934a508aa3e4e34
1 /*
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.
24 #include "includes.h"
26 int ClientNMB = -1;
27 int ClientDGRAM = -1;
28 int global_nmb_port = -1;
30 extern BOOL global_in_nmbd;
32 /* are we running as a daemon ? */
33 static BOOL is_daemon;
35 /* fork or run in foreground ? */
36 static BOOL Fork = True;
38 /* log to standard output ? */
39 static BOOL log_stdout;
41 /* have we found LanMan clients yet? */
42 BOOL found_lm_clients = False;
44 /* what server type are we currently */
46 time_t StartupTime = 0;
48 /**************************************************************************** **
49 Handle a SIGTERM in band.
50 **************************************************************************** */
52 static void terminate(void)
54 DEBUG(0,("Got SIGTERM: going down...\n"));
56 /* Write out wins.dat file if samba is a WINS server */
57 wins_write_database(False);
59 /* Remove all SELF registered names from WINS */
60 release_wins_names();
62 /* Announce all server entries as 0 time-to-live, 0 type. */
63 announce_my_servers_removed();
65 /* If there was an async dns child - kill it. */
66 kill_async_dns_child();
68 exit(0);
71 /**************************************************************************** **
72 Handle a SHUTDOWN message from smbcontrol.
73 **************************************************************************** */
75 static void nmbd_terminate(int msg_type, pid_t src, void *buf, size_t len)
77 terminate();
80 /**************************************************************************** **
81 Catch a SIGTERM signal.
82 **************************************************************************** */
84 static SIG_ATOMIC_T got_sig_term;
86 static void sig_term(int sig)
88 got_sig_term = 1;
89 sys_select_signal();
92 /**************************************************************************** **
93 Catch a SIGHUP signal.
94 **************************************************************************** */
96 static SIG_ATOMIC_T reload_after_sighup;
98 static void sig_hup(int sig)
100 reload_after_sighup = 1;
101 sys_select_signal();
104 #if DUMP_CORE
105 /**************************************************************************** **
106 Prepare to dump a core file - carefully!
107 **************************************************************************** */
109 static BOOL dump_core(void)
111 char *p;
112 pstring dname;
113 pstrcpy( dname, lp_logfile() );
114 if ((p=strrchr_m(dname,'/')))
115 *p=0;
116 pstrcat( dname, "/corefiles" );
117 mkdir( dname, 0700 );
118 sys_chown( dname, getuid(), getgid() );
119 chmod( dname, 0700 );
120 if ( chdir(dname) )
121 return( False );
122 umask( ~(0700) );
124 #ifdef HAVE_GETRLIMIT
125 #ifdef RLIMIT_CORE
127 struct rlimit rlp;
128 getrlimit( RLIMIT_CORE, &rlp );
129 rlp.rlim_cur = MAX( 4*1024*1024, rlp.rlim_cur );
130 setrlimit( RLIMIT_CORE, &rlp );
131 getrlimit( RLIMIT_CORE, &rlp );
132 DEBUG( 3, ( "Core limits now %d %d\n", (int)rlp.rlim_cur, (int)rlp.rlim_max ) );
134 #endif
135 #endif
138 DEBUG(0,("Dumping core in %s\n",dname));
139 abort();
140 return( True );
142 #endif
144 /**************************************************************************** **
145 Possibly continue after a fault.
146 **************************************************************************** */
148 static void fault_continue(void)
150 #if DUMP_CORE
151 dump_core();
152 #endif
155 /**************************************************************************** **
156 Expire old names from the namelist and server list.
157 **************************************************************************** */
159 static void expire_names_and_servers(time_t t)
161 static time_t lastrun = 0;
163 if ( !lastrun )
164 lastrun = t;
165 if ( t < (lastrun + 5) )
166 return;
167 lastrun = t;
170 * Expire any timed out names on all the broadcast
171 * subnets and those registered with the WINS server.
172 * (nmbd_namelistdb.c)
175 expire_names(t);
178 * Go through all the broadcast subnets and for each
179 * workgroup known on that subnet remove any expired
180 * server names. If a workgroup has an empty serverlist
181 * and has itself timed out then remove the workgroup.
182 * (nmbd_workgroupdb.c)
185 expire_workgroups_and_servers(t);
188 /************************************************************************** **
189 Reload the list of network interfaces.
190 ************************************************************************** */
192 static BOOL reload_interfaces(time_t t)
194 static time_t lastt;
195 int n;
196 struct subnet_record *subrec;
197 extern BOOL rescan_listen_set;
198 extern struct in_addr loopback_ip;
200 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) return False;
201 lastt = t;
203 if (!interfaces_changed()) return False;
205 /* the list of probed interfaces has changed, we may need to add/remove
206 some subnets */
207 load_interfaces();
209 /* find any interfaces that need adding */
210 for (n=iface_count() - 1; n >= 0; n--) {
211 struct interface *iface = get_interface(n);
214 * We don't want to add a loopback interface, in case
215 * someone has added 127.0.0.1 for smbd, nmbd needs to
216 * ignore it here. JRA.
219 if (ip_equal(iface->ip, loopback_ip)) {
220 DEBUG(2,("reload_interfaces: Ignoring loopback interface %s\n", inet_ntoa(iface->ip)));
221 continue;
224 for (subrec=subnetlist; subrec; subrec=subrec->next) {
225 if (ip_equal(iface->ip, subrec->myip) &&
226 ip_equal(iface->nmask, subrec->mask_ip)) break;
229 if (!subrec) {
230 /* it wasn't found! add it */
231 DEBUG(2,("Found new interface %s\n",
232 inet_ntoa(iface->ip)));
233 subrec = make_normal_subnet(iface);
234 if (subrec)
235 register_my_workgroup_one_subnet(subrec);
239 /* find any interfaces that need deleting */
240 for (subrec=subnetlist; subrec; subrec=subrec->next) {
241 for (n=iface_count() - 1; n >= 0; n--) {
242 struct interface *iface = get_interface(n);
243 if (ip_equal(iface->ip, subrec->myip) &&
244 ip_equal(iface->nmask, subrec->mask_ip)) break;
246 if (n == -1) {
247 /* oops, an interface has disapeared. This is
248 tricky, we don't dare actually free the
249 interface as it could be being used, so
250 instead we just wear the memory leak and
251 remove it from the list of interfaces without
252 freeing it */
253 DEBUG(2,("Deleting dead interface %s\n",
254 inet_ntoa(subrec->myip)));
255 close_subnet(subrec);
259 rescan_listen_set = True;
261 /* We need to shutdown if there are no subnets... */
262 if (FIRST_SUBNET == NULL) {
263 DEBUG(0,("reload_interfaces: No subnets to listen to. Shutting down...\n"));
264 return True;
266 return False;
269 /**************************************************************************** **
270 Reload the services file.
271 **************************************************************************** */
273 static BOOL reload_nmbd_services(BOOL test)
275 BOOL ret;
277 set_remote_machine_name("nmbd", False);
279 if ( lp_loaded() ) {
280 pstring fname;
281 pstrcpy( fname,lp_configfile());
282 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
283 pstrcpy(dyn_CONFIGFILE,fname);
284 test = False;
288 if ( test && !lp_file_list_changed() )
289 return(True);
291 ret = lp_load( dyn_CONFIGFILE, True , False, False);
293 /* perhaps the config filename is now set */
294 if ( !test ) {
295 DEBUG( 3, ( "services not loaded\n" ) );
296 reload_nmbd_services( True );
299 return(ret);
302 /**************************************************************************** **
303 * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
304 * We use buf here to return BOOL result to process() when reload_interfaces()
305 * detects that there are no subnets.
306 **************************************************************************** */
308 static void msg_reload_nmbd_services(int msg_type, pid_t src, void *buf, size_t len)
310 write_browse_list( 0, True );
311 dump_all_namelists();
312 reload_nmbd_services( True );
313 reopen_logs();
315 if(buf) {
316 /* We were called from process() */
317 /* If reload_interfaces() returned True */
318 /* we need to shutdown if there are no subnets... */
319 /* pass this info back to process() */
320 *((BOOL*)buf) = reload_interfaces(0);
325 /**************************************************************************** **
326 The main select loop.
327 **************************************************************************** */
329 static void process(void)
331 BOOL run_election;
332 BOOL no_subnets;
334 while( True ) {
335 time_t t = time(NULL);
337 /* Check for internal messages */
339 message_dispatch();
342 * Check all broadcast subnets to see if
343 * we need to run an election on any of them.
344 * (nmbd_elections.c)
347 run_election = check_elections();
350 * Read incoming UDP packets.
351 * (nmbd_packets.c)
354 if(listen_for_packets(run_election))
355 return;
358 * Handle termination inband.
361 if (got_sig_term) {
362 got_sig_term = 0;
363 terminate();
367 * Process all incoming packets
368 * read above. This calls the success and
369 * failure functions registered when response
370 * packets arrrive, and also deals with request
371 * packets from other sources.
372 * (nmbd_packets.c)
375 run_packet_queue();
378 * Run any elections - initiate becoming
379 * a local master browser if we have won.
380 * (nmbd_elections.c)
383 run_elections(t);
386 * Send out any broadcast announcements
387 * of our server names. This also announces
388 * the workgroup name if we are a local
389 * master browser.
390 * (nmbd_sendannounce.c)
393 announce_my_server_names(t);
396 * Send out any LanMan broadcast announcements
397 * of our server names.
398 * (nmbd_sendannounce.c)
401 announce_my_lm_server_names(t);
404 * If we are a local master browser, periodically
405 * announce ourselves to the domain master browser.
406 * This also deals with syncronising the domain master
407 * browser server lists with ourselves as a local
408 * master browser.
409 * (nmbd_sendannounce.c)
412 announce_myself_to_domain_master_browser(t);
415 * Fullfill any remote announce requests.
416 * (nmbd_sendannounce.c)
419 announce_remote(t);
422 * Fullfill any remote browse sync announce requests.
423 * (nmbd_sendannounce.c)
426 browse_sync_remote(t);
429 * Scan the broadcast subnets, and WINS client
430 * namelists and refresh any that need refreshing.
431 * (nmbd_mynames.c)
434 refresh_my_names(t);
437 * Scan the subnet namelists and server lists and
438 * expire thos that have timed out.
439 * (nmbd.c)
442 expire_names_and_servers(t);
445 * Write out a snapshot of our current browse list into
446 * the browse.dat file. This is used by smbd to service
447 * incoming NetServerEnum calls - used to synchronise
448 * browse lists over subnets.
449 * (nmbd_serverlistdb.c)
452 write_browse_list(t, False);
455 * If we are a domain master browser, we have a list of
456 * local master browsers we should synchronise browse
457 * lists with (these are added by an incoming local
458 * master browser announcement packet). Expire any of
459 * these that are no longer current, and pull the server
460 * lists from each of these known local master browsers.
461 * (nmbd_browsesync.c)
464 dmb_expire_and_sync_browser_lists(t);
467 * Check that there is a local master browser for our
468 * workgroup for all our broadcast subnets. If one
469 * is not found, start an election (which we ourselves
470 * may or may not participate in, depending on the
471 * setting of the 'local master' parameter.
472 * (nmbd_elections.c)
475 check_master_browser_exists(t);
478 * If we are configured as a logon server, attempt to
479 * register the special NetBIOS names to become such
480 * (WORKGROUP<1c> name) on all broadcast subnets and
481 * with the WINS server (if used). If we are configured
482 * to become a domain master browser, attempt to register
483 * the special NetBIOS name (WORKGROUP<1b> name) to
484 * become such.
485 * (nmbd_become_dmb.c)
488 add_domain_names(t);
491 * If we are a WINS server, do any timer dependent
492 * processing required.
493 * (nmbd_winsserver.c)
496 initiate_wins_processing(t);
499 * If we are a domain master browser, attempt to contact the
500 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
501 * This will only work to a Samba WINS server.
502 * (nmbd_browsesync.c)
505 if (lp_enhanced_browsing())
506 collect_all_workgroup_names_from_wins_server(t);
509 * Go through the response record queue and time out or re-transmit
510 * and expired entries.
511 * (nmbd_packets.c)
514 retransmit_or_expire_response_records(t);
517 * check to see if any remote browse sync child processes have completed
520 sync_check_completion();
523 * regularly sync with any other DMBs we know about
526 if (lp_enhanced_browsing())
527 sync_all_dmbs(t);
530 * clear the unexpected packet queue
533 clear_unexpected(t);
536 * Reload the services file if we got a sighup.
539 if(reload_after_sighup) {
540 DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
541 msg_reload_nmbd_services(MSG_SMB_CONF_UPDATED, (pid_t) 0, (void*) &no_subnets, 0);
542 if(no_subnets)
543 return;
544 reload_after_sighup = 0;
547 /* check for new network interfaces */
549 if(reload_interfaces(t))
550 return;
552 /* free up temp memory */
553 lp_talloc_free();
557 /**************************************************************************** **
558 Open the socket communication.
559 **************************************************************************** */
561 static BOOL open_sockets(BOOL isdaemon, int port)
564 * The sockets opened here will be used to receive broadcast
565 * packets *only*. Interface specific sockets are opened in
566 * make_subnet() in namedbsubnet.c. Thus we bind to the
567 * address "0.0.0.0". The parameter 'socket address' is
568 * now deprecated.
571 if ( isdaemon )
572 ClientNMB = open_socket_in(SOCK_DGRAM, port,
573 0, interpret_addr(lp_socket_address()),
574 True);
575 else
576 ClientNMB = 0;
578 ClientDGRAM = open_socket_in(SOCK_DGRAM,DGRAM_PORT,3,0,True);
580 if ( ClientNMB == -1 )
581 return( False );
583 /* we are never interested in SIGPIPE */
584 BlockSignals(True,SIGPIPE);
586 set_socket_options( ClientNMB, "SO_BROADCAST" );
587 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
589 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
590 return( True );
593 /**************************************************************************** **
594 main program
595 **************************************************************************** */
596 int main(int argc, const char *argv[])
598 pstring logfile;
599 static BOOL opt_interactive;
600 poptContext pc;
601 int opt;
602 struct poptOption long_options[] = {
603 POPT_AUTOHELP
604 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon(default)" },
605 {"interactive", 'i', POPT_ARG_VAL, &opt_interactive, True, "Run interactive (not a daemon)" },
606 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
607 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
608 {"hosts", 'H', POPT_ARG_STRING, dyn_LMHOSTSFILE, 'H', "Load a netbios hosts file"},
609 {"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
610 POPT_COMMON_SAMBA
611 { NULL }
614 global_nmb_port = NMB_PORT;
616 pc = poptGetContext("nmbd", argc, argv, long_options, 0);
617 while ((opt = poptGetNextOpt(pc)) != -1) ;
618 poptFreeContext(pc);
620 global_in_nmbd = True;
622 StartupTime = time(NULL);
624 sys_srandom(time(NULL) ^ sys_getpid());
626 slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
627 lp_set_logfile(logfile);
629 fault_setup((void (*)(void *))fault_continue );
631 /* POSIX demands that signals are inherited. If the invoking process has
632 * these signals masked, we will have problems, as we won't receive them. */
633 BlockSignals(False, SIGHUP);
634 BlockSignals(False, SIGUSR1);
635 BlockSignals(False, SIGTERM);
637 CatchSignal( SIGHUP, SIGNAL_CAST sig_hup );
638 CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
640 #if defined(SIGFPE)
641 /* we are never interested in SIGFPE */
642 BlockSignals(True,SIGFPE);
643 #endif
645 /* We no longer use USR2... */
646 #if defined(SIGUSR2)
647 BlockSignals(True, SIGUSR2);
648 #endif
650 if ( opt_interactive ) {
651 Fork = False;
652 log_stdout = True;
655 if ( log_stdout && Fork ) {
656 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
657 exit(1);
660 setup_logging( argv[0], log_stdout );
662 reopen_logs();
664 DEBUG( 0, ( "Netbios nameserver version %s started.\n", SAMBA_VERSION_STRING) );
665 DEBUGADD( 0, ( "Copyright Andrew Tridgell and the Samba Team 1994-2004\n" ) );
667 if ( !reload_nmbd_services(False) )
668 return(-1);
670 if(!init_names())
671 return -1;
673 reload_nmbd_services( True );
675 if (strequal(lp_workgroup(),"*")) {
676 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
677 exit(1);
680 set_samba_nb_type();
682 if (!is_daemon && !is_a_socket(0)) {
683 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
684 is_daemon = True;
687 if (is_daemon && !opt_interactive) {
688 DEBUG( 2, ( "Becoming a daemon.\n" ) );
689 become_daemon(Fork);
692 #if HAVE_SETPGID
694 * If we're interactive we want to set our own process group for
695 * signal management.
697 if (opt_interactive)
698 setpgid( (pid_t)0, (pid_t)0 );
699 #endif
701 #ifndef SYNC_DNS
702 /* Setup the async dns. We do it here so it doesn't have all the other
703 stuff initialised and thus chewing memory and sockets */
704 if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
705 start_async_dns();
707 #endif
709 if (!directory_exist(lp_lockdir(), NULL)) {
710 mkdir(lp_lockdir(), 0755);
713 pidfile_create("nmbd");
714 message_init();
715 message_register(MSG_FORCE_ELECTION, nmbd_message_election);
716 message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
717 message_register(MSG_SHUTDOWN, nmbd_terminate);
718 message_register(MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services);
720 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
722 if ( !open_sockets( is_daemon, global_nmb_port ) ) {
723 kill_async_dns_child();
724 return 1;
727 /* Determine all the IP addresses we have. */
728 load_interfaces();
730 /* Create an nmbd subnet record for each of the above. */
731 if( False == create_subnets() ) {
732 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
733 kill_async_dns_child();
734 exit(1);
737 /* Load in any static local names. */
738 load_lmhosts_file(dyn_LMHOSTSFILE);
739 DEBUG(3,("Loaded hosts file %s\n", dyn_LMHOSTSFILE));
741 /* If we are acting as a WINS server, initialise data structures. */
742 if( !initialise_wins() ) {
743 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
744 kill_async_dns_child();
745 exit(1);
749 * Register nmbd primary workgroup and nmbd names on all
750 * the broadcast subnets, and on the WINS server (if specified).
751 * Also initiate the startup of our primary workgroup (start
752 * elections if we are setup as being able to be a local
753 * master browser.
756 if( False == register_my_workgroup_and_names() ) {
757 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
758 kill_async_dns_child();
759 exit(1);
762 /* We can only take signals in the select. */
763 BlockSignals( True, SIGTERM );
765 process();
767 if (dbf)
768 x_fclose(dbf);
769 kill_async_dns_child();
770 return(0);