sync 3.0 into HEAD for the last time
[vlendec/samba-autobuild/.git] / source3 / 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();
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(void)
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                 }
225         } else {
226                 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
227                 num_interfaces = 1;
228                 
229                 /* open an incoming socket */
230                 s = open_socket_in(SOCK_STREAM, wins_port, 0, interpret_addr(lp_socket_address()),True);
231                 if (s == -1)
232                         return(False);
233                 
234                 /* ready to listen */
235                 set_socket_options(s,"SO_KEEPALIVE"); 
236                 set_socket_options(s,user_socket_options);
237
238                 if (listen(s, 5) == -1) {
239                         DEBUG(0,("create_listen_fdset: listen: %s\n", strerror(errno)));
240                         close(s);
241                         return False;
242                 }
243                 
244                 add_fd_to_sock_array(s);
245                 FD_SET(s, listen_set);
246         } 
247
248         return True;
249 }
250
251 /*******************************************************************
252   read a packet from a socket and parse it, returning a packet ready
253   to be used or put on the queue. This assumes a UDP socket
254   ******************************************************************/
255 static struct wins_packet_struct *read_wins_packet(int fd, int timeout)
256 {
257         struct wins_packet_struct *p;
258         GENERIC_PACKET *q;
259         struct BUFFER inbuf;
260         ssize_t len=0;
261         size_t total=0;  
262         ssize_t ret;
263         BOOL ok = False;
264
265         inbuf.buffer=NULL;
266         inbuf.length=0;
267         inbuf.offset=0;
268
269         if(!grow_buffer(&inbuf, 4))
270                 return NULL;
271
272         ok = (read(fd, inbuf.buffer,4) == 4);
273         if (!ok)
274                 return NULL;
275         len = smb_len(inbuf.buffer);
276
277         if (len<=0)
278                 return NULL;
279
280         if(!grow_buffer(&inbuf, len))
281                 return NULL;
282                 
283         while (total < len) {
284                 ret = read(fd, inbuf.buffer + total + 4, len - total);
285                 if (ret == 0) {
286                         DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(len - total), strerror(errno) ));
287                         return NULL;
288                 }
289                 if (ret == -1) {
290                         DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(len - total), strerror(errno) ));
291                         return NULL;
292                 }
293                 total += ret;
294         }
295
296         q = (GENERIC_PACKET *)talloc(mem_ctx, sizeof(GENERIC_PACKET));
297         p = (struct wins_packet_struct *)talloc(mem_ctx, sizeof(*p));
298         if (q==NULL || p==NULL)
299                 return NULL;
300
301         decode_generic_packet(&inbuf, q);
302
303         q->fd=fd;
304         
305         p->next = NULL;
306         p->prev = NULL;
307         p->stop_packet = False;
308         p->timestamp = time(NULL);
309         p->fd = fd;
310         p->packet=q;
311         
312         return p;
313 }
314
315 static struct wins_packet_struct *packet_queue = NULL;
316
317 /*******************************************************************
318   Queue a packet into a packet queue
319 ******************************************************************/
320 static void queue_packet(struct wins_packet_struct *packet)
321 {
322         struct wins_packet_struct *p;
323
324         if (!packet_queue) {
325                 packet->prev = NULL;
326                 packet->next = NULL;
327                 packet_queue = packet;
328                 return;
329         }
330   
331         /* find the bottom */
332         for (p=packet_queue;p->next;p=p->next) 
333                 ;
334
335         p->next = packet;
336         packet->next = NULL;
337         packet->prev = p;
338 }
339
340 /****************************************************************************
341   Listens for NMB or DGRAM packets, and queues them.
342   return True if the socket is dead
343 ***************************************************************************/
344 static BOOL listen_for_wins_packets(void)
345 {
346         int num_interfaces = iface_count();
347         fd_set fds;
348         int i, num, s, new_s;
349         struct timeval timeout;
350
351         if(listen_set == NULL) {
352                 if(!create_listen_fdset()) {
353                         DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
354                         return True;
355                 }
356         }
357
358         memcpy((char *)&fds, (char *)listen_set, sizeof(fd_set));
359
360         timeout.tv_sec = NMBD_SELECT_LOOP;
361         timeout.tv_usec = 0;
362
363         /* Prepare for the select - allow certain signals. */
364
365         BlockSignals(False, SIGTERM);
366
367         num = sys_select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
368
369         /* We can only take signals when we are in the select - block them again here. */
370
371         BlockSignals(True, SIGTERM);
372
373         if(num == -1)
374                 return False;
375
376         for (; num > 0; num--) {
377                 s = -1;
378                 /* check the sockets we are only listening on, waiting to accept */             
379                 for (i=0; i<num_interfaces; i++) {
380                         struct sockaddr addr;
381                         socklen_t in_addrlen = sizeof(addr);
382                 
383                         if(FD_ISSET(sock_array[i], &fds)) {
384                                 s = sock_array[i];
385                                 /* Clear this so we don't look at it again. */
386                                 FD_CLR(sock_array[i], &fds);
387
388                                 /* accept and add the new socket to the listen set */
389                                 new_s=accept(s, &addr, &in_addrlen);
390
391                                 if (new_s < 0)
392                                         continue;
393         
394                                 DEBUG(5,("listen_for_wins_packets: new connection, old: %d, new : %d\n", s, new_s));
395                                 
396                                 set_socket_options(new_s, "SO_KEEPALIVE");
397                                 set_socket_options(new_s, user_socket_options);
398                                 FD_SET(new_s, listen_set);
399                                 add_fd_to_sock_array(new_s);
400                         }
401                 }
402
403                 /*
404                  * check for the sockets we are waiting data from
405                  * either client sending datas
406                  * or reply to our requests
407                  */
408                 for (i=num_interfaces; i<listen_number; i++) {
409                         if(FD_ISSET(sock_array[i], &fds)) {
410                                 struct wins_packet_struct *packet = read_wins_packet(sock_array[i], timeout.tv_sec);
411                                 if (packet) {
412                                         packet->fd = sock_array[i];
413                                         queue_packet(packet);
414                                 }
415                                 DEBUG(2,("listen_for_wins_packets: some data on fd %d\n", sock_array[i]));
416                                 FD_CLR(sock_array[i], &fds);
417                                 break;
418                         }
419         
420                 }
421
422         }
423
424         return False;
425 }
426
427
428 /*******************************************************************
429   Run elements off the packet queue till its empty
430 ******************************************************************/
431
432 static void run_wins_packet_queue(void)
433 {
434         struct wins_packet_struct *p;
435
436         while ((p = packet_queue)) {
437                 packet_queue = p->next;
438                 if (packet_queue)
439                         packet_queue->prev = NULL;
440                 p->next = p->prev = NULL;
441
442                 construct_reply(p);
443
444                 /* if it was a stop assoc, close the connection */
445                 if (p->stop_packet) {
446                         FD_CLR(p->fd, listen_set);
447                         remove_fd_from_sock_array(p->fd);
448                         close(p->fd);
449                 }
450         }
451
452
453 /**************************************************************************** **
454  The main select loop.
455  **************************************************************************** */
456 static void process(void)
457 {
458
459         while( True ) {
460                 time_t t = time(NULL);
461
462                 /* check for internal messages */
463                 message_dispatch();
464
465                 if(listen_for_wins_packets())
466                         return;
467
468                 run_wins_packet_queue();
469
470                 run_pull_replication(t);
471                 
472                 run_push_replication(t);
473                 
474                 /*
475                  * Reload the services file if we got a sighup.
476                  */
477
478                 if(reload_after_sighup) {
479                         reload_services( True );
480                         reopen_logs();
481                         reload_after_sighup = False;
482                 }
483
484                 /* free temp memory */
485                 talloc_destroy_pool(mem_ctx);
486
487                 /* free up temp memory */
488                 lp_talloc_free();
489         }
490 } /* process */
491
492 /****************************************************************************
493   main program
494 ****************************************************************************/
495  int main(int argc,char *argv[])
496 {
497         /* shall I run as a daemon */
498         static BOOL is_daemon = False;
499         static BOOL interactive = False;
500         static BOOL Fork = True;
501         static BOOL log_stdout = False;
502         struct poptOption long_options[] = {
503                 POPT_AUTOHELP
504                 { "daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
505                 { "foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools, etc)" },
506                 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
507                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Run interactive (not a daemon)" },
508                 { "port", 'p', POPT_ARG_INT, &wins_port, 'p', "Listen on the specified port" },
509                 POPT_COMMON_SAMBA
510                 POPT_TABLEEND
511         };
512         int opt;
513         poptContext pc;
514
515 #ifdef HAVE_SET_AUTH_PARAMETERS
516         set_auth_parameters(argc,argv);
517 #endif
518
519         pc = poptGetContext("wrepld", argc, (const char **)argv, long_options, 
520                                                 POPT_CONTEXT_KEEP_FIRST);
521
522         while ((opt = poptGetNextOpt(pc)) != -1) {
523                 switch (opt)  {
524                 case 'i':
525                         interactive = True;
526                         Fork = False;
527                         log_stdout = True;
528                         break;
529                 }
530         }
531
532
533         if (log_stdout && Fork) {
534                 d_printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
535                 poptPrintUsage(pc, stderr, 0);
536                 exit(1);
537         }
538
539 #ifdef HAVE_SETLUID
540         /* needed for SecureWare on SCO */
541         setluid(0);
542 #endif
543
544         sec_init();
545
546         load_case_tables();
547
548         set_remote_machine_name("wrepld", False);
549
550         setup_logging(argv[0],log_stdout);
551
552         /* we want to re-seed early to prevent time delays causing
553            client problems at a later date. (tridge) */
554         generate_random_buffer(NULL, 0, False);
555
556         /* make absolutely sure we run as root - to handle cases where people
557            are crazy enough to have it setuid */
558
559         gain_root_privilege();
560         gain_root_group_privilege();
561
562         fault_setup((void (*)(void *))exit_server);
563         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
564
565         /* we are never interested in SIGPIPE */
566         BlockSignals(True,SIGPIPE);
567
568 #if defined(SIGFPE)
569         /* we are never interested in SIGFPE */
570         BlockSignals(True,SIGFPE);
571 #endif
572
573 #if defined(SIGUSR2)
574         /* We are no longer interested in USR2 */
575         BlockSignals(True,SIGUSR2);
576 #endif
577
578         /* POSIX demands that signals are inherited. If the invoking process has
579          * these signals masked, we will have problems, as we won't recieve them. */
580         BlockSignals(False, SIGHUP);
581         BlockSignals(False, SIGUSR1);
582
583         /* we want total control over the permissions on created files,
584            so set our umask to 0 */
585         umask(0);
586
587         reopen_logs();
588
589         DEBUG(1,( "wrepld version %s started.\n", SAMBA_VERSION_STRING));
590         DEBUGADD(1,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
591
592         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
593                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
594
595         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
596                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
597                 exit(1);
598         }
599
600         /*
601          * Do this before reload_services.
602          */
603
604         if (!reload_services(False))
605                 return(-1);     
606
607         if (!init_names())
608                 return -1;
609         
610 #ifdef WITH_PROFILE
611         if (!profile_setup(False)) {
612                 DEBUG(0,("ERROR: failed to setup profiling\n"));
613                 return -1;
614         }
615 #endif
616
617         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
618         
619         DEBUG(3,( "loaded services\n"));
620
621         if (!is_daemon && !is_a_socket(0)) {
622                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
623                 is_daemon = True;
624         }
625
626         if (is_daemon && !interactive) {
627                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
628                 become_daemon(Fork);
629         }
630
631 #if HAVE_SETPGID
632         /*
633          * If we're interactive we want to set our own process group for
634          * signal management.
635          */
636         if (interactive)
637                 setpgid( (pid_t)0, (pid_t)0);
638 #endif
639
640         if (!directory_exist(lp_lockdir(), NULL)) {
641                 mkdir(lp_lockdir(), 0755);
642         }
643
644         if (is_daemon) {
645                 pidfile_create("wrepld");
646         }
647
648         if (!message_init()) {
649                 exit(1);
650         }
651
652         /* Initialise the memory context */
653         mem_ctx=talloc_init("wins repl talloc ctx");
654
655         /* initialise the global partners table */
656         partner_count=init_wins_partner_table();
657
658         /* We can only take signals in the select. */
659         BlockSignals( True, SIGTERM );
660
661         process();
662
663         poptFreeContext(pc);
664         exit_server("normal exit");
665         return(0);
666 }