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