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 /* have we found LanMan clients yet? */
37 BOOL found_lm_clients = False;
39 /* what server type are we currently */
41 time_t StartupTime = 0;
43 /**************************************************************************** **
44 Handle a SIGTERM in band.
45 **************************************************************************** */
47 static void terminate(void)
49 DEBUG(0,("Got SIGTERM: going down...\n"));
51 /* Write out wins.dat file if samba is a WINS server */
52 wins_write_database(0,False);
54 /* Remove all SELF registered names from WINS */
57 /* Announce all server entries as 0 time-to-live, 0 type. */
58 announce_my_servers_removed();
60 /* If there was an async dns child - kill it. */
61 kill_async_dns_child();
66 /**************************************************************************** **
67 Handle a SHUTDOWN message from smbcontrol.
68 **************************************************************************** */
70 static void nmbd_terminate(int msg_type, struct server_id src,
71 void *buf, size_t len, void *private_data)
76 /**************************************************************************** **
77 Catch a SIGTERM signal.
78 **************************************************************************** */
80 static SIG_ATOMIC_T got_sig_term;
82 static void sig_term(int sig)
85 sys_select_signal(SIGTERM);
88 /**************************************************************************** **
89 Catch a SIGHUP signal.
90 **************************************************************************** */
92 static SIG_ATOMIC_T reload_after_sighup;
94 static void sig_hup(int sig)
96 reload_after_sighup = 1;
97 sys_select_signal(SIGHUP);
100 /**************************************************************************** **
101 Possibly continue after a fault.
102 **************************************************************************** */
104 static void fault_continue(void)
109 /**************************************************************************** **
110 Expire old names from the namelist and server list.
111 **************************************************************************** */
113 static void expire_names_and_servers(time_t t)
115 static time_t lastrun = 0;
119 if ( t < (lastrun + 5) )
124 * Expire any timed out names on all the broadcast
125 * subnets and those registered with the WINS server.
126 * (nmbd_namelistdb.c)
132 * Go through all the broadcast subnets and for each
133 * workgroup known on that subnet remove any expired
134 * server names. If a workgroup has an empty serverlist
135 * and has itself timed out then remove the workgroup.
136 * (nmbd_workgroupdb.c)
139 expire_workgroups_and_servers(t);
142 /************************************************************************** **
143 Reload the list of network interfaces.
144 ************************************************************************** */
146 static BOOL reload_interfaces(time_t t)
150 struct subnet_record *subrec;
152 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) return False;
155 if (!interfaces_changed()) return False;
157 /* the list of probed interfaces has changed, we may need to add/remove
161 /* find any interfaces that need adding */
162 for (n=iface_count() - 1; n >= 0; n--) {
163 struct interface *iface = get_interface(n);
166 DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
171 * We don't want to add a loopback interface, in case
172 * someone has added 127.0.0.1 for smbd, nmbd needs to
173 * ignore it here. JRA.
176 if (ip_equal(iface->ip, loopback_ip)) {
177 DEBUG(2,("reload_interfaces: Ignoring loopback interface %s\n", inet_ntoa(iface->ip)));
181 for (subrec=subnetlist; subrec; subrec=subrec->next) {
182 if (ip_equal(iface->ip, subrec->myip) &&
183 ip_equal(iface->nmask, subrec->mask_ip)) break;
187 /* it wasn't found! add it */
188 DEBUG(2,("Found new interface %s\n",
189 inet_ntoa(iface->ip)));
190 subrec = make_normal_subnet(iface);
192 register_my_workgroup_one_subnet(subrec);
196 /* find any interfaces that need deleting */
197 for (subrec=subnetlist; subrec; subrec=subrec->next) {
198 for (n=iface_count() - 1; n >= 0; n--) {
199 struct interface *iface = get_interface(n);
200 if (ip_equal(iface->ip, subrec->myip) &&
201 ip_equal(iface->nmask, subrec->mask_ip)) break;
204 /* oops, an interface has disapeared. This is
205 tricky, we don't dare actually free the
206 interface as it could be being used, so
207 instead we just wear the memory leak and
208 remove it from the list of interfaces without
210 DEBUG(2,("Deleting dead interface %s\n",
211 inet_ntoa(subrec->myip)));
212 close_subnet(subrec);
216 rescan_listen_set = True;
218 /* We need to shutdown if there are no subnets... */
219 if (FIRST_SUBNET == NULL) {
220 DEBUG(0,("reload_interfaces: No subnets to listen to. Shutting down...\n"));
226 /**************************************************************************** **
227 Reload the services file.
228 **************************************************************************** */
230 static BOOL reload_nmbd_services(BOOL test)
234 set_remote_machine_name("nmbd", False);
238 pstrcpy( fname,lp_configfile());
239 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
240 pstrcpy(dyn_CONFIGFILE,fname);
245 if ( test && !lp_file_list_changed() )
248 ret = lp_load( dyn_CONFIGFILE, True , False, False, True);
250 /* perhaps the config filename is now set */
252 DEBUG( 3, ( "services not loaded\n" ) );
253 reload_nmbd_services( True );
259 /**************************************************************************** **
260 * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
261 * We use buf here to return BOOL result to process() when reload_interfaces()
262 * detects that there are no subnets.
263 **************************************************************************** */
265 static void msg_reload_nmbd_services(int msg_type, struct server_id src,
266 void *buf, size_t len, void *private_data)
268 write_browse_list( 0, True );
269 dump_all_namelists();
270 reload_nmbd_services( True );
274 /* We were called from process() */
275 /* If reload_interfaces() returned True */
276 /* we need to shutdown if there are no subnets... */
277 /* pass this info back to process() */
278 *((BOOL*)buf) = reload_interfaces(0);
282 static void msg_nmbd_send_packet(int msg_type, struct server_id src,
283 void *buf, size_t len, void *private_data)
285 struct packet_struct *p = (struct packet_struct *)buf;
286 struct subnet_record *subrec;
287 struct in_addr *local_ip;
289 DEBUG(10, ("Received send_packet from %d\n", procid_to_pid(&src)));
291 if (len != sizeof(struct packet_struct)) {
292 DEBUG(2, ("Discarding invalid packet length from %d\n",
293 procid_to_pid(&src)));
297 if ((p->packet_type != NMB_PACKET) &&
298 (p->packet_type != DGRAM_PACKET)) {
299 DEBUG(2, ("Discarding invalid packet type from %d: %d\n",
300 procid_to_pid(&src), p->packet_type));
304 local_ip = iface_ip(p->ip);
306 if (local_ip == NULL) {
307 DEBUG(2, ("Could not find ip for packet from %d\n",
308 procid_to_pid(&src)));
312 subrec = FIRST_SUBNET;
314 p->fd = (p->packet_type == NMB_PACKET) ?
315 subrec->nmb_sock : subrec->dgram_sock;
317 for (subrec = FIRST_SUBNET; subrec != NULL;
318 subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
319 if (ip_equal(*local_ip, subrec->myip)) {
320 p->fd = (p->packet_type == NMB_PACKET) ?
321 subrec->nmb_sock : subrec->dgram_sock;
326 if (p->packet_type == DGRAM_PACKET) {
328 p->packet.dgram.header.source_ip.s_addr = local_ip->s_addr;
329 p->packet.dgram.header.source_port = 138;
335 /**************************************************************************** **
336 The main select loop.
337 **************************************************************************** */
339 static void process(void)
345 time_t t = time(NULL);
347 /* Check for internal messages */
352 * Check all broadcast subnets to see if
353 * we need to run an election on any of them.
357 run_election = check_elections();
360 * Read incoming UDP packets.
364 if(listen_for_packets(run_election))
368 * Handle termination inband.
377 * Process all incoming packets
378 * read above. This calls the success and
379 * failure functions registered when response
380 * packets arrrive, and also deals with request
381 * packets from other sources.
388 * Run any elections - initiate becoming
389 * a local master browser if we have won.
396 * Send out any broadcast announcements
397 * of our server names. This also announces
398 * the workgroup name if we are a local
400 * (nmbd_sendannounce.c)
403 announce_my_server_names(t);
406 * Send out any LanMan broadcast announcements
407 * of our server names.
408 * (nmbd_sendannounce.c)
411 announce_my_lm_server_names(t);
414 * If we are a local master browser, periodically
415 * announce ourselves to the domain master browser.
416 * This also deals with syncronising the domain master
417 * browser server lists with ourselves as a local
419 * (nmbd_sendannounce.c)
422 announce_myself_to_domain_master_browser(t);
425 * Fullfill any remote announce requests.
426 * (nmbd_sendannounce.c)
432 * Fullfill any remote browse sync announce requests.
433 * (nmbd_sendannounce.c)
436 browse_sync_remote(t);
439 * Scan the broadcast subnets, and WINS client
440 * namelists and refresh any that need refreshing.
447 * Scan the subnet namelists and server lists and
448 * expire thos that have timed out.
452 expire_names_and_servers(t);
455 * Write out a snapshot of our current browse list into
456 * the browse.dat file. This is used by smbd to service
457 * incoming NetServerEnum calls - used to synchronise
458 * browse lists over subnets.
459 * (nmbd_serverlistdb.c)
462 write_browse_list(t, False);
465 * If we are a domain master browser, we have a list of
466 * local master browsers we should synchronise browse
467 * lists with (these are added by an incoming local
468 * master browser announcement packet). Expire any of
469 * these that are no longer current, and pull the server
470 * lists from each of these known local master browsers.
471 * (nmbd_browsesync.c)
474 dmb_expire_and_sync_browser_lists(t);
477 * Check that there is a local master browser for our
478 * workgroup for all our broadcast subnets. If one
479 * is not found, start an election (which we ourselves
480 * may or may not participate in, depending on the
481 * setting of the 'local master' parameter.
485 check_master_browser_exists(t);
488 * If we are configured as a logon server, attempt to
489 * register the special NetBIOS names to become such
490 * (WORKGROUP<1c> name) on all broadcast subnets and
491 * with the WINS server (if used). If we are configured
492 * to become a domain master browser, attempt to register
493 * the special NetBIOS name (WORKGROUP<1b> name) to
495 * (nmbd_become_dmb.c)
501 * If we are a WINS server, do any timer dependent
502 * processing required.
503 * (nmbd_winsserver.c)
506 initiate_wins_processing(t);
509 * If we are a domain master browser, attempt to contact the
510 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
511 * This will only work to a Samba WINS server.
512 * (nmbd_browsesync.c)
515 if (lp_enhanced_browsing())
516 collect_all_workgroup_names_from_wins_server(t);
519 * Go through the response record queue and time out or re-transmit
520 * and expired entries.
524 retransmit_or_expire_response_records(t);
527 * check to see if any remote browse sync child processes have completed
530 sync_check_completion();
533 * regularly sync with any other DMBs we know about
536 if (lp_enhanced_browsing())
540 * clear the unexpected packet queue
546 * Reload the services file if we got a sighup.
549 if(reload_after_sighup) {
550 DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
551 msg_reload_nmbd_services(MSG_SMB_CONF_UPDATED,
552 pid_to_procid(0), (void*) &no_subnets, 0, NULL);
555 reload_after_sighup = 0;
558 /* check for new network interfaces */
560 if(reload_interfaces(t))
563 /* free up temp memory */
568 /**************************************************************************** **
569 Open the socket communication.
570 **************************************************************************** */
572 static BOOL open_sockets(enum smb_server_mode server_mode, int port)
575 * The sockets opened here will be used to receive broadcast
576 * packets *only*. Interface specific sockets are opened in
577 * make_subnet() in namedbsubnet.c. Thus we bind to the
578 * address "0.0.0.0". The parameter 'socket address' is
582 if ( server_mode == SERVER_MODE_INETD ) {
585 ClientNMB = open_socket_in(SOCK_DGRAM, port,
586 0, interpret_addr(lp_socket_address()),
590 ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
591 3, interpret_addr(lp_socket_address()),
594 if ( ClientNMB == -1 )
597 /* we are never interested in SIGPIPE */
598 BlockSignals(True,SIGPIPE);
600 set_socket_options( ClientNMB, "SO_BROADCAST" );
601 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
603 /* Ensure we're non-blocking. */
604 set_blocking( ClientNMB, False);
605 set_blocking( ClientDGRAM, False);
607 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
611 /**************************************************************************** **
613 **************************************************************************** */
614 int main(int argc, const char *argv[])
618 const char *p_lmhosts = dyn_LMHOSTSFILE;
619 BOOL no_process_group = False;
620 BOOL log_stdout = False;
621 enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
623 struct poptOption long_options[] = {
625 {"daemon", 'D', POPT_ARG_VAL, &server_mode, SERVER_MODE_DAEMON,
626 "Become a daemon(default)" },
627 {"interactive", 'i', POPT_ARG_VAL, &server_mode,
628 SERVER_MODE_INTERACTIVE, "Run interactive (not a daemon)" },
629 {"foreground", 'F', POPT_ARG_VAL, &server_mode,
630 SERVER_MODE_FOREGROUND, "Run daemon in foreground (for daemontools & etc)" },
631 {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
632 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
633 {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 'H', "Load a netbios hosts file"},
634 {"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
641 global_nmb_port = NMB_PORT;
643 pc = poptGetContext("nmbd", argc, argv, long_options, 0);
644 while (poptGetNextOpt(pc) != -1) {};
647 global_in_nmbd = True;
649 StartupTime = time(NULL);
651 sys_srandom(time(NULL) ^ sys_getpid());
653 if (!override_logfile) {
654 slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
655 lp_set_logfile(logfile);
658 fault_setup((void (*)(void *))fault_continue );
659 dump_core_setup("nmbd");
661 /* POSIX demands that signals are inherited. If the invoking process has
662 * these signals masked, we will have problems, as we won't receive them. */
663 BlockSignals(False, SIGHUP);
664 BlockSignals(False, SIGUSR1);
665 BlockSignals(False, SIGTERM);
667 CatchSignal( SIGHUP, SIGNAL_CAST sig_hup );
668 CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
671 /* we are never interested in SIGFPE */
672 BlockSignals(True,SIGFPE);
675 /* We no longer use USR2... */
677 BlockSignals(True, SIGUSR2);
680 if (server_mode == SERVER_MODE_INTERACTIVE) {
684 if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
685 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
689 setup_logging( argv[0], log_stdout );
693 DEBUG( 0, ( "Netbios nameserver version %s started.\n", SAMBA_VERSION_STRING) );
694 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
696 if ( !reload_nmbd_services(False) )
702 reload_nmbd_services( True );
704 if (strequal(lp_workgroup(),"*")) {
705 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
711 if (is_a_socket(0)) {
712 if (server_mode == SERVER_MODE_DAEMON) {
713 DEBUG(0,("standard input is a socket, "
714 "assuming -F option\n"));
716 server_mode = SERVER_MODE_INETD;
719 if (server_mode == SERVER_MODE_DAEMON) {
720 DEBUG( 2, ( "Becoming a daemon.\n" ) );
721 become_daemon(True, no_process_group);
722 } else if (server_mode == SERVER_MODE_FOREGROUND) {
723 become_daemon(False, no_process_group);
728 * If we're interactive we want to set our own process group for
731 if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group)
732 setpgid( (pid_t)0, (pid_t)0 );
736 /* Setup the async dns. We do it here so it doesn't have all the other
737 stuff initialised and thus chewing memory and sockets */
738 if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
743 if (!directory_exist(lp_lockdir(), NULL)) {
744 mkdir(lp_lockdir(), 0755);
747 pidfile_create("nmbd");
749 message_register(MSG_FORCE_ELECTION, nmbd_message_election, NULL);
751 /* Until winsrepl is done. */
752 message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry, NULL);
754 message_register(MSG_SHUTDOWN, nmbd_terminate, NULL);
755 message_register(MSG_SMB_CONF_UPDATED, msg_reload_nmbd_services, NULL);
756 message_register(MSG_SEND_PACKET, msg_nmbd_send_packet, NULL);
760 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
762 if ( !open_sockets( server_mode, global_nmb_port ) ) {
763 kill_async_dns_child();
767 /* Determine all the IP addresses we have. */
770 /* Create an nmbd subnet record for each of the above. */
771 if( False == create_subnets() ) {
772 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
773 kill_async_dns_child();
777 /* Load in any static local names. */
778 load_lmhosts_file(p_lmhosts);
779 DEBUG(3,("Loaded hosts file %s\n", p_lmhosts));
781 /* If we are acting as a WINS server, initialise data structures. */
782 if( !initialise_wins() ) {
783 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
784 kill_async_dns_child();
789 * Register nmbd primary workgroup and nmbd names on all
790 * the broadcast subnets, and on the WINS server (if specified).
791 * Also initiate the startup of our primary workgroup (start
792 * elections if we are setup as being able to be a local
796 if( False == register_my_workgroup_and_names() ) {
797 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
798 kill_async_dns_child();
802 /* We can only take signals in the select. */
803 BlockSignals( True, SIGTERM );
809 kill_async_dns_child();