first public release of samba4 code
[samba.git] / source / wrepld / server.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Jean François Micouleau      1998-2002.
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "includes.h"
22 #include "wins_repl.h"
23
24 extern WINS_OWNER *global_wins_table;
25 extern int partner_count;
26
27 extern fd_set *listen_set;
28 extern int listen_number;
29 extern int *sock_array;
30
31 extern TALLOC_CTX *mem_ctx;
32
33 int wins_port = 42;
34
35 /****************************************************************************
36   when exiting, take the whole family
37 ****************************************************************************/
38 static void *dflt_sig(void)
39 {
40         exit_server("caught signal");
41         return NULL;
42 }
43
44 /****************************************************************************
45   reload the services file
46   **************************************************************************/
47 BOOL reload_services(BOOL test)
48 {
49         BOOL ret;
50         
51         if (lp_loaded()) {
52                 pstring fname;
53                 pstrcpy(fname,lp_configfile());
54                 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
55                         pstrcpy(dyn_CONFIGFILE,fname);
56                         test = False;
57                 }
58         }
59
60         reopen_logs();
61
62         if (test && !lp_file_list_changed())
63                 return(True);
64
65         ret = lp_load(dyn_CONFIGFILE,False,False,True);
66
67
68         /* perhaps the config filename is now set */
69         if (!test)
70                 reload_services(True);
71
72         reopen_logs();
73
74         load_interfaces();
75
76         return(ret);
77 }
78
79 /****************************************************************************
80  Catch a sighup.
81 ****************************************************************************/
82
83 VOLATILE sig_atomic_t reload_after_sighup = False;
84
85 static void sig_hup(int sig)
86 {
87         BlockSignals(True,SIGHUP);
88         DEBUG(0,("Got SIGHUP\n"));
89
90         sys_select_signal();
91         reload_after_sighup = True;
92         BlockSignals(False,SIGHUP);
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         pstrcpy(dname,lp_logfile());
104         if ((p=strrchr_m(dname,'/'))) *p=0;
105         pstrcat(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 #ifdef HAVE_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",
121                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
122         }
123 #endif
124 #endif
125
126
127         DEBUG(0,("Dumping core in %s\n",dname));
128         abort();
129         return(True);
130 }
131 #endif
132
133 /****************************************************************************
134 exit the server
135 ****************************************************************************/
136 void exit_server(const char *reason)
137 {
138         static int firsttime=1;
139
140         if (!firsttime)
141                 exit(0);
142         firsttime = 0;
143
144         DEBUG(2,("Closing connections\n"));
145
146         if (!reason) {   
147                 int oldlevel = DEBUGLEVEL;
148                 DEBUGLEVEL = 10;
149                 DEBUGLEVEL = oldlevel;
150                 DEBUG(0,("===============================================================\n"));
151 #if DUMP_CORE
152                 if (dump_core()) return;
153 #endif
154         }
155
156         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
157         exit(0);
158 }
159
160 /****************************************************************************
161  Usage of the program.
162 ****************************************************************************/
163
164 static void usage(char *pname)
165 {
166
167         d_printf("Usage: %s [-DFSaioPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
168         d_printf("       [-O socket options] [-s services file]\n");
169         d_printf("\t-D                    Become a daemon (default)\n");
170         d_printf("\t-F                    Run daemon in foreground (for daemontools, etc)\n");
171         d_printf("\t-S                    Log to stdout\n");
172         d_printf("\t-a                    Append to log file (default)\n");
173         d_printf("\t-i                    Run interactive (not a daemon)\n" );
174         d_printf("\t-o                    Overwrite log file, don't append\n");
175         d_printf("\t-h                    Print usage\n");
176         d_printf("\t-?                    Print usage\n");
177         d_printf("\t-V                    Print version\n");
178         d_printf("\t-d debuglevel         Set the debuglevel\n");
179         d_printf("\t-l log basename.      Basename for log/debug files\n");
180         d_printf("\t-p port               Listen on the specified port\n");
181         d_printf("\t-O socket options     Socket options\n");
182         d_printf("\t-s services file.     Filename of services file\n");
183         d_printf("\n");
184 }
185
186 /****************************************************************************
187   Create an fd_set containing all the sockets in the subnet structures,
188   plus the broadcast sockets.
189 ***************************************************************************/
190
191 static BOOL create_listen_fdset(void)
192 {
193         int i;
194         int num_interfaces = iface_count();
195         int s;
196
197         listen_set = (fd_set *)malloc(sizeof(fd_set));
198         if(listen_set == NULL) {
199                 DEBUG(0,("create_listen_fdset: malloc fail !\n"));
200                 return True;
201         }
202
203 #ifdef HAVE_ATEXIT
204         {
205                 static int atexit_set;
206                 if(atexit_set == 0) {
207                         atexit_set=1;
208                 }
209         }
210 #endif
211
212         FD_ZERO(listen_set);
213
214         if(lp_interfaces() && lp_bind_interfaces_only()) {
215                 /* We have been given an interfaces line, and been 
216                    told to only bind to those interfaces. Create a
217                    socket per interface and bind to only these.
218                 */
219                 
220                 if(num_interfaces > FD_SETSIZE) {
221                         DEBUG(0,("create_listen_fdset: Too many interfaces specified to bind to. Number was %d max can be %d\n", num_interfaces, FD_SETSIZE));
222                         return False;
223                 }
224
225                 /* Now open a listen socket for each of the interfaces. */
226                 for(i = 0; i < num_interfaces; i++) {
227                         struct in_addr *ifip = iface_n_ip(i);
228                         
229                         if(ifip == NULL) {
230                                 DEBUG(0,("create_listen_fdset: interface %d has NULL IP address !\n", i));
231                                 continue;
232                         }
233                         s = open_socket_in(SOCK_STREAM, wins_port, 0, ifip->s_addr, True);
234                         if(s == -1)
235                                 return False;
236
237                         /* ready to listen */
238                         set_socket_options(s,"SO_KEEPALIVE"); 
239                         set_socket_options(s,lp_socket_options());
240       
241                         if (listen(s, 5) == -1) {
242                                 DEBUG(5,("listen: %s\n",strerror(errno)));
243                                 close(s);
244                                 return False;
245                         }
246                         add_fd_to_sock_array(s);
247                         FD_SET(s, listen_set);
248                 }
249         } else {
250                 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
251                 num_interfaces = 1;
252                 
253                 /* open an incoming socket */
254                 s = open_socket_in(SOCK_STREAM, wins_port, 0, interpret_addr(lp_socket_address()),True);
255                 if (s == -1)
256                         return(False);
257                 
258                 /* ready to listen */
259                 set_socket_options(s,"SO_KEEPALIVE"); 
260                 set_socket_options(s, lp_socket_options());
261
262                 if (listen(s, 5) == -1) {
263                         DEBUG(0,("create_listen_fdset: listen: %s\n", strerror(errno)));
264                         close(s);
265                         return False;
266                 }
267                 
268                 add_fd_to_sock_array(s);
269                 FD_SET(s, listen_set);
270         } 
271
272         return True;
273 }
274
275 /*******************************************************************
276   read a packet from a socket and parse it, returning a packet ready
277   to be used or put on the queue. This assumes a UDP socket
278   ******************************************************************/
279 static struct wins_packet_struct *read_wins_packet(int fd, int timeout)
280 {
281         struct wins_packet_struct *p;
282         GENERIC_PACKET *q;
283         struct BUFFER inbuf;
284         ssize_t len=0;
285         size_t total=0;  
286         ssize_t ret;
287         BOOL ok = False;
288
289         inbuf.buffer=NULL;
290         inbuf.length=0;
291         inbuf.offset=0;
292
293         if(!grow_buffer(&inbuf, 4))
294                 return NULL;
295
296         ok = (read(fd, inbuf.buffer,4) == 4);
297         if (!ok)
298                 return NULL;
299         len = smb_len(inbuf.buffer);
300
301         if (len<=0)
302                 return NULL;
303
304         if(!grow_buffer(&inbuf, len))
305                 return NULL;
306                 
307         while (total < len) {
308                 ret = read(fd, inbuf.buffer + total + 4, len - total);
309                 if (ret == 0) {
310                         DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(len - total), strerror(errno) ));
311                         return NULL;
312                 }
313                 if (ret == -1) {
314                         DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(len - total), strerror(errno) ));
315                         return NULL;
316                 }
317                 total += ret;
318         }
319
320         q = (GENERIC_PACKET *)talloc(mem_ctx, sizeof(GENERIC_PACKET));
321         p = (struct wins_packet_struct *)talloc(mem_ctx, sizeof(*p));
322         if (q==NULL || p==NULL)
323                 return NULL;
324
325         decode_generic_packet(&inbuf, q);
326
327         q->fd=fd;
328         
329         p->next = NULL;
330         p->prev = NULL;
331         p->stop_packet = False;
332         p->timestamp = time(NULL);
333         p->fd = fd;
334         p->packet=q;
335         
336         return p;
337 }
338
339 static struct wins_packet_struct *packet_queue = NULL;
340
341 /*******************************************************************
342   Queue a packet into a packet queue
343 ******************************************************************/
344 static void queue_packet(struct wins_packet_struct *packet)
345 {
346         struct wins_packet_struct *p;
347
348         if (!packet_queue) {
349                 packet->prev = NULL;
350                 packet->next = NULL;
351                 packet_queue = packet;
352                 return;
353         }
354   
355         /* find the bottom */
356         for (p=packet_queue;p->next;p=p->next) 
357                 ;
358
359         p->next = packet;
360         packet->next = NULL;
361         packet->prev = p;
362 }
363
364 /****************************************************************************
365   Listens for NMB or DGRAM packets, and queues them.
366   return True if the socket is dead
367 ***************************************************************************/
368 static BOOL listen_for_wins_packets(void)
369 {
370         int num_interfaces = iface_count();
371         fd_set fds;
372         int i, num, s, new_s;
373         struct timeval timeout;
374
375         if(listen_set == NULL) {
376                 if(!create_listen_fdset()) {
377                         DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
378                         return True;
379                 }
380         }
381
382         memcpy((char *)&fds, (char *)listen_set, sizeof(fd_set));
383
384         timeout.tv_sec = NMBD_SELECT_LOOP;
385         timeout.tv_usec = 0;
386
387         /* Prepare for the select - allow certain signals. */
388
389         BlockSignals(False, SIGTERM);
390
391         num = sys_select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
392
393         /* We can only take signals when we are in the select - block them again here. */
394
395         BlockSignals(True, SIGTERM);
396
397         if(num == -1)
398                 return False;
399
400         for (; num > 0; num--) {
401                 s = -1;
402                 /* check the sockets we are only listening on, waiting to accept */             
403                 for (i=0; i<num_interfaces; i++) {
404                         struct sockaddr addr;
405                         socklen_t in_addrlen = sizeof(addr);
406                 
407                         if(FD_ISSET(sock_array[i], &fds)) {
408                                 s = sock_array[i];
409                                 /* Clear this so we don't look at it again. */
410                                 FD_CLR(sock_array[i], &fds);
411
412                                 /* accept and add the new socket to the listen set */
413                                 new_s=accept(s, &addr, &in_addrlen);
414
415                                 if (new_s < 0)
416                                         continue;
417         
418                                 DEBUG(5,("listen_for_wins_packets: new connection, old: %d, new : %d\n", s, new_s));
419                                 
420                                 set_socket_options(new_s, "SO_KEEPALIVE");
421                                 set_socket_options(new_s, lp_socket_options());
422                                 FD_SET(new_s, listen_set);
423                                 add_fd_to_sock_array(new_s);
424                         }
425                 }
426
427                 /*
428                  * check for the sockets we are waiting data from
429                  * either client sending datas
430                  * or reply to our requests
431                  */
432                 for (i=num_interfaces; i<listen_number; i++) {
433                         if(FD_ISSET(sock_array[i], &fds)) {
434                                 struct wins_packet_struct *packet = read_wins_packet(sock_array[i], timeout.tv_sec);
435                                 if (packet) {
436                                         packet->fd = sock_array[i];
437                                         queue_packet(packet);
438                                 }
439                                 DEBUG(2,("listen_for_wins_packets: some data on fd %d\n", sock_array[i]));
440                                 FD_CLR(sock_array[i], &fds);
441                                 break;
442                         }
443         
444                 }
445
446         }
447
448         return False;
449 }
450
451
452 /*******************************************************************
453   Run elements off the packet queue till its empty
454 ******************************************************************/
455
456 static void run_wins_packet_queue(void)
457 {
458         struct wins_packet_struct *p;
459
460         while ((p = packet_queue)) {
461                 packet_queue = p->next;
462                 if (packet_queue)
463                         packet_queue->prev = NULL;
464                 p->next = p->prev = NULL;
465
466                 construct_reply(p);
467
468                 /* if it was a stop assoc, close the connection */
469                 if (p->stop_packet) {
470                         FD_CLR(p->fd, listen_set);
471                         remove_fd_from_sock_array(p->fd);
472                         close(p->fd);
473                 }
474         }
475
476
477 /**************************************************************************** **
478  The main select loop.
479  **************************************************************************** */
480 static void process(void)
481 {
482
483         while( True ) {
484                 time_t t = time(NULL);
485
486                 /* check for internal messages */
487                 message_dispatch();
488
489                 if(listen_for_wins_packets())
490                         return;
491
492                 run_wins_packet_queue();
493
494                 run_pull_replication(t);
495                 
496                 run_push_replication(t);
497                 
498                 /*
499                  * Reload the services file if we got a sighup.
500                  */
501
502                 if(reload_after_sighup) {
503                         reload_services( True );
504                         reopen_logs();
505                         reload_after_sighup = False;
506                 }
507
508                 /* free temp memory */
509                 talloc_destroy_pool(mem_ctx);
510
511                 /* free up temp memory */
512                 lp_talloc_free();
513         }
514 } /* process */
515
516 /****************************************************************************
517   main program
518 ****************************************************************************/
519  int main(int argc,char *argv[])
520 {
521         extern char *optarg;
522         /* shall I run as a daemon */
523         BOOL is_daemon = False;
524         BOOL interactive = False;
525         BOOL specified_logfile = False;
526         BOOL Fork = True;
527         BOOL log_stdout = False;
528         int opt;
529         pstring logfile;
530
531 #ifdef HAVE_SET_AUTH_PARAMETERS
532         set_auth_parameters(argc,argv);
533 #endif
534
535         /* this is for people who can't start the program correctly */
536         while (argc > 1 && (*argv[1] != '-')) {
537                 argv++;
538                 argc--;
539         }
540
541         while ( EOF != (opt = getopt(argc, argv, "FSO:l:s:d:Dp:h?Vaiof:")) )
542                 switch (opt)  {
543                 case 'F':
544                         Fork = False;
545                         break;
546                 case 'S':
547                         log_stdout = True;
548                         break;
549                 case 'O':
550                         lp_set_cmdline("socket options", optarg);
551                         break;
552
553                 case 's':
554                         pstrcpy(dyn_CONFIGFILE,optarg);
555                         break;
556
557                 case 'l':
558                         specified_logfile = True;
559                         slprintf(logfile, sizeof(logfile)-1, "%s/log.wrepld", optarg);
560                         lp_set_logfile(logfile);
561                         break;
562
563                 case 'i':
564                         interactive = True;
565                         Fork = False;
566                         log_stdout = True;
567                         break;
568
569                 case 'D':
570                         is_daemon = True;
571                         break;
572
573                 case 'd':
574                         if (*optarg == 'A')
575                                 DEBUGLEVEL = 10000;
576                         else
577                                 DEBUGLEVEL = atoi(optarg);
578                         break;
579
580                 case 'p':
581                         wins_port = atoi(optarg);
582                         break;
583
584                 case 'h':
585                 case '?':
586                         usage(argv[0]);
587                         exit(0);
588                         break;
589
590                 case 'V':
591                         d_printf("Version %s\n",VERSION);
592                         exit(0);
593                         break;
594                 default:
595                         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
596                         usage(argv[0]);
597                         exit(1);
598                 }
599         if (log_stdout && Fork) {
600                 d_printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
601                 usage(argv[0]);
602                 exit(1);
603         }
604
605 #ifdef HAVE_SETLUID
606         /* needed for SecureWare on SCO */
607         setluid(0);
608 #endif
609
610         sec_init();
611
612         load_case_tables();
613
614         if(!specified_logfile) {
615                 slprintf(logfile, sizeof(logfile)-1, "%s/log.wrepld",
616                          dyn_LOGFILEBASE);
617                 lp_set_logfile(logfile);
618         }
619
620         set_remote_machine_name("wrepld");
621
622         setup_logging(argv[0],log_stdout);
623
624         /* we want to re-seed early to prevent time delays causing
625            client problems at a later date. (tridge) */
626         generate_random_buffer(NULL, 0, False);
627
628         /* make absolutely sure we run as root - to handle cases where people
629            are crazy enough to have it setuid */
630
631         gain_root_privilege();
632         gain_root_group_privilege();
633
634         fault_setup((void (*)(void *))exit_server);
635         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
636
637         /* we are never interested in SIGPIPE */
638         BlockSignals(True,SIGPIPE);
639
640 #if defined(SIGFPE)
641         /* we are never interested in SIGFPE */
642         BlockSignals(True,SIGFPE);
643 #endif
644
645 #if defined(SIGUSR2)
646         /* We are no longer interested in USR2 */
647         BlockSignals(True,SIGUSR2);
648 #endif
649
650         /* POSIX demands that signals are inherited. If the invoking process has
651          * these signals masked, we will have problems, as we won't recieve them. */
652         BlockSignals(False, SIGHUP);
653         BlockSignals(False, SIGUSR1);
654
655         /* we want total control over the permissions on created files,
656            so set our umask to 0 */
657         umask(0);
658
659         reopen_logs();
660
661         DEBUG(1,( "wrepld version %s started.\n", VERSION));
662         DEBUGADD(1,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
663
664         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
665                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
666
667         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
668                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
669                 exit(1);
670         }
671
672         /*
673          * Do this before reload_services.
674          */
675
676         if (!reload_services(False))
677                 return(-1);     
678
679         if (!init_names())
680                 return -1;
681         
682 #ifdef WITH_PROFILE
683         if (!profile_setup(False)) {
684                 DEBUG(0,("ERROR: failed to setup profiling\n"));
685                 return -1;
686         }
687 #endif
688
689         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
690         
691         DEBUG(3,( "loaded services\n"));
692
693         if (!is_daemon && !is_a_socket(0)) {
694                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
695                 is_daemon = True;
696         }
697
698         if (is_daemon && !interactive) {
699                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
700                 become_daemon(Fork);
701         }
702
703 #if HAVE_SETPGID
704         /*
705          * If we're interactive we want to set our own process group for
706          * signal management.
707          */
708         if (interactive)
709                 setpgid( (pid_t)0, (pid_t)0);
710 #endif
711
712         if (!directory_exist(lp_lockdir(), NULL)) {
713                 mkdir(lp_lockdir(), 0755);
714         }
715
716         if (is_daemon) {
717                 pidfile_create("wrepld");
718         }
719
720         if (!message_init()) {
721                 exit(1);
722         }
723
724         /* Initialise the memory context */
725         mem_ctx=talloc_init("wins repl talloc ctx");
726
727         /* initialise the global partners table */
728         partner_count=init_wins_partner_table();
729
730         /* We can only take signals in the select. */
731         BlockSignals( True, SIGTERM );
732
733         process();
734
735         exit_server("normal exit");
736         return(0);
737 }