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
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 int global_nmb_port = -1;
29 extern pstring global_myname;
30 extern fstring global_myworkgroup;
31 extern char **my_netbios_names;
33 extern BOOL global_in_nmbd;
35 /* are we running as a daemon ? */
36 static BOOL is_daemon = False;
38 /* have we found LanMan clients yet? */
39 BOOL found_lm_clients = False;
41 /* what server type are we currently */
43 time_t StartupTime = 0;
45 /**************************************************************************** **
46 Handle a SIGTERM in band.
47 **************************************************************************** */
49 static void terminate(void)
51 DEBUG(0,("Got SIGTERM: going down...\n"));
53 /* Write out wins.dat file if samba is a WINS server */
54 wins_write_database(False);
56 /* Remove all SELF registered names from WINS */
59 /* Announce all server entries as 0 time-to-live, 0 type. */
60 announce_my_servers_removed();
62 /* If there was an async dns child - kill it. */
63 kill_async_dns_child();
68 /**************************************************************************** **
69 Handle a SHUTDOWN message from smbcontrol.
70 **************************************************************************** */
72 static void nmbd_terminate(int msg_type, pid_t src, void *buf, size_t len)
77 /**************************************************************************** **
78 Catch a SIGTERM signal.
79 **************************************************************************** */
81 static SIG_ATOMIC_T got_sig_term;
83 static void sig_term(int sig)
89 /**************************************************************************** **
90 Catch a SIGHUP signal.
91 **************************************************************************** */
93 static SIG_ATOMIC_T reload_after_sighup;
95 static void sig_hup(int sig)
97 reload_after_sighup = 1;
102 /**************************************************************************** **
103 Prepare to dump a core file - carefully!
104 **************************************************************************** */
106 static BOOL dump_core(void)
110 pstrcpy( dname, lp_logfile() );
111 if ((p=strrchr_m(dname,'/')))
113 pstrcat( dname, "/corefiles" );
114 mkdir( dname, 0700 );
115 sys_chown( dname, getuid(), getgid() );
116 chmod( dname, 0700 );
121 #ifdef HAVE_GETRLIMIT
125 getrlimit( RLIMIT_CORE, &rlp );
126 rlp.rlim_cur = MAX( 4*1024*1024, rlp.rlim_cur );
127 setrlimit( RLIMIT_CORE, &rlp );
128 getrlimit( RLIMIT_CORE, &rlp );
129 DEBUG( 3, ( "Core limits now %d %d\n", (int)rlp.rlim_cur, (int)rlp.rlim_max ) );
135 DEBUG(0,("Dumping core in %s\n",dname));
141 /**************************************************************************** **
142 Possibly continue after a fault.
143 **************************************************************************** */
145 static void fault_continue(void)
152 /**************************************************************************** **
153 Expire old names from the namelist and server list.
154 **************************************************************************** */
156 static void expire_names_and_servers(time_t t)
158 static time_t lastrun = 0;
162 if ( t < (lastrun + 5) )
167 * Expire any timed out names on all the broadcast
168 * subnets and those registered with the WINS server.
169 * (nmbd_namelistdb.c)
175 * Go through all the broadcast subnets and for each
176 * workgroup known on that subnet remove any expired
177 * server names. If a workgroup has an empty serverlist
178 * and has itself timed out then remove the workgroup.
179 * (nmbd_workgroupdb.c)
182 expire_workgroups_and_servers(t);
185 /************************************************************************** **
186 Reload the list of network interfaces.
187 ************************************************************************** */
189 static BOOL reload_interfaces(time_t t)
193 struct subnet_record *subrec;
194 extern BOOL rescan_listen_set;
195 extern struct in_addr loopback_ip;
197 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) return False;
200 if (!interfaces_changed()) return False;
202 /* the list of probed interfaces has changed, we may need to add/remove
206 /* find any interfaces that need adding */
207 for (n=iface_count() - 1; n >= 0; n--) {
208 struct interface *iface = get_interface(n);
211 * We don't want to add a loopback interface, in case
212 * someone has added 127.0.0.1 for smbd, nmbd needs to
213 * ignore it here. JRA.
216 if (ip_equal(iface->ip, loopback_ip)) {
217 DEBUG(2,("reload_interfaces: Ignoring loopback interface %s\n", inet_ntoa(iface->ip)));
221 for (subrec=subnetlist; subrec; subrec=subrec->next) {
222 if (ip_equal(iface->ip, subrec->myip) &&
223 ip_equal(iface->nmask, subrec->mask_ip)) break;
227 /* it wasn't found! add it */
228 DEBUG(2,("Found new interface %s\n",
229 inet_ntoa(iface->ip)));
230 subrec = make_normal_subnet(iface);
231 if (subrec) register_my_workgroup_one_subnet(subrec);
235 /* find any interfaces that need deleting */
236 for (subrec=subnetlist; subrec; subrec=subrec->next) {
237 for (n=iface_count() - 1; n >= 0; n--) {
238 struct interface *iface = get_interface(n);
239 if (ip_equal(iface->ip, subrec->myip) &&
240 ip_equal(iface->nmask, subrec->mask_ip)) break;
243 /* oops, an interface has disapeared. This is
244 tricky, we don't dare actually free the
245 interface as it could be being used, so
246 instead we just wear the memory leak and
247 remove it from the list of interfaces without
249 DEBUG(2,("Deleting dead interface %s\n",
250 inet_ntoa(subrec->myip)));
251 close_subnet(subrec);
255 rescan_listen_set = True;
257 /* We need to shutdown if there are no subnets... */
258 if (FIRST_SUBNET == NULL) {
259 DEBUG(0,("reload_interfaces: No subnets to listen to. Shutting down...\n"));
265 /**************************************************************************** **
266 Reload the services file.
267 **************************************************************************** */
269 static BOOL reload_nmbd_services(BOOL test)
272 extern fstring remote_machine;
274 fstrcpy( remote_machine, "nmbd" );
278 pstrcpy( fname,lp_configfile());
279 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
280 pstrcpy(dyn_CONFIGFILE,fname);
285 if ( test && !lp_file_list_changed() )
288 ret = lp_load( dyn_CONFIGFILE, True , False, False);
290 /* perhaps the config filename is now set */
292 DEBUG( 3, ( "services not loaded\n" ) );
293 reload_nmbd_services( True );
299 /**************************************************************************** **
300 The main select loop.
301 **************************************************************************** */
303 static void process(void)
308 time_t t = time(NULL);
310 /* Check for internal messages */
315 * Check all broadcast subnets to see if
316 * we need to run an election on any of them.
320 run_election = check_elections();
323 * Read incoming UDP packets.
327 if(listen_for_packets(run_election))
331 * Handle termination inband.
340 * Process all incoming packets
341 * read above. This calls the success and
342 * failure functions registered when response
343 * packets arrrive, and also deals with request
344 * packets from other sources.
351 * Run any elections - initiate becoming
352 * a local master browser if we have won.
359 * Send out any broadcast announcements
360 * of our server names. This also announces
361 * the workgroup name if we are a local
363 * (nmbd_sendannounce.c)
366 announce_my_server_names(t);
369 * Send out any LanMan broadcast announcements
370 * of our server names.
371 * (nmbd_sendannounce.c)
374 announce_my_lm_server_names(t);
377 * If we are a local master browser, periodically
378 * announce ourselves to the domain master browser.
379 * This also deals with syncronising the domain master
380 * browser server lists with ourselves as a local
382 * (nmbd_sendannounce.c)
385 announce_myself_to_domain_master_browser(t);
388 * Fullfill any remote announce requests.
389 * (nmbd_sendannounce.c)
395 * Fullfill any remote browse sync announce requests.
396 * (nmbd_sendannounce.c)
399 browse_sync_remote(t);
402 * Scan the broadcast subnets, and WINS client
403 * namelists and refresh any that need refreshing.
410 * Scan the subnet namelists and server lists and
411 * expire thos that have timed out.
415 expire_names_and_servers(t);
418 * Write out a snapshot of our current browse list into
419 * the browse.dat file. This is used by smbd to service
420 * incoming NetServerEnum calls - used to synchronise
421 * browse lists over subnets.
422 * (nmbd_serverlistdb.c)
425 write_browse_list(t, False);
428 * If we are a domain master browser, we have a list of
429 * local master browsers we should synchronise browse
430 * lists with (these are added by an incoming local
431 * master browser announcement packet). Expire any of
432 * these that are no longer current, and pull the server
433 * lists from each of these known local master browsers.
434 * (nmbd_browsesync.c)
437 dmb_expire_and_sync_browser_lists(t);
440 * Check that there is a local master browser for our
441 * workgroup for all our broadcast subnets. If one
442 * is not found, start an election (which we ourselves
443 * may or may not participate in, depending on the
444 * setting of the 'local master' parameter.
448 check_master_browser_exists(t);
451 * If we are configured as a logon server, attempt to
452 * register the special NetBIOS names to become such
453 * (WORKGROUP<1c> name) on all broadcast subnets and
454 * with the WINS server (if used). If we are configured
455 * to become a domain master browser, attempt to register
456 * the special NetBIOS name (WORKGROUP<1b> name) to
458 * (nmbd_become_dmb.c)
464 * If we are a WINS server, do any timer dependent
465 * processing required.
466 * (nmbd_winsserver.c)
469 initiate_wins_processing(t);
472 * If we are a domain master browser, attempt to contact the
473 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
474 * This will only work to a Samba WINS server.
475 * (nmbd_browsesync.c)
478 if (lp_enhanced_browsing())
479 collect_all_workgroup_names_from_wins_server(t);
482 * Go through the response record queue and time out or re-transmit
483 * and expired entries.
487 retransmit_or_expire_response_records(t);
490 * check to see if any remote browse sync child processes have completed
493 sync_check_completion();
496 * regularly sync with any other DMBs we know about
499 if (lp_enhanced_browsing())
503 * clear the unexpected packet queue
509 * Reload the services file if we got a sighup.
512 if(reload_after_sighup) {
513 DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
514 write_browse_list( 0, True );
515 dump_all_namelists();
516 reload_nmbd_services( True );
518 if(reload_interfaces(0))
520 reload_after_sighup = 0;
523 /* check for new network interfaces */
525 if(reload_interfaces(t))
528 /* free up temp memory */
533 /**************************************************************************** **
534 Open the socket communication.
535 **************************************************************************** */
537 static BOOL open_sockets(BOOL isdaemon, int port)
540 * The sockets opened here will be used to receive broadcast
541 * packets *only*. Interface specific sockets are opened in
542 * make_subnet() in namedbsubnet.c. Thus we bind to the
543 * address "0.0.0.0". The parameter 'socket address' is
548 ClientNMB = open_socket_in(SOCK_DGRAM, port,0,0,True);
552 ClientDGRAM = open_socket_in(SOCK_DGRAM,DGRAM_PORT,3,0,True);
554 if ( ClientNMB == -1 )
557 /* we are never interested in SIGPIPE */
558 BlockSignals(True,SIGPIPE);
560 set_socket_options( ClientNMB, "SO_BROADCAST" );
561 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
563 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
567 /**************************************************************************** **
568 Initialise connect, service and file structs.
569 **************************************************************************** */
571 static BOOL init_structs(void)
573 extern fstring local_machine;
580 if (! *global_myname)
582 fstrcpy( global_myname, myhostname() );
583 p = strchr_m( global_myname, '.' );
587 strupper( global_myname );
589 /* Add any NETBIOS name aliases. Ensure that the first entry
590 is equal to global_myname.
592 /* Work out the max number of netbios aliases that we have */
593 ptr = lp_netbios_aliases();
596 for( ; *ptr; namecount++,ptr++ )
598 if ( *global_myname )
601 /* Allocate space for the netbios aliases */
602 my_netbios_names = (char **)malloc( sizeof(char *) * (namecount+1) );
603 if( NULL == my_netbios_names )
605 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
609 /* Use the global_myname string first */
611 if ( *global_myname )
612 my_netbios_names[namecount++] = global_myname;
614 ptr = lp_netbios_aliases();
619 nbname = strdup(*ptr);
622 DEBUG(0,("init_structs: malloc fail when allocating names.\n"));
626 /* Look for duplicates */
628 for( n=0; n<namecount; n++ )
630 if( 0 == strcmp( nbname, my_netbios_names[n] ) )
634 my_netbios_names[namecount++] = nbname;
642 /* Terminate name list */
643 my_netbios_names[namecount++] = NULL;
645 fstrcpy( local_machine, global_myname );
646 trim_string( local_machine, " ", " " );
647 p = strchr_m( local_machine, ' ' );
650 strlower( local_machine );
652 DEBUG( 5, ("Netbios name list:-\n") );
653 for( n=0; my_netbios_names[n]; n++ )
654 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names[n] ) );
659 /**************************************************************************** **
660 Usage on the program.
661 **************************************************************************** */
663 static void usage(char *pname)
666 printf( "Usage: %s [-DaiohV] [-H lmhosts file] [-d debuglevel] [-l log basename]\n", pname );
667 printf( " [-n name] [-p port] [-s configuration file]\n" );
668 printf( "\t-D Become a daemon (default)\n" );
669 printf( "\t-a Append to log file (default)\n" );
670 printf( "\t-i Run interactive (not a daemon)\n" );
671 printf( "\t-o Overwrite log file, don't append\n" );
672 printf( "\t-h Print usage\n" );
673 printf( "\t-V Print version\n" );
674 printf( "\t-H hosts file Load a netbios hosts file\n" );
675 printf( "\t-d debuglevel Set the debuglevel\n" );
676 printf( "\t-l log basename. Basename for log/debug files\n" );
677 printf( "\t-n netbiosname. Primary netbios name\n" );
678 printf( "\t-p port Listen on the specified port\n" );
679 printf( "\t-s configuration file Configuration file name\n" );
684 /**************************************************************************** **
686 **************************************************************************** */
687 int main(int argc,char *argv[])
691 extern BOOL append_log;
692 BOOL opt_interactive = False;
695 append_log = True; /* Default, override with '-o' option. */
697 global_nmb_port = NMB_PORT;
698 global_in_nmbd = True;
700 StartupTime = time(NULL);
702 sys_srandom(time(NULL) ^ sys_getpid());
704 slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
705 lp_set_logfile(logfile);
707 /* this is for people who can't start the program correctly */
708 while (argc > 1 && (*argv[1] != '-'))
714 fault_setup((void (*)(void *))fault_continue );
716 /* POSIX demands that signals are inherited. If the invoking process has
717 * these signals masked, we will have problems, as we won't recieve them. */
718 BlockSignals(False, SIGHUP);
719 BlockSignals(False, SIGUSR1);
720 BlockSignals(False, SIGTERM);
722 CatchSignal( SIGHUP, SIGNAL_CAST sig_hup );
723 CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
726 /* we are never interested in SIGFPE */
727 BlockSignals(True,SIGFPE);
730 /* We no longer use USR2... */
732 BlockSignals(True, SIGUSR2);
736 (opt = getopt( argc, argv, "Vaos:T:I:C:bAB:N:Rn:l:d:Dp:hSH:G:f:i" )) )
741 pstrcpy(dyn_CONFIGFILE, optarg);
748 DEBUG(0,("Obsolete option '%c' used\n",opt));
751 opt_interactive = True;
754 pstrcpy(dyn_LMHOSTSFILE, optarg);
757 pstrcpy(global_myname,optarg);
758 strupper(global_myname);
761 slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", optarg);
762 lp_set_logfile(logfile);
774 DEBUGLEVEL = atoi(optarg);
777 global_nmb_port = atoi(optarg);
784 printf( "Version %s\n", VERSION );
788 if( !is_a_socket(0) )
790 DEBUG(0,("Incorrect program usage - is the command line correct?\n"));
798 setup_logging( argv[0], opt_interactive );
802 DEBUG( 0, ( "Netbios nameserver version %s started.\n", VERSION ) );
803 DEBUGADD( 0, ( "Copyright Andrew Tridgell and the Samba Team 1994-2002\n" ) );
805 if ( !reload_nmbd_services(False) )
811 reload_nmbd_services( True );
813 fstrcpy( global_myworkgroup, lp_workgroup() );
815 if (strequal(global_myworkgroup,"*"))
817 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
823 if (!is_daemon && !is_a_socket(0))
825 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
829 if (is_daemon && !opt_interactive)
831 DEBUG( 2, ( "Becoming a daemon.\n" ) );
837 * If we're interactive we want to set our own process group for
841 setpgid( (pid_t)0, (pid_t)0 );
845 /* Setup the async dns. We do it here so it doesn't have all the other
846 stuff initialised and thus chewing memory and sockets */
847 if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
852 if (!directory_exist(lp_lockdir(), NULL)) {
853 mkdir(lp_lockdir(), 0755);
856 pidfile_create("nmbd");
858 message_register(MSG_FORCE_ELECTION, nmbd_message_election);
859 message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
860 message_register(MSG_SHUTDOWN, nmbd_terminate);
862 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
864 if ( !open_sockets( is_daemon, global_nmb_port ) ) {
865 kill_async_dns_child();
869 /* Determine all the IP addresses we have. */
872 /* Create an nmbd subnet record for each of the above. */
873 if( False == create_subnets() )
875 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
876 kill_async_dns_child();
880 /* Load in any static local names. */
881 load_lmhosts_file(dyn_LMHOSTSFILE);
882 DEBUG(3,("Loaded hosts file %s\n", dyn_LMHOSTSFILE));
884 /* If we are acting as a WINS server, initialise data structures. */
885 if( !initialise_wins() )
887 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
888 kill_async_dns_child();
893 * Register nmbd primary workgroup and nmbd names on all
894 * the broadcast subnets, and on the WINS server (if specified).
895 * Also initiate the startup of our primary workgroup (start
896 * elections if we are setup as being able to be a local
900 if( False == register_my_workgroup_and_names() )
902 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
903 kill_async_dns_child();
907 /* We can only take signals in the select. */
908 BlockSignals( True, SIGTERM );
914 kill_async_dns_child();