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