This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[tprouty/samba.git] / source / nmbd / nmbd.c
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)
7    
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.
12    
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.
17    
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.
21    
22 */
23
24 #include "includes.h"
25
26 int ClientNMB       = -1;
27 int ClientDGRAM     = -1;
28 int global_nmb_port = -1;
29
30 extern BOOL global_in_nmbd;
31
32 /* are we running as a daemon ? */
33 static BOOL is_daemon;
34
35 /* fork or run in foreground ? */
36 static BOOL Fork = True;
37
38 /* log to standard output ? */
39 static BOOL log_stdout;
40
41 /* have we found LanMan clients yet? */
42 BOOL found_lm_clients = False;
43
44 /* what server type are we currently */
45
46 time_t StartupTime = 0;
47
48 /**************************************************************************** **
49  Handle a SIGTERM in band.
50  **************************************************************************** */
51
52 static void terminate(void)
53 {
54         DEBUG(0,("Got SIGTERM: going down...\n"));
55   
56         /* Write out wins.dat file if samba is a WINS server */
57         wins_write_database(False);
58   
59         /* Remove all SELF registered names from WINS */
60         release_wins_names();
61   
62         /* Announce all server entries as 0 time-to-live, 0 type. */
63         announce_my_servers_removed();
64
65         /* If there was an async dns child - kill it. */
66         kill_async_dns_child();
67
68         exit(0);
69 }
70
71 /**************************************************************************** **
72  Handle a SHUTDOWN message from smbcontrol.
73  **************************************************************************** */
74
75 static void nmbd_terminate(int msg_type, pid_t src, void *buf, size_t len)
76 {
77         terminate();
78 }
79
80 /**************************************************************************** **
81  Catch a SIGTERM signal.
82  **************************************************************************** */
83
84 static SIG_ATOMIC_T got_sig_term;
85
86 static void sig_term(int sig)
87 {
88         got_sig_term = 1;
89         sys_select_signal();
90 }
91
92 /**************************************************************************** **
93  Catch a SIGHUP signal.
94  **************************************************************************** */
95
96 static SIG_ATOMIC_T reload_after_sighup;
97
98 static void sig_hup(int sig)
99 {
100         reload_after_sighup = 1;
101         sys_select_signal();
102 }
103
104 #if DUMP_CORE
105 /**************************************************************************** **
106  Prepare to dump a core file - carefully!
107  **************************************************************************** */
108
109 static BOOL dump_core(void)
110 {
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) );
123
124 #ifdef HAVE_GETRLIMIT
125 #ifdef RLIMIT_CORE
126         {
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 ) );
133         }
134 #endif
135 #endif
136
137
138         DEBUG(0,("Dumping core in %s\n",dname));
139         abort();
140         return( True );
141 }
142 #endif
143
144 /**************************************************************************** **
145  Possibly continue after a fault.
146  **************************************************************************** */
147
148 static void fault_continue(void)
149 {
150 #if DUMP_CORE
151         dump_core();
152 #endif
153 }
154
155 /**************************************************************************** **
156  Expire old names from the namelist and server list.
157  **************************************************************************** */
158
159 static void expire_names_and_servers(time_t t)
160 {
161         static time_t lastrun = 0;
162   
163         if ( !lastrun )
164                 lastrun = t;
165         if ( t < (lastrun + 5) )
166                 return;
167         lastrun = t;
168
169         /*
170          * Expire any timed out names on all the broadcast
171          * subnets and those registered with the WINS server.
172          * (nmbd_namelistdb.c)
173          */
174
175         expire_names(t);
176
177         /*
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)
183          */
184
185         expire_workgroups_and_servers(t);
186 }
187
188 /************************************************************************** **
189  Reload the list of network interfaces.
190  ************************************************************************** */
191
192 static BOOL reload_interfaces(time_t t)
193 {
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;
199
200         if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) return False;
201         lastt = t;
202
203         if (!interfaces_changed()) return False;
204
205         /* the list of probed interfaces has changed, we may need to add/remove
206            some subnets */
207         load_interfaces();
208
209         /* find any interfaces that need adding */
210         for (n=iface_count() - 1; n >= 0; n--) {
211                 struct interface *iface = get_interface(n);
212
213                 /*
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.
217                  */
218
219                 if (ip_equal(iface->ip, loopback_ip)) {
220                         DEBUG(2,("reload_interfaces: Ignoring loopback interface %s\n", inet_ntoa(iface->ip)));
221                         continue;
222                 }
223
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;
227                 }
228
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) register_my_workgroup_one_subnet(subrec);
235                 }
236         }
237
238         /* find any interfaces that need deleting */
239         for (subrec=subnetlist; subrec; subrec=subrec->next) {
240                 for (n=iface_count() - 1; n >= 0; n--) {
241                         struct interface *iface = get_interface(n);
242                         if (ip_equal(iface->ip, subrec->myip) &&
243                             ip_equal(iface->nmask, subrec->mask_ip)) break;
244                 }
245                 if (n == -1) {
246                         /* oops, an interface has disapeared. This is
247                          tricky, we don't dare actually free the
248                          interface as it could be being used, so
249                          instead we just wear the memory leak and
250                          remove it from the list of interfaces without
251                          freeing it */
252                         DEBUG(2,("Deleting dead interface %s\n", 
253                                  inet_ntoa(subrec->myip)));
254                         close_subnet(subrec);
255                 }
256         }
257         
258         rescan_listen_set = True;
259
260         /* We need to shutdown if there are no subnets... */
261         if (FIRST_SUBNET == NULL) {
262                 DEBUG(0,("reload_interfaces: No subnets to listen to. Shutting down...\n"));
263                 return True;
264         }
265         return False;
266 }
267
268 /**************************************************************************** **
269  Reload the services file.
270  **************************************************************************** */
271
272 static BOOL reload_nmbd_services(BOOL test)
273 {
274         BOOL ret;
275
276         set_remote_machine_name("nmbd", False);
277
278         if ( lp_loaded() ) {
279                 pstring fname;
280                 pstrcpy( fname,lp_configfile());
281                 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
282                         pstrcpy(dyn_CONFIGFILE,fname);
283                         test = False;
284                 }
285         }
286
287         if ( test && !lp_file_list_changed() )
288                 return(True);
289
290         ret = lp_load( dyn_CONFIGFILE, True , False, False);
291
292         /* perhaps the config filename is now set */
293         if ( !test ) {
294                 DEBUG( 3, ( "services not loaded\n" ) );
295                 reload_nmbd_services( True );
296         }
297
298         return(ret);
299 }
300
301 /**************************************************************************** **
302  The main select loop.
303  **************************************************************************** */
304
305 static void process(void)
306 {
307         BOOL run_election;
308
309         while( True ) {
310                 time_t t = time(NULL);
311
312                 /* Check for internal messages */
313
314                 message_dispatch();
315
316                 /*
317                  * Check all broadcast subnets to see if
318                  * we need to run an election on any of them.
319                  * (nmbd_elections.c)
320                  */
321
322                 run_election = check_elections();
323
324                 /*
325                  * Read incoming UDP packets.
326                  * (nmbd_packets.c)
327                  */
328
329                 if(listen_for_packets(run_election))
330                         return;
331
332                 /*
333                  * Handle termination inband.
334                  */
335
336                 if (got_sig_term) {
337                         got_sig_term = 0;
338                         terminate();
339                 }
340
341                 /*
342                  * Process all incoming packets
343                  * read above. This calls the success and
344                  * failure functions registered when response
345                  * packets arrrive, and also deals with request
346                  * packets from other sources.
347                  * (nmbd_packets.c)
348                  */
349
350                 run_packet_queue();
351
352                 /*
353                  * Run any elections - initiate becoming
354                  * a local master browser if we have won.
355                  * (nmbd_elections.c)
356                  */
357
358                 run_elections(t);
359
360                 /*
361                  * Send out any broadcast announcements
362                  * of our server names. This also announces
363                  * the workgroup name if we are a local
364                  * master browser.
365                  * (nmbd_sendannounce.c)
366                  */
367
368                 announce_my_server_names(t);
369
370                 /*
371                  * Send out any LanMan broadcast announcements
372                  * of our server names.
373                  * (nmbd_sendannounce.c)
374                  */
375
376                 announce_my_lm_server_names(t);
377
378                 /*
379                  * If we are a local master browser, periodically
380                  * announce ourselves to the domain master browser.
381                  * This also deals with syncronising the domain master
382                  * browser server lists with ourselves as a local
383                  * master browser.
384                  * (nmbd_sendannounce.c)
385                  */
386
387                 announce_myself_to_domain_master_browser(t);
388
389                 /*
390                  * Fullfill any remote announce requests.
391                  * (nmbd_sendannounce.c)
392                  */
393
394                 announce_remote(t);
395
396                 /*
397                  * Fullfill any remote browse sync announce requests.
398                  * (nmbd_sendannounce.c)
399                  */
400
401                 browse_sync_remote(t);
402
403                 /*
404                  * Scan the broadcast subnets, and WINS client
405                  * namelists and refresh any that need refreshing.
406                  * (nmbd_mynames.c)
407                  */
408
409                 refresh_my_names(t);
410
411                 /*
412                  * Scan the subnet namelists and server lists and
413                  * expire thos that have timed out.
414                  * (nmbd.c)
415                  */
416
417                 expire_names_and_servers(t);
418
419                 /*
420                  * Write out a snapshot of our current browse list into
421                  * the browse.dat file. This is used by smbd to service
422                  * incoming NetServerEnum calls - used to synchronise
423                  * browse lists over subnets.
424                  * (nmbd_serverlistdb.c)
425                  */
426
427                 write_browse_list(t, False);
428
429                 /*
430                  * If we are a domain master browser, we have a list of
431                  * local master browsers we should synchronise browse
432                  * lists with (these are added by an incoming local
433                  * master browser announcement packet). Expire any of
434                  * these that are no longer current, and pull the server
435                  * lists from each of these known local master browsers.
436                  * (nmbd_browsesync.c)
437                  */
438
439                 dmb_expire_and_sync_browser_lists(t);
440
441                 /*
442                  * Check that there is a local master browser for our
443                  * workgroup for all our broadcast subnets. If one
444                  * is not found, start an election (which we ourselves
445                  * may or may not participate in, depending on the
446                  * setting of the 'local master' parameter.
447                  * (nmbd_elections.c)
448                  */
449
450                 check_master_browser_exists(t);
451
452                 /*
453                  * If we are configured as a logon server, attempt to
454                  * register the special NetBIOS names to become such
455                  * (WORKGROUP<1c> name) on all broadcast subnets and
456                  * with the WINS server (if used). If we are configured
457                  * to become a domain master browser, attempt to register
458                  * the special NetBIOS name (WORKGROUP<1b> name) to
459                  * become such.
460                  * (nmbd_become_dmb.c)
461                  */
462
463                 add_domain_names(t);
464
465                 /*
466                  * If we are a WINS server, do any timer dependent
467                  * processing required.
468                  * (nmbd_winsserver.c)
469                  */
470
471                 initiate_wins_processing(t);
472
473                 /*
474                  * If we are a domain master browser, attempt to contact the
475                  * WINS server to get a list of all known WORKGROUPS/DOMAINS.
476                  * This will only work to a Samba WINS server.
477                  * (nmbd_browsesync.c)
478                  */
479
480                 if (lp_enhanced_browsing())
481                         collect_all_workgroup_names_from_wins_server(t);
482
483                 /*
484                  * Go through the response record queue and time out or re-transmit
485                  * and expired entries.
486                  * (nmbd_packets.c)
487                  */
488
489                 retransmit_or_expire_response_records(t);
490
491                 /*
492                  * check to see if any remote browse sync child processes have completed
493                  */
494
495                 sync_check_completion();
496
497                 /*
498                  * regularly sync with any other DMBs we know about 
499                  */
500
501                 if (lp_enhanced_browsing())
502                         sync_all_dmbs(t);
503
504                 /*
505                  * clear the unexpected packet queue 
506                  */
507
508                 clear_unexpected(t);
509
510                 /*
511                  * Reload the services file if we got a sighup.
512                  */
513
514                 if(reload_after_sighup) {
515                         DEBUG( 0, ( "Got SIGHUP dumping debug info.\n" ) );
516                         write_browse_list( 0, True );
517                         dump_all_namelists();
518                         reload_nmbd_services( True );
519                         reopen_logs();
520                         if(reload_interfaces(0))
521                                 return;
522                         reload_after_sighup = 0;
523                 }
524
525                 /* check for new network interfaces */
526
527                 if(reload_interfaces(t))
528                         return;
529
530                 /* free up temp memory */
531                         lp_talloc_free();
532         }
533 }
534
535 /**************************************************************************** **
536  Open the socket communication.
537  **************************************************************************** */
538
539 static BOOL open_sockets(BOOL isdaemon, int port)
540 {
541         /*
542          * The sockets opened here will be used to receive broadcast
543          * packets *only*. Interface specific sockets are opened in
544          * make_subnet() in namedbsubnet.c. Thus we bind to the
545          * address "0.0.0.0". The parameter 'socket address' is
546          * now deprecated.
547          */
548
549         if ( isdaemon )
550                 ClientNMB = open_socket_in(SOCK_DGRAM, port,
551                                            interpret_addr(lp_socket_address()),
552                                            0,True);
553         else
554                 ClientNMB = 0;
555   
556         ClientDGRAM = open_socket_in(SOCK_DGRAM,DGRAM_PORT,3,0,True);
557
558         if ( ClientNMB == -1 )
559                 return( False );
560
561         /* we are never interested in SIGPIPE */
562         BlockSignals(True,SIGPIPE);
563
564         set_socket_options( ClientNMB,   "SO_BROADCAST" );
565         set_socket_options( ClientDGRAM, "SO_BROADCAST" );
566
567         DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
568         return( True );
569 }
570
571 /**************************************************************************** **
572  main program
573  **************************************************************************** */
574  int main(int argc, const char *argv[])
575 {
576         pstring logfile;
577         static BOOL opt_interactive;
578         poptContext pc;
579         int opt;
580         struct poptOption long_options[] = {
581         POPT_AUTOHELP
582         {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon(default)" },
583         {"interactive", 'i', POPT_ARG_VAL, &opt_interactive, True, "Run interactive (not a daemon)" },
584         {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
585         {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
586         {"hosts", 'H', POPT_ARG_STRING, dyn_LMHOSTSFILE, 'H', "Load a netbios hosts file"},
587         {"port", 'p', POPT_ARG_INT, &global_nmb_port, NMB_PORT, "Listen on the specified port" },
588         POPT_COMMON_SAMBA
589         { NULL }
590         };
591
592         global_nmb_port = NMB_PORT;
593
594         pc = poptGetContext("nmbd", argc, argv, long_options, 0);
595         while ((opt = poptGetNextOpt(pc)) != -1) ;
596         poptFreeContext(pc);
597
598         global_in_nmbd = True;
599         
600         StartupTime = time(NULL);
601         
602         sys_srandom(time(NULL) ^ sys_getpid());
603         
604         slprintf(logfile, sizeof(logfile)-1, "%s/log.nmbd", dyn_LOGFILEBASE);
605         lp_set_logfile(logfile);
606         
607         fault_setup((void (*)(void *))fault_continue );
608         
609         /* POSIX demands that signals are inherited. If the invoking process has
610          * these signals masked, we will have problems, as we won't receive them. */
611         BlockSignals(False, SIGHUP);
612         BlockSignals(False, SIGUSR1);
613         BlockSignals(False, SIGTERM);
614         
615         CatchSignal( SIGHUP,  SIGNAL_CAST sig_hup );
616         CatchSignal( SIGTERM, SIGNAL_CAST sig_term );
617         
618 #if defined(SIGFPE)
619         /* we are never interested in SIGFPE */
620         BlockSignals(True,SIGFPE);
621 #endif
622
623         /* We no longer use USR2... */
624 #if defined(SIGUSR2)
625         BlockSignals(True, SIGUSR2);
626 #endif
627
628         if ( opt_interactive ) {
629                 Fork = False;
630                 log_stdout = True;
631         }
632
633   if ( log_stdout && Fork ) {
634     DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
635     exit(1);
636   }
637
638   setup_logging( argv[0], log_stdout );
639
640   reopen_logs();
641
642   DEBUG( 0, ( "Netbios nameserver version %s started.\n", VERSION ) );
643   DEBUGADD( 0, ( "Copyright Andrew Tridgell and the Samba Team 1994-2003\n" ) );
644
645   if ( !reload_nmbd_services(False) )
646     return(-1);
647
648   if(!init_names())
649     return -1;
650
651   reload_nmbd_services( True );
652
653   if (strequal(lp_workgroup(),"*"))
654   {
655     DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
656     exit(1);
657   }
658
659   set_samba_nb_type();
660
661   if (!is_daemon && !is_a_socket(0))
662   {
663     DEBUG(0,("standard input is not a socket, assuming -D option\n"));
664     is_daemon = True;
665   }
666   
667   if (is_daemon && !opt_interactive)
668   {
669     DEBUG( 2, ( "Becoming a daemon.\n" ) );
670     become_daemon(Fork);
671   }
672
673 #if HAVE_SETPGID
674   /*
675    * If we're interactive we want to set our own process group for 
676    * signal management.
677    */
678   if (opt_interactive)
679     setpgid( (pid_t)0, (pid_t)0 );
680 #endif
681
682 #ifndef SYNC_DNS
683   /* Setup the async dns. We do it here so it doesn't have all the other
684      stuff initialised and thus chewing memory and sockets */
685   if(lp_we_are_a_wins_server() && lp_dns_proxy()) {
686           start_async_dns();
687   }
688 #endif
689
690   if (!directory_exist(lp_lockdir(), NULL)) {
691           mkdir(lp_lockdir(), 0755);
692   }
693
694   pidfile_create("nmbd");
695   message_init();
696   message_register(MSG_FORCE_ELECTION, nmbd_message_election);
697   message_register(MSG_WINS_NEW_ENTRY, nmbd_wins_new_entry);
698   message_register(MSG_SHUTDOWN, nmbd_terminate);
699
700   DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
701
702   if ( !open_sockets( is_daemon, global_nmb_port ) ) {
703     kill_async_dns_child();
704     return 1;
705   }
706
707   /* Determine all the IP addresses we have. */
708   load_interfaces();
709
710   /* Create an nmbd subnet record for each of the above. */
711   if( False == create_subnets() )
712   {
713     DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
714     kill_async_dns_child();
715     exit(1);
716   }
717
718   /* Load in any static local names. */ 
719   load_lmhosts_file(dyn_LMHOSTSFILE);
720   DEBUG(3,("Loaded hosts file %s\n", dyn_LMHOSTSFILE));
721
722   /* If we are acting as a WINS server, initialise data structures. */
723   if( !initialise_wins() )
724   {
725     DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
726     kill_async_dns_child();
727     exit(1);
728   }
729
730   /* 
731    * Register nmbd primary workgroup and nmbd names on all
732    * the broadcast subnets, and on the WINS server (if specified).
733    * Also initiate the startup of our primary workgroup (start
734    * elections if we are setup as being able to be a local
735    * master browser.
736    */
737
738   if( False == register_my_workgroup_and_names() )
739   {
740     DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
741     kill_async_dns_child();
742     exit(1);
743   }
744
745   /* We can only take signals in the select. */
746   BlockSignals( True, SIGTERM );
747
748   process();
749
750   if (dbf)
751     x_fclose(dbf);
752   kill_async_dns_child();
753   return(0);
754 }