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