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