nmbd and smbd had different behavior with respect to log files. nmbd would
[samba.git] / source3 / smbd / server.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Main SMB server routines
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23 #include "trans2.h"
24
25 pstring servicesf = CONFIGFILE;
26 extern pstring debugf;
27 extern fstring global_myworkgroup;
28 extern pstring global_myname;
29
30 int am_parent = 1;
31
32 /* the last message the was processed */
33 int last_message = -1;
34
35 /* a useful macro to debug the last message processed */
36 #define LAST_MESSAGE() smb_fn_name(last_message)
37
38 extern pstring scope;
39 extern int DEBUGLEVEL;
40
41 extern pstring user_socket_options;
42
43 #ifdef WITH_DFS
44 extern int dcelogin_atmost_once;
45 #endif /* WITH_DFS */
46
47
48 extern fstring remote_machine;
49 extern pstring OriginalDir;
50 extern pstring myhostname;
51
52 /****************************************************************************
53   when exiting, take the whole family
54 ****************************************************************************/
55 void *dflt_sig(void)
56 {
57         exit_server("caught signal");
58         return NULL;
59 }
60
61 /****************************************************************************
62   Send a SIGTERM to our process group.
63 *****************************************************************************/
64 void  killkids(void)
65 {
66         if(am_parent) kill(0,SIGTERM);
67 }
68
69
70
71 /****************************************************************************
72   this is called when the client exits abruptly
73   **************************************************************************/
74 static void sig_pipe(int sig)
75 {
76         struct cli_state *cli;
77         BlockSignals(True,SIGPIPE);
78
79         if ((cli = server_client()) && cli->initialised) {
80                 DEBUG(3,("lost connection to password server\n"));
81                 cli_shutdown(cli);
82                 BlockSignals(False,SIGPIPE);
83                 return;
84         }
85
86         exit_server("Got sigpipe\n");
87 }
88
89 /****************************************************************************
90   open the socket communication
91 ****************************************************************************/
92 static BOOL open_sockets_inetd(void)
93 {
94         extern int Client;
95
96         /* Started from inetd. fd 0 is the socket. */
97         /* We will abort gracefully when the client or remote system 
98            goes away */
99         CatchSignal(SIGPIPE, SIGNAL_CAST sig_pipe);
100         Client = dup(0);
101         
102         /* close our standard file descriptors */
103         close_low_fds();
104         
105         set_socket_options(Client,"SO_KEEPALIVE");
106         set_socket_options(Client,user_socket_options);
107
108         return True;
109 }
110
111
112 /****************************************************************************
113   open the socket communication
114 ****************************************************************************/
115 static BOOL open_sockets(BOOL is_daemon,int port)
116 {
117         extern int Client;
118         int num_interfaces = iface_count();
119         int fd_listenset[FD_SETSIZE];
120         fd_set listen_set;
121         int s;
122         int i;
123
124         if (!is_daemon) {
125                 return open_sockets_inetd();
126         }
127
128                 
129 #ifdef HAVE_ATEXIT
130         {
131                 static int atexit_set;
132                 if(atexit_set == 0) {
133                         atexit_set=1;
134                         atexit(killkids);
135                 }
136         }
137 #endif
138
139         /* Stop zombies */
140         CatchChild();
141                 
142                 
143         FD_ZERO(&listen_set);
144
145         if(lp_interfaces() && lp_bind_interfaces_only()) {
146                 /* We have been given an interfaces line, and been 
147                    told to only bind to those interfaces. Create a
148                    socket per interface and bind to only these.
149                 */
150                 
151                 if(num_interfaces > FD_SETSIZE) {
152                         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
153 max can be %d\n", 
154                                  num_interfaces, FD_SETSIZE));
155                         return False;
156                 }
157                 
158                 /* Now open a listen socket for each of the
159                    interfaces. */
160                 for(i = 0; i < num_interfaces; i++) {
161                         struct in_addr *ifip = iface_n_ip(i);
162                         
163                         if(ifip == NULL) {
164                                 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
165                                 continue;
166                         }
167                         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr);
168                         if(s == -1)
169                                 return False;
170                                 /* ready to listen */
171                         if (listen(s, 5) == -1) {
172                                 DEBUG(0,("listen: %s\n",strerror(errno)));
173                                 close(s);
174                                 return False;
175                         }
176                         FD_SET(s,&listen_set);
177                 }
178         } else {
179                 /* Just bind to 0.0.0.0 - accept connections
180                    from anywhere. */
181                 num_interfaces = 1;
182                 
183                 /* open an incoming socket */
184                 s = open_socket_in(SOCK_STREAM, port, 0,
185                                    interpret_addr(lp_socket_address()));
186                 if (s == -1)
187                         return(False);
188                 
189                 /* ready to listen */
190                 if (listen(s, 5) == -1) {
191                         DEBUG(0,("open_sockets: listen: %s\n",
192                                  strerror(errno)));
193                         close(s);
194                         return False;
195                 }
196                 
197                 fd_listenset[0] = s;
198                 FD_SET(s,&listen_set);
199         } 
200
201         /* now accept incoming connections - forking a new process
202            for each incoming connection */
203         DEBUG(2,("waiting for a connection\n"));
204         while (1) {
205                 fd_set lfds;
206                 int num;
207                 
208                 memcpy((char *)&lfds, (char *)&listen_set, 
209                        sizeof(listen_set));
210                 
211                 num = sys_select(&lfds,NULL);
212                 
213                 if (num == -1 && errno == EINTR)
214                         continue;
215                 
216                 /* Find the sockets that are read-ready -
217                    accept on these. */
218                 for( ; num > 0; num--) {
219                         struct sockaddr addr;
220                         int in_addrlen = sizeof(addr);
221                         
222                         s = -1;
223                         for(i = 0; i < num_interfaces; i++) {
224                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
225                                         s = fd_listenset[i];
226                                         /* Clear this so we don't look
227                                            at it again. */
228                                         FD_CLR(fd_listenset[i],&lfds);
229                                         break;
230                                 }
231                         }
232
233                         Client = accept(s,&addr,&in_addrlen);
234                         
235                         if (Client == -1 && errno == EINTR)
236                                 continue;
237                         
238                         if (Client == -1) {
239                                 DEBUG(0,("open_sockets: accept: %s\n",
240                                          strerror(errno)));
241                                 continue;
242                         }
243                         
244                         if (Client != -1 && fork()==0) {
245                                 /* Child code ... */
246                                 
247                                 CatchSignal(SIGPIPE, 
248                                             SIGNAL_CAST sig_pipe);
249                                 
250                                 /* close the listening socket(s) */
251                                 for(i = 0; i < num_interfaces; i++)
252                                         close(fd_listenset[i]);
253                                 
254                                 /* close our standard file
255                                    descriptors */
256                                 close_low_fds();
257                                 am_parent = 0;
258                                 
259                                 set_socket_options(Client,"SO_KEEPALIVE");
260                                 set_socket_options(Client,user_socket_options);
261                                 
262                                 /* Reset global variables in util.c so
263                                    that client substitutions will be
264                                    done correctly in the process.  */
265                                 reset_globals_after_fork();
266                                 return True; 
267                         }
268                         /* The parent doesn't need this socket */
269                         close(Client); 
270
271                         /* Force parent to check log size after
272                          * spawning child.  Fix from
273                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
274                          * parent smbd will log to logserver.smb.  It
275                          * writes only two messages for each child
276                          * started/finished. But each child writes,
277                          * say, 50 messages also in logserver.smb,
278                          * begining with the debug_count of the
279                          * parent, before the child opens its own log
280                          * file logserver.client. In a worst case
281                          * scenario the size of logserver.smb would be
282                          * checked after about 50*50=2500 messages
283                          * (ca. 100kb).
284                          * */
285                         force_check_log_size();
286  
287                 } /* end for num */
288         } /* end while 1 */
289
290         return True;
291 }
292
293 /****************************************************************************
294   reload the services file
295   **************************************************************************/
296 BOOL reload_services(BOOL test)
297 {
298         BOOL ret;
299
300         if (lp_loaded()) {
301                 pstring fname;
302                 pstrcpy(fname,lp_configfile());
303                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
304                         pstrcpy(servicesf,fname);
305                         test = False;
306                 }
307         }
308
309         reopen_logs();
310
311         if (test && !lp_file_list_changed())
312                 return(True);
313
314         lp_killunused(conn_snum_used);
315
316         ret = lp_load(servicesf,False,False,True);
317
318         load_printers();
319
320         /* perhaps the config filename is now set */
321         if (!test)
322                 reload_services(True);
323
324         reopen_logs();
325
326         load_interfaces();
327
328         {
329                 extern int Client;
330                 if (Client != -1) {      
331                         set_socket_options(Client,"SO_KEEPALIVE");
332                         set_socket_options(Client,user_socket_options);
333                 }
334         }
335
336         reset_mangled_cache();
337
338         /* this forces service parameters to be flushed */
339         become_service(NULL,True);
340
341         return(ret);
342 }
343
344
345
346 /****************************************************************************
347 this prevents zombie child processes
348 ****************************************************************************/
349 BOOL reload_after_sighup = False;
350
351 static void sig_hup(int sig)
352 {
353         BlockSignals(True,SIGHUP);
354         DEBUG(0,("Got SIGHUP\n"));
355
356         /*
357          * Fix from <branko.cibej@hermes.si> here.
358          * We used to reload in the signal handler - this
359          * is a *BIG* no-no.
360          */
361
362         reload_after_sighup = True;
363         BlockSignals(False,SIGHUP);
364 }
365
366
367
368 #if DUMP_CORE
369 /*******************************************************************
370 prepare to dump a core file - carefully!
371 ********************************************************************/
372 static BOOL dump_core(void)
373 {
374         char *p;
375         pstring dname;
376         pstrcpy(dname,debugf);
377         if ((p=strrchr(dname,'/'))) *p=0;
378         pstrcat(dname,"/corefiles");
379         mkdir(dname,0700);
380         sys_chown(dname,getuid(),getgid());
381         chmod(dname,0700);
382         if (chdir(dname)) return(False);
383         umask(~(0700));
384
385 #ifdef HAVE_GETRLIMIT
386 #ifdef RLIMIT_CORE
387         {
388                 struct rlimit rlp;
389                 getrlimit(RLIMIT_CORE, &rlp);
390                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
391                 setrlimit(RLIMIT_CORE, &rlp);
392                 getrlimit(RLIMIT_CORE, &rlp);
393                 DEBUG(3,("Core limits now %d %d\n",
394                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
395         }
396 #endif
397 #endif
398
399
400         DEBUG(0,("Dumping core in %s\n",dname));
401         abort();
402         return(True);
403 }
404 #endif
405
406
407 /****************************************************************************
408 exit the server
409 ****************************************************************************/
410 void exit_server(char *reason)
411 {
412         static int firsttime=1;
413         extern char *last_inbuf;
414
415
416         if (!firsttime) exit(0);
417         firsttime = 0;
418
419         unbecome_user();
420         DEBUG(2,("Closing connections\n"));
421
422         conn_close_all();
423
424 #ifdef WITH_DFS
425         if (dcelogin_atmost_once) {
426                 dfs_unlogin();
427         }
428 #endif
429
430         if (!reason) {   
431                 int oldlevel = DEBUGLEVEL;
432                 DEBUGLEVEL = 10;
433                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
434                 if (last_inbuf)
435                         show_msg(last_inbuf);
436                 DEBUGLEVEL = oldlevel;
437                 DEBUG(0,("===============================================================\n"));
438 #if DUMP_CORE
439                 if (dump_core()) return;
440 #endif
441         }    
442
443         locking_end();
444
445         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
446         exit(0);
447 }
448
449
450
451 /****************************************************************************
452   initialise connect, service and file structs
453 ****************************************************************************/
454 static void init_structs(void )
455 {
456         get_myname(myhostname,NULL);
457
458         /*
459          * Set the machine NETBIOS name if not already
460          * set from the config file.
461          */
462
463         if (!*global_myname) {
464                 char *p;
465                 fstrcpy( global_myname, myhostname );
466                 p = strchr( global_myname, '.' );
467                 if (p) 
468                         *p = 0;
469         }
470
471         strupper( global_myname );
472
473         conn_init();
474
475         file_init();
476
477         /* for RPC pipes */
478         init_rpc_pipe_hnd();
479
480         /* for LSA handles */
481         init_lsa_policy_hnd();
482
483         init_dptrs();
484 }
485
486 /****************************************************************************
487 usage on the program
488 ****************************************************************************/
489 static void usage(char *pname)
490 {
491         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
492
493         printf("Usage: %s [-D] [-p port] [-d debuglevel] ", pname);
494         printf("[-l log basename] [-s services file]\n" );
495         printf("Version %s\n",VERSION);
496         printf("\t-D                    become a daemon\n");
497         printf("\t-p port               listen on the specified port\n");
498         printf("\t-d debuglevel         set the debuglevel\n");
499         printf("\t-l log basename.      Basename for log/debug files\n");
500         printf("\t-s services file.     Filename of services file\n");
501         printf("\t-P                    passive only\n");
502         printf("\t-a                    append to log file (default)\n");
503         printf("\t-o                    overwrite log file, don't append\n");
504         printf("\n");
505 }
506
507
508 /****************************************************************************
509   main program
510 ****************************************************************************/
511  int main(int argc,char *argv[])
512 {
513         extern BOOL append_log;
514         /* shall I run as a daemon */
515         BOOL is_daemon = False;
516         int port = SMB_PORT;
517         int opt;
518         extern char *optarg;
519         
520 #ifdef HAVE_SET_AUTH_PARAMETERS
521         set_auth_parameters(argc,argv);
522 #endif
523
524 #ifdef HAVE_SETLUID
525         /* needed for SecureWare on SCO */
526         setluid(0);
527 #endif
528
529         append_log = True;
530
531         TimeInit();
532
533         pstrcpy(debugf,SMBLOGFILE);  
534
535         pstrcpy(remote_machine, "smb");
536
537         setup_logging(argv[0],False);
538
539         charset_initialise();
540
541         /* make absolutely sure we run as root - to handle cases where people
542            are crazy enough to have it setuid */
543 #ifdef HAVE_SETRESUID
544         setresuid(0,0,0);
545 #else
546         setuid(0);
547         seteuid(0);
548         setuid(0);
549         seteuid(0);
550 #endif
551
552         fault_setup((void (*)(void *))exit_server);
553         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
554
555         /* we want total control over the permissions on created files,
556            so set our umask to 0 */
557         umask(0);
558
559         GetWd(OriginalDir);
560
561         init_uid();
562
563         /* this is for people who can't start the program correctly */
564         while (argc > 1 && (*argv[1] != '-')) {
565                 argv++;
566                 argc--;
567         }
568
569         while ( EOF != (opt = getopt(argc, argv, "O:i:l:s:d:Dp:h?Paof:")) )
570                 switch (opt)  {
571                 case 'O':
572                         pstrcpy(user_socket_options,optarg);
573                         break;
574
575                 case 'i':
576                         pstrcpy(scope,optarg);
577                         break;
578
579                 case 'P':
580                         {
581                                 extern BOOL passive;
582                                 passive = True;
583                         }
584                         break;  
585
586                 case 's':
587                         pstrcpy(servicesf,optarg);
588                         break;
589
590                 case 'l':
591                         pstrcpy(debugf,optarg);
592                         break;
593
594                 case 'a':
595                         append_log = True;
596                         break;
597
598                 case 'o':
599                         append_log = False;
600                         break;
601
602                 case 'D':
603                         is_daemon = True;
604                         break;
605
606                 case 'd':
607                         if (*optarg == 'A')
608                                 DEBUGLEVEL = 10000;
609                         else
610                                 DEBUGLEVEL = atoi(optarg);
611                         break;
612
613                 case 'p':
614                         port = atoi(optarg);
615                         break;
616
617                 case 'h':
618                 case '?':
619                         usage(argv[0]);
620                         exit(0);
621                         break;
622
623                 default:
624                         usage(argv[0]);
625                         exit(1);
626                 }
627
628         reopen_logs();
629
630         DEBUG(1,( "smbd version %s started.\n", VERSION));
631         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1997\n"));
632
633         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
634                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
635
636         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
637                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
638                 exit(1);
639         }
640
641         init_structs();
642         
643         if (!reload_services(False))
644                 return(-1);     
645
646 #ifdef WITH_SSL
647         {
648                 extern BOOL sslEnabled;
649                 sslEnabled = lp_ssl_enabled();
650                 if(sslEnabled)
651                         sslutil_init(True);
652         }
653 #endif        /* WITH_SSL */
654
655         codepage_initialise(lp_client_code_page());
656
657         pstrcpy(global_myworkgroup, lp_workgroup());
658
659         if(!pdb_generate_machine_sid()) {
660                 DEBUG(0,("ERROR: Samba cannot get a machine SID.\n"));
661                 exit(1);
662         }
663
664         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
665         
666         /* Setup the signals that allow the debug log level
667            to by dynamically changed. */
668  
669         /* If we are using the malloc debug code we can't use
670            SIGUSR1 and SIGUSR2 to do debug level changes. */
671         
672 #ifndef MEM_MAN
673 #if defined(SIGUSR1)
674         CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
675 #endif /* SIGUSR1 */
676    
677 #if defined(SIGUSR2)
678         CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
679 #endif /* SIGUSR2 */
680 #endif /* MEM_MAN */
681
682         DEBUG(3,( "loaded services\n"));
683
684         if (!is_daemon && !is_a_socket(0)) {
685                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
686                 is_daemon = True;
687         }
688
689         if (is_daemon) {
690                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
691                 become_daemon();
692         }
693
694         if (!directory_exist(lp_lockdir(), NULL)) {
695                 mkdir(lp_lockdir(), 0755);
696         }
697
698         if (is_daemon) {
699                 pidfile_create("smbd");
700         }
701
702         if (!open_sockets(is_daemon,port))
703                 exit(1);
704
705         if (!locking_init(0))
706                 exit(1);
707
708         if(!initialize_password_db())
709                 exit(1);
710
711         /* possibly reload the services file. */
712         reload_services(True);
713         
714         if (*lp_rootdir()) {
715                 if (sys_chroot(lp_rootdir()) == 0)
716                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
717         }
718
719         /* Setup the oplock IPC socket. */
720         if( !open_oplock_ipc() )
721                 exit(1);
722
723         smbd_process();
724         close_sockets();
725         
726         exit_server("normal exit");
727         return(0);
728 }