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