Janitorial duties to make autogen.sh portable.
[Samba/gebeck_regimport.git] / source3 / wrepld / server.c
blob31f260e94c0d791fba98e48d1b613af8a6dae660
1 /*
2 Unix SMB/CIFS implementation.
3 Main SMB server routines
4 Copyright (C) Jean François Micouleau 1998-2002.
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.
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.
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.
21 #include "includes.h"
22 #include "wins_repl.h"
24 extern pstring user_socket_options;
26 extern WINS_OWNER *global_wins_table;
27 extern int partner_count;
29 extern fd_set *listen_set;
30 extern int listen_number;
31 extern int *sock_array;
33 extern TALLOC_CTX *mem_ctx;
35 int wins_port = 42;
37 /****************************************************************************
38 when exiting, take the whole family
39 ****************************************************************************/
40 static void *dflt_sig(void)
42 exit_server("caught signal");
43 return NULL;
46 /****************************************************************************
47 reload the services file
48 **************************************************************************/
49 BOOL reload_services(BOOL test)
51 BOOL ret;
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;
62 reopen_logs();
64 if (test && !lp_file_list_changed())
65 return(True);
67 ret = lp_load(dyn_CONFIGFILE,False,False,True);
70 /* perhaps the config filename is now set */
71 if (!test)
72 reload_services(True);
74 reopen_logs();
76 load_interfaces();
78 return(ret);
81 /****************************************************************************
82 Catch a sighup.
83 ****************************************************************************/
85 VOLATILE sig_atomic_t reload_after_sighup = False;
87 static void sig_hup(int sig)
89 BlockSignals(True,SIGHUP);
90 DEBUG(0,("Got SIGHUP\n"));
92 sys_select_signal();
93 reload_after_sighup = True;
94 BlockSignals(False,SIGHUP);
97 #if DUMP_CORE
98 /*******************************************************************
99 prepare to dump a core file - carefully!
100 ********************************************************************/
101 static BOOL dump_core(void)
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));
114 #ifdef HAVE_GETRLIMIT
115 #ifdef RLIMIT_CORE
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));
125 #endif
126 #endif
129 DEBUG(0,("Dumping core in %s\n",dname));
130 abort();
131 return(True);
133 #endif
135 /****************************************************************************
136 exit the server
137 ****************************************************************************/
138 void exit_server(const char *reason)
140 static int firsttime=1;
142 if (!firsttime)
143 exit(0);
144 firsttime = 0;
146 DEBUG(2,("Closing connections\n"));
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
158 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
159 exit(0);
162 /****************************************************************************
163 Usage of the program.
164 ****************************************************************************/
166 static void usage(char *pname)
169 d_printf("Usage: %s [-DFSaioPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
170 d_printf(" [-O socket options] [-s services file]\n");
171 d_printf("\t-D Become a daemon (default)\n");
172 d_printf("\t-F Run daemon in foreground (for daemontools, etc)\n");
173 d_printf("\t-S Log to stdout\n");
174 d_printf("\t-a Append to log file (default)\n");
175 d_printf("\t-i Run interactive (not a daemon)\n" );
176 d_printf("\t-o Overwrite log file, don't append\n");
177 d_printf("\t-h Print usage\n");
178 d_printf("\t-? Print usage\n");
179 d_printf("\t-V Print version\n");
180 d_printf("\t-d debuglevel Set the debuglevel\n");
181 d_printf("\t-l log basename. Basename for log/debug files\n");
182 d_printf("\t-p port Listen on the specified port\n");
183 d_printf("\t-O socket options Socket options\n");
184 d_printf("\t-s services file. Filename of services file\n");
185 d_printf("\n");
188 /****************************************************************************
189 Create an fd_set containing all the sockets in the subnet structures,
190 plus the broadcast sockets.
191 ***************************************************************************/
193 static BOOL create_listen_fdset(void)
195 int i;
196 int num_interfaces = iface_count();
197 int s;
199 listen_set = (fd_set *)malloc(sizeof(fd_set));
200 if(listen_set == NULL) {
201 DEBUG(0,("create_listen_fdset: malloc fail !\n"));
202 return True;
205 #ifdef HAVE_ATEXIT
207 static int atexit_set;
208 if(atexit_set == 0) {
209 atexit_set=1;
212 #endif
214 FD_ZERO(listen_set);
216 if(lp_interfaces() && lp_bind_interfaces_only()) {
217 /* We have been given an interfaces line, and been
218 told to only bind to those interfaces. Create a
219 socket per interface and bind to only these.
222 if(num_interfaces > FD_SETSIZE) {
223 DEBUG(0,("create_listen_fdset: Too many interfaces specified to bind to. Number was %d max can be %d\n", num_interfaces, FD_SETSIZE));
224 return False;
227 /* Now open a listen socket for each of the interfaces. */
228 for(i = 0; i < num_interfaces; i++) {
229 struct in_addr *ifip = iface_n_ip(i);
231 if(ifip == NULL) {
232 DEBUG(0,("create_listen_fdset: interface %d has NULL IP address !\n", i));
233 continue;
235 s = open_socket_in(SOCK_STREAM, wins_port, 0, ifip->s_addr, True);
236 if(s == -1)
237 return False;
239 /* ready to listen */
240 set_socket_options(s,"SO_KEEPALIVE");
241 set_socket_options(s,user_socket_options);
243 if (listen(s, 5) == -1) {
244 DEBUG(5,("listen: %s\n",strerror(errno)));
245 close(s);
246 return False;
248 add_fd_to_sock_array(s);
249 FD_SET(s, listen_set);
251 } else {
252 /* Just bind to 0.0.0.0 - accept connections from anywhere. */
253 num_interfaces = 1;
255 /* open an incoming socket */
256 s = open_socket_in(SOCK_STREAM, wins_port, 0, interpret_addr(lp_socket_address()),True);
257 if (s == -1)
258 return(False);
260 /* ready to listen */
261 set_socket_options(s,"SO_KEEPALIVE");
262 set_socket_options(s,user_socket_options);
264 if (listen(s, 5) == -1) {
265 DEBUG(0,("create_listen_fdset: listen: %s\n", strerror(errno)));
266 close(s);
267 return False;
270 add_fd_to_sock_array(s);
271 FD_SET(s, listen_set);
274 return True;
277 /*******************************************************************
278 read a packet from a socket and parse it, returning a packet ready
279 to be used or put on the queue. This assumes a UDP socket
280 ******************************************************************/
281 static struct wins_packet_struct *read_wins_packet(int fd, int timeout)
283 struct wins_packet_struct *p;
284 GENERIC_PACKET *q;
285 struct BUFFER inbuf;
286 ssize_t len=0;
287 size_t total=0;
288 ssize_t ret;
289 BOOL ok = False;
291 inbuf.buffer=NULL;
292 inbuf.length=0;
293 inbuf.offset=0;
295 if(!grow_buffer(&inbuf, 4))
296 return NULL;
298 ok = (read(fd, inbuf.buffer,4) == 4);
299 if (!ok)
300 return NULL;
301 len = smb_len(inbuf.buffer);
303 if (len<=0)
304 return NULL;
306 if(!grow_buffer(&inbuf, len))
307 return NULL;
309 while (total < len) {
310 ret = read(fd, inbuf.buffer + total + 4, len - total);
311 if (ret == 0) {
312 DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(len - total), strerror(errno) ));
313 return NULL;
315 if (ret == -1) {
316 DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(len - total), strerror(errno) ));
317 return NULL;
319 total += ret;
322 q = (GENERIC_PACKET *)talloc(mem_ctx, sizeof(GENERIC_PACKET));
323 p = (struct wins_packet_struct *)talloc(mem_ctx, sizeof(*p));
324 if (q==NULL || p==NULL)
325 return NULL;
327 decode_generic_packet(&inbuf, q);
329 q->fd=fd;
331 p->next = NULL;
332 p->prev = NULL;
333 p->stop_packet = False;
334 p->timestamp = time(NULL);
335 p->fd = fd;
336 p->packet=q;
338 return p;
341 static struct wins_packet_struct *packet_queue = NULL;
343 /*******************************************************************
344 Queue a packet into a packet queue
345 ******************************************************************/
346 static void queue_packet(struct wins_packet_struct *packet)
348 struct wins_packet_struct *p;
350 if (!packet_queue) {
351 packet->prev = NULL;
352 packet->next = NULL;
353 packet_queue = packet;
354 return;
357 /* find the bottom */
358 for (p=packet_queue;p->next;p=p->next)
361 p->next = packet;
362 packet->next = NULL;
363 packet->prev = p;
366 /****************************************************************************
367 Listens for NMB or DGRAM packets, and queues them.
368 return True if the socket is dead
369 ***************************************************************************/
370 static BOOL listen_for_wins_packets(void)
372 int num_interfaces = iface_count();
373 fd_set fds;
374 int i, num, s, new_s;
375 struct timeval timeout;
377 if(listen_set == NULL) {
378 if(!create_listen_fdset()) {
379 DEBUG(0,("listen_for_packets: Fatal error. unable to create listen set. Exiting.\n"));
380 return True;
384 memcpy((char *)&fds, (char *)listen_set, sizeof(fd_set));
386 timeout.tv_sec = NMBD_SELECT_LOOP;
387 timeout.tv_usec = 0;
389 /* Prepare for the select - allow certain signals. */
391 BlockSignals(False, SIGTERM);
393 num = sys_select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
395 /* We can only take signals when we are in the select - block them again here. */
397 BlockSignals(True, SIGTERM);
399 if(num == -1)
400 return False;
402 for (; num > 0; num--) {
403 s = -1;
404 /* check the sockets we are only listening on, waiting to accept */
405 for (i=0; i<num_interfaces; i++) {
406 struct sockaddr addr;
407 socklen_t in_addrlen = sizeof(addr);
409 if(FD_ISSET(sock_array[i], &fds)) {
410 s = sock_array[i];
411 /* Clear this so we don't look at it again. */
412 FD_CLR(sock_array[i], &fds);
414 /* accept and add the new socket to the listen set */
415 new_s=accept(s, &addr, &in_addrlen);
417 if (new_s < 0)
418 continue;
420 DEBUG(5,("listen_for_wins_packets: new connection, old: %d, new : %d\n", s, new_s));
422 set_socket_options(new_s, "SO_KEEPALIVE");
423 set_socket_options(new_s, user_socket_options);
424 FD_SET(new_s, listen_set);
425 add_fd_to_sock_array(new_s);
430 * check for the sockets we are waiting data from
431 * either client sending datas
432 * or reply to our requests
434 for (i=num_interfaces; i<listen_number; i++) {
435 if(FD_ISSET(sock_array[i], &fds)) {
436 struct wins_packet_struct *packet = read_wins_packet(sock_array[i], timeout.tv_sec);
437 if (packet) {
438 packet->fd = sock_array[i];
439 queue_packet(packet);
441 DEBUG(2,("listen_for_wins_packets: some data on fd %d\n", sock_array[i]));
442 FD_CLR(sock_array[i], &fds);
443 break;
450 return False;
454 /*******************************************************************
455 Run elements off the packet queue till its empty
456 ******************************************************************/
458 static void run_wins_packet_queue(void)
460 struct wins_packet_struct *p;
462 while ((p = packet_queue)) {
463 packet_queue = p->next;
464 if (packet_queue)
465 packet_queue->prev = NULL;
466 p->next = p->prev = NULL;
468 construct_reply(p);
470 /* if it was a stop assoc, close the connection */
471 if (p->stop_packet) {
472 FD_CLR(p->fd, listen_set);
473 remove_fd_from_sock_array(p->fd);
474 close(p->fd);
479 /**************************************************************************** **
480 The main select loop.
481 **************************************************************************** */
482 static void process(void)
485 while( True ) {
486 time_t t = time(NULL);
488 /* check for internal messages */
489 message_dispatch();
491 if(listen_for_wins_packets())
492 return;
494 run_wins_packet_queue();
496 run_pull_replication(t);
498 run_push_replication(t);
501 * Reload the services file if we got a sighup.
504 if(reload_after_sighup) {
505 reload_services( True );
506 reopen_logs();
507 reload_after_sighup = False;
510 /* free temp memory */
511 talloc_destroy_pool(mem_ctx);
513 /* free up temp memory */
514 lp_talloc_free();
516 } /* process */
518 /****************************************************************************
519 main program
520 ****************************************************************************/
521 int main(int argc,char *argv[])
523 extern char *optarg;
524 /* shall I run as a daemon */
525 BOOL is_daemon = False;
526 BOOL interactive = False;
527 BOOL specified_logfile = False;
528 BOOL Fork = True;
529 BOOL log_stdout = False;
530 int opt;
531 pstring logfile;
533 #ifdef HAVE_SET_AUTH_PARAMETERS
534 set_auth_parameters(argc,argv);
535 #endif
537 /* this is for people who can't start the program correctly */
538 while (argc > 1 && (*argv[1] != '-')) {
539 argv++;
540 argc--;
543 while ( EOF != (opt = getopt(argc, argv, "FSO:l:s:d:Dp:h?Vaiof:")) )
544 switch (opt) {
545 case 'F':
546 Fork = False;
547 break;
548 case 'S':
549 log_stdout = True;
550 break;
551 case 'O':
552 pstrcpy(user_socket_options,optarg);
553 break;
555 case 's':
556 pstrcpy(dyn_CONFIGFILE,optarg);
557 break;
559 case 'l':
560 specified_logfile = True;
561 slprintf(logfile, sizeof(logfile)-1, "%s/log.wrepld", optarg);
562 lp_set_logfile(logfile);
563 break;
565 case 'i':
566 interactive = True;
567 Fork = False;
568 log_stdout = True;
569 break;
571 case 'D':
572 is_daemon = True;
573 break;
575 case 'd':
576 if (*optarg == 'A')
577 DEBUGLEVEL = 10000;
578 else
579 DEBUGLEVEL = atoi(optarg);
580 break;
582 case 'p':
583 wins_port = atoi(optarg);
584 break;
586 case 'h':
587 case '?':
588 usage(argv[0]);
589 exit(0);
590 break;
592 case 'V':
593 d_printf("Version %s\n",VERSION);
594 exit(0);
595 break;
596 default:
597 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
598 usage(argv[0]);
599 exit(1);
601 if (log_stdout && Fork) {
602 d_printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
603 usage(argv[0]);
604 exit(1);
607 #ifdef HAVE_SETLUID
608 /* needed for SecureWare on SCO */
609 setluid(0);
610 #endif
612 sec_init();
614 load_case_tables();
616 if(!specified_logfile) {
617 slprintf(logfile, sizeof(logfile)-1, "%s/log.wrepld",
618 dyn_LOGFILEBASE);
619 lp_set_logfile(logfile);
622 set_remote_machine_name("wrepld", False);
624 setup_logging(argv[0],log_stdout);
626 /* we want to re-seed early to prevent time delays causing
627 client problems at a later date. (tridge) */
628 generate_random_buffer(NULL, 0, False);
630 /* make absolutely sure we run as root - to handle cases where people
631 are crazy enough to have it setuid */
633 gain_root_privilege();
634 gain_root_group_privilege();
636 fault_setup((void (*)(void *))exit_server);
637 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
639 /* we are never interested in SIGPIPE */
640 BlockSignals(True,SIGPIPE);
642 #if defined(SIGFPE)
643 /* we are never interested in SIGFPE */
644 BlockSignals(True,SIGFPE);
645 #endif
647 #if defined(SIGUSR2)
648 /* We are no longer interested in USR2 */
649 BlockSignals(True,SIGUSR2);
650 #endif
652 /* POSIX demands that signals are inherited. If the invoking process has
653 * these signals masked, we will have problems, as we won't recieve them. */
654 BlockSignals(False, SIGHUP);
655 BlockSignals(False, SIGUSR1);
657 /* we want total control over the permissions on created files,
658 so set our umask to 0 */
659 umask(0);
661 reopen_logs();
663 DEBUG(1,( "wrepld version %s started.\n", VERSION));
664 DEBUGADD(1,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
666 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
667 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
669 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
670 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
671 exit(1);
675 * Do this before reload_services.
678 if (!reload_services(False))
679 return(-1);
681 if (!init_names())
682 return -1;
684 #ifdef WITH_PROFILE
685 if (!profile_setup(False)) {
686 DEBUG(0,("ERROR: failed to setup profiling\n"));
687 return -1;
689 #endif
691 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
693 DEBUG(3,( "loaded services\n"));
695 if (!is_daemon && !is_a_socket(0)) {
696 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
697 is_daemon = True;
700 if (is_daemon && !interactive) {
701 DEBUG( 3, ( "Becoming a daemon.\n" ) );
702 become_daemon(Fork);
705 #if HAVE_SETPGID
707 * If we're interactive we want to set our own process group for
708 * signal management.
710 if (interactive)
711 setpgid( (pid_t)0, (pid_t)0);
712 #endif
714 if (!directory_exist(lp_lockdir(), NULL)) {
715 mkdir(lp_lockdir(), 0755);
718 if (is_daemon) {
719 pidfile_create("wrepld");
722 if (!message_init()) {
723 exit(1);
726 /* Initialise the memory context */
727 mem_ctx=talloc_init("wins repl talloc ctx");
729 /* initialise the global partners table */
730 partner_count=init_wins_partner_table();
732 /* We can only take signals in the select. */
733 BlockSignals( True, SIGTERM );
735 process();
737 exit_server("normal exit");
738 return(0);