a huge pile of changes :-)
[jra/samba/.git] / source3 / nmbd / nmbd.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    NBT netbios routines and daemon - version 2
5    Copyright (C) Andrew Tridgell 1994-1995
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20    
21    Revision History:
22
23    14 jan 96: lkcl@pires.co.uk
24    added multiple workgroup domain master support
25
26 */
27
28 #include "includes.h"
29 #include "loadparm.h"
30 #include "localnet.h"
31
32 extern int DEBUGLEVEL;
33
34 extern pstring debugf;
35 pstring servicesf = CONFIGFILE;
36
37 extern pstring scope;
38
39 int ClientNMB   = -1;
40 int ClientDGRAM = -1;
41
42 extern pstring myhostname;
43 static pstring host_file;
44 extern pstring myname;
45
46 /* are we running as a daemon ? */
47 static BOOL is_daemon = False;
48
49 /* machine comment for host announcements */
50 pstring ServerComment="";
51
52 static BOOL got_bcast = False;
53 static BOOL got_myip = False;
54 static BOOL got_nmask = False;
55
56 /* what server type are we currently */
57
58 time_t StartupTime =0;
59
60 struct in_addr ipzero;
61
62
63 /****************************************************************************
64 catch a sighup
65 ****************************************************************************/
66 static int sig_hup(void)
67 {
68   BlockSignals(True);
69
70   DEBUG(0,("Got SIGHUP (reload not implemented)\n"));
71   dump_names();
72   reload_services(True);
73
74   BlockSignals(False);
75 #ifndef DONT_REINSTALL_SIG
76   signal(SIGHUP,SIGNAL_CAST sig_hup);
77 #endif
78   return(0);
79 }
80
81 /****************************************************************************
82 catch a sigpipe
83 ****************************************************************************/
84 static int sig_pipe(void)
85 {
86   BlockSignals(True);
87
88   DEBUG(0,("Got SIGPIPE\n"));
89   if (!is_daemon)
90     exit(1);
91   BlockSignals(False);
92   return(0);
93 }
94
95 #if DUMP_CORE
96 /*******************************************************************
97 prepare to dump a core file - carefully!
98 ********************************************************************/
99 static BOOL dump_core(void)
100 {
101   char *p;
102   pstring dname;
103   strcpy(dname,debugf);
104   if ((p=strrchr(dname,'/'))) *p=0;
105   strcat(dname,"/corefiles");
106   mkdir(dname,0700);
107   sys_chown(dname,getuid(),getgid());
108   chmod(dname,0700);
109   if (chdir(dname)) return(False);
110   umask(~(0700));
111
112 #ifndef NO_GETRLIMIT
113 #ifdef RLIMIT_CORE
114   {
115     struct rlimit rlp;
116     getrlimit(RLIMIT_CORE, &rlp);
117     rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
118     setrlimit(RLIMIT_CORE, &rlp);
119     getrlimit(RLIMIT_CORE, &rlp);
120     DEBUG(3,("Core limits now %d %d\n",rlp.rlim_cur,rlp.rlim_max));
121   }
122 #endif
123 #endif
124
125
126   DEBUG(0,("Dumping core in %s\n",dname));
127   return(True);
128 }
129 #endif
130
131
132 /****************************************************************************
133 possibly continue after a fault
134 ****************************************************************************/
135 static void fault_continue(void)
136 {
137 #if DUMP_CORE
138   dump_core();
139 #endif
140 }
141
142 /*******************************************************************
143   expire old names from the namelist and server list
144   ******************************************************************/
145 static void expire_names_and_servers(void)
146 {
147         static time_t lastrun = 0;
148         time_t t = time(NULL);
149
150         if (!lastrun) lastrun = t;
151         if (t < lastrun + 5) return;
152         lastrun = t;
153
154         expire_names(t);
155         expire_servers(t);
156 }
157
158 /*****************************************************************************
159   reload the services file
160   **************************************************************************/
161 BOOL reload_services(BOOL test)
162 {
163   BOOL ret;
164   extern fstring remote_machine;
165
166   strcpy(remote_machine,"nmbd");
167
168   if (lp_loaded())
169     {
170       pstring fname;
171       strcpy(fname,lp_configfile());
172       if (file_exist(fname,NULL) && !strcsequal(fname,servicesf))
173         {
174           strcpy(servicesf,fname);
175           test = False;
176         }
177     }
178
179   if (test && !lp_file_list_changed())
180     return(True);
181
182   ret = lp_load(servicesf,True);
183
184   /* perhaps the config filename is now set */
185   if (!test) {
186     DEBUG(3,("services not loaded\n"));
187     reload_services(True);
188   }
189
190   return(ret);
191 }
192
193
194
195 /****************************************************************************
196 load a netbios hosts file
197 ****************************************************************************/
198 static void load_hosts_file(char *fname)
199 {
200   FILE *f = fopen(fname,"r");
201   pstring line;
202   if (!f) {
203     DEBUG(2,("Can't open lmhosts file %s\n",fname));
204     return;
205   }
206
207   while (!feof(f))
208     {
209       if (!fgets_slash(line,sizeof(pstring),f)) continue;
210
211       if (*line == '#') continue;
212
213       {
214         BOOL group=False;
215
216         pstring ip,name,mask,flags,extra;
217
218         char *ptr;
219         int count = 0;
220         struct in_addr ipaddr;
221         struct in_addr ipmask;
222         enum name_source source = LMHOSTS;
223
224         strcpy(ip,"");
225         strcpy(name,"");
226         strcpy(mask,"");
227         strcpy(flags,"");
228         strcpy(extra,"");
229         
230         ptr = line;
231
232         if (next_token(&ptr,ip   ,NULL)) ++count;
233         if (next_token(&ptr,name ,NULL)) ++count;
234         if (next_token(&ptr,mask ,NULL)) ++count;
235         if (next_token(&ptr,flags,NULL)) ++count;
236         if (next_token(&ptr,extra,NULL)) ++count;
237
238         if (count <= 0) continue;
239
240         if (count > 0 && count < 2) {
241           DEBUG(0,("Ill formed hosts line [%s]\n",line));           
242           continue;
243         }
244
245         /* work out if we need to shuffle the tokens along due to the
246            optional subnet mask argument */
247
248         if (strchr(mask, 'G') || strchr(mask, 'S') || strchr(mask, 'M')) {
249           strcpy(flags, mask );
250           /* default action for no subnet mask */
251           strcpy(mask, inet_ntoa(Netmask));
252         }
253
254         DEBUG(4, ("lmhost entry: %s %s %s %s\n", ip, name, mask, flags));
255
256         if (strchr(flags,'G') || strchr(flags,'S'))
257           group = True;
258
259         if (strchr(flags,'M') && !group) {
260           source = SELF;
261           strcpy(myname,name);
262         }
263
264         ipaddr = *interpret_addr2(ip);
265         ipmask = *interpret_addr2(mask);
266
267         if (group) {
268           add_domain_entry(ipaddr, ipmask, name, True);
269         } else {
270           add_netbios_entry(name,0x20,NB_ACTIVE,0,source,ipaddr);
271         }
272       }
273     }
274
275   fclose(f);
276 }
277
278
279 /****************************************************************************
280   The main select loop.
281   ***************************************************************************/
282 static void process(void)
283 {
284   BOOL run_election;
285
286   while (True)
287     {
288       run_election = check_elections();
289       listen_for_packets(run_election);
290
291       run_packet_queue();
292       run_elections();
293
294       announce_host();
295       announce_backup();
296       announce_master();
297
298       expire_names_and_servers();
299       expire_netbios_response_entries(time(NULL)-10);
300
301       write_browse_list();
302       do_browser_lists();
303       check_master_browser();
304     }
305 }
306
307
308 /****************************************************************************
309   open the socket communication
310 ****************************************************************************/
311 static BOOL open_sockets(BOOL isdaemon, int port)
312 {
313   struct hostent *hp;
314  
315   /* get host info */
316   if ((hp = Get_Hostbyname(myhostname)) == 0) {
317     DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",myhostname));
318     return False;
319   }   
320
321   if (isdaemon)
322     ClientNMB = open_socket_in(SOCK_DGRAM, port,0);
323   else
324     ClientNMB = 0;
325   
326   ClientDGRAM = open_socket_in(SOCK_DGRAM,DGRAM_PORT,3);
327
328   if (ClientNMB == -1)
329     return(False);
330
331   signal(SIGPIPE, SIGNAL_CAST sig_pipe);
332
333   set_socket_options(ClientNMB,"SO_BROADCAST");
334   set_socket_options(ClientDGRAM,"SO_BROADCAST");
335
336   DEBUG(3,("Sockets opened.\n"));
337   return True;
338 }
339
340
341 /*******************************************************************
342   check that a IP, bcast and netmask and consistent. Must be a 1s
343   broadcast
344   ******************************************************************/
345 static BOOL ip_consistent(struct in_addr ip,struct in_addr bcast, struct in_addr nmask)
346 {
347   unsigned long a_ip,a_bcast,a_nmask;
348
349   a_ip = ntohl(ip.s_addr);
350   a_bcast = ntohl(bcast.s_addr);
351   a_nmask = ntohl(nmask.s_addr);
352
353   /* check the netmask is sane */
354   if (((a_nmask>>24)&0xFF) != 0xFF) {
355     DEBUG(0,("Insane netmask %s\n",inet_ntoa(nmask)));
356     return(False);
357   }
358
359   /* check the IP and bcast are on the same net */
360   if ((a_ip&a_nmask) != (a_bcast&a_nmask)) {
361     DEBUG(0,("IP and broadcast are on different nets!\n"));
362     return(False);
363   }
364
365   /* check the IP and bcast are on the same net */
366   if ((a_bcast|a_nmask) != 0xFFFFFFFF) {
367     DEBUG(0,("Not a ones based broadcast %s\n",inet_ntoa(bcast)));
368     return(False);
369   }
370
371   return(True);
372 }
373
374
375 /****************************************************************************
376   initialise connect, service and file structs
377 ****************************************************************************/
378 static BOOL init_structs()
379 {
380   if (!get_myname(myhostname,got_myip?NULL:&myip))
381     return(False);
382
383   /* Read the broadcast address from the interface */
384   {
385     struct in_addr ip0,ip1,ip2;
386
387     ip0 = myip;
388
389     if (!(got_bcast && got_nmask))
390       {
391         get_broadcast(&ip0,&ip1,&ip2);
392
393         if (!got_myip)
394           myip = ip0;
395     
396         if (!got_bcast)
397           bcast_ip = ip1;
398     
399         if (!got_nmask)
400           Netmask = ip2;   
401       } 
402
403     DEBUG(1,("Using IP %s  ",inet_ntoa(myip))); 
404     DEBUG(1,("broadcast %s  ",inet_ntoa(bcast_ip)));
405     DEBUG(1,("netmask %s\n",inet_ntoa(Netmask)));    
406
407     if (!ip_consistent(myip,bcast_ip,Netmask)) {
408       DEBUG(0,("WARNING: The IP address, broadcast and Netmask are not consistent\n"));
409       DEBUG(0,("You are likely to experience problems with this setup!\n"));
410     }
411   }
412
413   if (! *myname) {
414     char *p;
415     strcpy(myname,myhostname);
416     p = strchr(myname,'.');
417     if (p) *p = 0;
418   }
419
420   return True;
421 }
422
423 /****************************************************************************
424 usage on the program
425 ****************************************************************************/
426 static void usage(char *pname)
427 {
428   DEBUG(0,("Incorrect program usage - is the command line correct?\n"));
429
430   printf("Usage: %s [-n name] [-B bcast address] [-D] [-p port] [-d debuglevel] [-l log basename]\n",pname);
431   printf("Version %s\n",VERSION);
432   printf("\t-D                    become a daemon\n");
433   printf("\t-p port               listen on the specified port\n");
434   printf("\t-d debuglevel         set the debuglevel\n");
435   printf("\t-l log basename.      Basename for log/debug files\n");
436   printf("\t-n netbiosname.       the netbios name to advertise for this host\n");
437   printf("\t-B broadcast address  the address to use for broadcasts\n");
438   printf("\t-N netmask           the netmask to use for subnet determination\n");
439   printf("\t-H hosts file        load a netbios hosts file\n");
440   printf("\t-G group name        add a group name to be part of\n");
441   printf("\t-I ip-address        override the IP address\n");
442   printf("\t-C comment           sets the machine comment that appears in browse lists\n");
443   printf("\n");
444 }
445
446
447 /****************************************************************************
448   main program
449   **************************************************************************/
450  int main(int argc,char *argv[])
451 {
452   int port = NMB_PORT;
453   int opt;
454   extern FILE *dbf;
455   extern char *optarg;
456
457   *host_file = 0;
458
459   StartupTime = time(NULL);
460
461   TimeInit();
462
463   strcpy(debugf,NMBLOGFILE);
464
465   setup_logging(argv[0],False);
466
467   charset_initialise();
468
469   ipzero = *interpret_addr2("0.0.0.0");
470
471 #ifdef LMHOSTSFILE
472   strcpy(host_file,LMHOSTSFILE);
473 #endif
474
475   /* this is for people who can't start the program correctly */
476   while (argc > 1 && (*argv[1] != '-')) {
477     argv++;
478     argc--;
479   }
480
481   fault_setup(fault_continue);
482
483   signal(SIGHUP,SIGNAL_CAST sig_hup);
484
485   bcast_ip = ipzero;
486   myip = ipzero;
487
488   while ((opt = getopt (argc, argv, "s:T:I:C:bAi:B:N:Rn:l:d:Dp:hSH:G:")) != EOF)
489     {
490       switch (opt)
491         {
492         case 's':
493           strcpy(servicesf,optarg);
494           break;
495         case 'C':
496           strcpy(ServerComment,optarg);
497           break;
498         case 'G':
499           if (got_bcast && got_nmask) {
500             add_domain_entry(bcast_ip,Netmask,optarg, True);
501           } else {
502             DEBUG(0, ("Warning: option -G %s added before broadcast and netmask.\n",
503                       optarg));
504             DEBUG(0, ("Assuming default values: bcast %s netmask %s\n",
505                       inet_ntoa(bcast_ip), inet_ntoa(Netmask))); /* (i hope) */
506           }
507           break;
508         case 'H':
509           strcpy(host_file,optarg);
510           break;
511         case 'I':
512           myip = *interpret_addr2(optarg);
513           got_myip = True;
514           break;
515         case 'B':
516           bcast_ip = *interpret_addr2(optarg);
517           got_bcast = True;
518           break;
519         case 'N':
520           Netmask = *interpret_addr2(optarg);
521           got_nmask = True;
522           break;
523         case 'n':
524           strcpy(myname,optarg);
525           break;
526         case 'l':
527           sprintf(debugf,"%s.nmb",optarg);
528           break;
529         case 'i':
530           strcpy(scope,optarg);
531           strupper(scope);
532           break;
533         case 'D':
534           is_daemon = True;
535           break;
536         case 'd':
537           DEBUGLEVEL = atoi(optarg);
538           break;
539         case 'p':
540           port = atoi(optarg);
541           break;
542         case 'h':
543           usage(argv[0]);
544           exit(0);
545           break;
546         default:
547           if (!is_a_socket(0)) {
548             usage(argv[0]);
549           }
550           break;
551         }
552     }
553
554   DEBUG(1,("%s netbios nameserver version %s started\n",timestring(),VERSION));
555   DEBUG(1,("Copyright Andrew Tridgell 1994\n"));
556
557   init_structs();
558
559   if (!reload_services(False))
560     return(-1); 
561
562   if (!is_daemon && !is_a_socket(0)) {
563     DEBUG(0,("standard input is not a socket, assuming -D option\n"));
564     is_daemon = True;
565   }
566   
567   if (is_daemon) {
568     DEBUG(2,("%s becoming a daemon\n",timestring()));
569     become_daemon();
570   }
571
572   DEBUG(3,("Opening sockets %d\n", port));
573
574   if (!open_sockets(is_daemon,port)) return 1;
575
576   if (*host_file) {
577     load_hosts_file(host_file);
578     DEBUG(3,("Loaded hosts file\n"));
579   }
580
581   if (!*ServerComment)
582     strcpy(ServerComment,"Samba %v");
583   string_sub(ServerComment,"%v",VERSION);
584   string_sub(ServerComment,"%h",myhostname);
585
586   add_my_names();
587   add_my_domains();
588
589   DEBUG(3,("Checked names\n"));
590   
591   write_browse_list();
592
593   DEBUG(3,("Dumped names\n"));
594
595   process();
596   close_sockets();
597
598   if (dbf)
599     fclose(dbf);
600   return(0);
601 }