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