printf() -> d_printf()
[tprouty/samba.git] / source / 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
24 pstring servicesf = CONFIGFILE;
25 extern pstring debugf;
26 extern fstring global_myworkgroup;
27 extern pstring global_myname;
28
29 int am_parent = 1;
30
31 /* the last message the was processed */
32 int last_message = -1;
33
34 /* a useful macro to debug the last message processed */
35 #define LAST_MESSAGE() smb_fn_name(last_message)
36
37 extern int DEBUGLEVEL;
38
39 extern pstring user_socket_options;
40
41 #ifdef WITH_DFS
42 extern int dcelogin_atmost_once;
43 #endif /* WITH_DFS */
44
45 extern fstring remote_machine;
46
47 /* really we should have a top level context structure that has the
48    client file descriptor as an element. That would require a major rewrite :(
49
50    the following 2 functions are an alternative - they make the file
51    descriptor private to smbd
52  */
53 static int server_fd = -1;
54
55 int smbd_server_fd(void)
56 {
57         return server_fd;
58 }
59
60 void smbd_set_server_fd(int fd)
61 {
62         server_fd = fd;
63         client_setfd(fd);
64 }
65
66 /****************************************************************************
67   when exiting, take the whole family
68 ****************************************************************************/
69 static void *dflt_sig(void)
70 {
71         exit_server("caught signal");
72         return NULL;
73 }
74
75 /****************************************************************************
76   Send a SIGTERM to our process group.
77 *****************************************************************************/
78 static void  killkids(void)
79 {
80         if(am_parent) kill(0,SIGTERM);
81 }
82
83 /****************************************************************************
84   process a sam sync message - not sure whether to do this here or
85   somewhere else
86 ****************************************************************************/
87 static void msg_sam_sync(int msg_type, pid_t pid, void *buf, size_t len)
88 {
89         DEBUG(10, ("** sam sync message received, ignoring\n"));
90 }
91
92 /****************************************************************************
93   process a sam sync replicate message - not sure whether to do this here or
94   somewhere else
95 ****************************************************************************/
96 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
97 {
98         uint32 low_serial;
99
100         if (len != sizeof(uint32))
101                 return;
102
103         low_serial = *((uint32 *)buf);
104
105         DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
106                   low_serial));
107 }
108
109 /****************************************************************************
110   open the socket communication
111 ****************************************************************************/
112 static BOOL open_sockets_inetd(void)
113 {
114         /* Started from inetd. fd 0 is the socket. */
115         /* We will abort gracefully when the client or remote system 
116            goes away */
117         smbd_set_server_fd(dup(0));
118         
119         /* close our standard file descriptors */
120         close_low_fds();
121         
122         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
123         set_socket_options(smbd_server_fd(),user_socket_options);
124
125         return True;
126 }
127
128
129 /****************************************************************************
130   open the socket communication
131 ****************************************************************************/
132 static BOOL open_sockets(BOOL is_daemon,int port)
133 {
134         int num_interfaces = iface_count();
135         int fd_listenset[FD_SETSIZE];
136         fd_set listen_set;
137         int s;
138         int i;
139
140         if (!is_daemon) {
141                 return open_sockets_inetd();
142         }
143
144                 
145 #ifdef HAVE_ATEXIT
146         {
147                 static int atexit_set;
148                 if(atexit_set == 0) {
149                         atexit_set=1;
150                         atexit(killkids);
151                 }
152         }
153 #endif
154
155         /* Stop zombies */
156         CatchChild();
157                 
158                 
159         FD_ZERO(&listen_set);
160
161         if(lp_interfaces() && lp_bind_interfaces_only()) {
162                 /* We have been given an interfaces line, and been 
163                    told to only bind to those interfaces. Create a
164                    socket per interface and bind to only these.
165                 */
166                 
167                 if(num_interfaces > FD_SETSIZE) {
168                         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
169 max can be %d\n", 
170                                  num_interfaces, FD_SETSIZE));
171                         return False;
172                 }
173                 
174                 /* Now open a listen socket for each of the
175                    interfaces. */
176                 for(i = 0; i < num_interfaces; i++) {
177                         struct in_addr *ifip = iface_n_ip(i);
178                         
179                         if(ifip == NULL) {
180                                 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
181                                 continue;
182                         }
183                         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
184                         if(s == -1)
185                                 return False;
186
187                         /* ready to listen */
188                         set_socket_options(s,"SO_KEEPALIVE"); 
189                         set_socket_options(s,user_socket_options);
190       
191                         if (listen(s, 5) == -1) {
192                                 DEBUG(0,("listen: %s\n",strerror(errno)));
193                                 close(s);
194                                 return False;
195                         }
196                         FD_SET(s,&listen_set);
197                 }
198         } else {
199                 /* Just bind to 0.0.0.0 - accept connections
200                    from anywhere. */
201                 num_interfaces = 1;
202                 
203                 /* open an incoming socket */
204                 s = open_socket_in(SOCK_STREAM, port, 0,
205                                    interpret_addr(lp_socket_address()),True);
206                 if (s == -1)
207                         return(False);
208                 
209                 /* ready to listen */
210                 set_socket_options(s,"SO_KEEPALIVE"); 
211                 set_socket_options(s,user_socket_options);
212
213                 if (listen(s, 5) == -1) {
214                         DEBUG(0,("open_sockets: listen: %s\n",
215                                  strerror(errno)));
216                         close(s);
217                         return False;
218                 }
219                 
220                 fd_listenset[0] = s;
221                 FD_SET(s,&listen_set);
222         } 
223
224         /* Listen to messages */
225
226         message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
227         message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
228
229         /* now accept incoming connections - forking a new process
230            for each incoming connection */
231         DEBUG(2,("waiting for a connection\n"));
232         while (1) {
233                 fd_set lfds;
234                 int num;
235                 
236                 /* Free up temporary memory from the main smbd. */
237                 lp_talloc_free();
238
239                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
240                 message_dispatch();
241
242                 memcpy((char *)&lfds, (char *)&listen_set, 
243                        sizeof(listen_set));
244                 
245                 num = sys_select(FD_SETSIZE,&lfds,NULL);
246                 
247                 if (num == -1 && errno == EINTR) {
248                         extern VOLATILE sig_atomic_t reload_after_sighup;
249
250                         /* check for sighup processing */
251                         if (reload_after_sighup) {
252                                 unbecome_user();
253                                 DEBUG(1,("Reloading services after SIGHUP\n"));
254                                 reload_services(False);
255                                 reload_after_sighup = False;
256                         }
257
258                         continue;
259                 }
260                 
261                 /* check if we need to reload services */
262                 check_reload(time(NULL));
263
264                 /* Find the sockets that are read-ready -
265                    accept on these. */
266                 for( ; num > 0; num--) {
267                         struct sockaddr addr;
268                         socklen_t in_addrlen = sizeof(addr);
269                         
270                         s = -1;
271                         for(i = 0; i < num_interfaces; i++) {
272                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
273                                         s = fd_listenset[i];
274                                         /* Clear this so we don't look
275                                            at it again. */
276                                         FD_CLR(fd_listenset[i],&lfds);
277                                         break;
278                                 }
279                         }
280
281                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
282                         
283                         if (smbd_server_fd() == -1 && errno == EINTR)
284                                 continue;
285                         
286                         if (smbd_server_fd() == -1) {
287                                 DEBUG(0,("open_sockets: accept: %s\n",
288                                          strerror(errno)));
289                                 continue;
290                         }
291                         
292                         if (smbd_server_fd() != -1 && sys_fork()==0) {
293                                 /* Child code ... */
294                                 
295                                 /* close the listening socket(s) */
296                                 for(i = 0; i < num_interfaces; i++)
297                                         close(fd_listenset[i]);
298                                 
299                                 /* close our standard file
300                                    descriptors */
301                                 close_low_fds();
302                                 am_parent = 0;
303                                 
304                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
305                                 set_socket_options(smbd_server_fd(),user_socket_options);
306                                 
307                                 /* Reset global variables in util.c so
308                                    that client substitutions will be
309                                    done correctly in the process.  */
310                                 reset_globals_after_fork();
311
312                                 /* tdb needs special fork handling */
313                                 tdb_reopen_all();
314
315                                 return True; 
316                         }
317                         /* The parent doesn't need this socket */
318                         close(smbd_server_fd()); 
319
320                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
321                                 Clear the closed fd info out of server_fd --
322                                 and more importantly, out of client_fd in
323                                 util_sock.c, to avoid a possible
324                                 getpeername failure if we reopen the logs
325                                 and use %I in the filename.
326                         */
327
328                         smbd_set_server_fd(-1);
329
330                         /* Force parent to check log size after
331                          * spawning child.  Fix from
332                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
333                          * parent smbd will log to logserver.smb.  It
334                          * writes only two messages for each child
335                          * started/finished. But each child writes,
336                          * say, 50 messages also in logserver.smb,
337                          * begining with the debug_count of the
338                          * parent, before the child opens its own log
339                          * file logserver.client. In a worst case
340                          * scenario the size of logserver.smb would be
341                          * checked after about 50*50=2500 messages
342                          * (ca. 100kb).
343                          * */
344                         force_check_log_size();
345  
346                 } /* end for num */
347         } /* end while 1 */
348
349 /* NOTREACHED   return True; */
350 }
351
352 /****************************************************************************
353   reload the services file
354   **************************************************************************/
355 BOOL reload_services(BOOL test)
356 {
357         BOOL ret;
358         
359         if (lp_loaded()) {
360                 pstring fname;
361                 pstrcpy(fname,lp_configfile());
362                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
363                         pstrcpy(servicesf,fname);
364                         test = False;
365                 }
366         }
367
368         reopen_logs();
369
370         if (test && !lp_file_list_changed())
371                 return(True);
372
373         lp_killunused(conn_snum_used);
374         
375         ret = lp_load(servicesf,False,False,True);
376
377         load_printers();
378
379         /* perhaps the config filename is now set */
380         if (!test)
381                 reload_services(True);
382
383         reopen_logs();
384
385         load_interfaces();
386
387         {
388                 if (smbd_server_fd() != -1) {      
389                         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
390                         set_socket_options(smbd_server_fd(),user_socket_options);
391                 }
392         }
393
394         reset_mangled_cache();
395         reset_stat_cache();
396
397         /* this forces service parameters to be flushed */
398         become_service(NULL,True);
399
400         return(ret);
401 }
402
403
404
405 /****************************************************************************
406  Catch a sighup.
407 ****************************************************************************/
408
409 VOLATILE sig_atomic_t reload_after_sighup = False;
410
411 static void sig_hup(int sig)
412 {
413         BlockSignals(True,SIGHUP);
414         DEBUG(0,("Got SIGHUP\n"));
415
416         sys_select_signal();
417         reload_after_sighup = True;
418         BlockSignals(False,SIGHUP);
419 }
420
421
422
423 #if DUMP_CORE
424 /*******************************************************************
425 prepare to dump a core file - carefully!
426 ********************************************************************/
427 static BOOL dump_core(void)
428 {
429         char *p;
430         pstring dname;
431         pstrcpy(dname,debugf);
432         if ((p=strrchr_m(dname,'/'))) *p=0;
433         pstrcat(dname,"/corefiles");
434         mkdir(dname,0700);
435         sys_chown(dname,getuid(),getgid());
436         chmod(dname,0700);
437         if (chdir(dname)) return(False);
438         umask(~(0700));
439
440 #ifdef HAVE_GETRLIMIT
441 #ifdef RLIMIT_CORE
442         {
443                 struct rlimit rlp;
444                 getrlimit(RLIMIT_CORE, &rlp);
445                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
446                 setrlimit(RLIMIT_CORE, &rlp);
447                 getrlimit(RLIMIT_CORE, &rlp);
448                 DEBUG(3,("Core limits now %d %d\n",
449                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
450         }
451 #endif
452 #endif
453
454
455         DEBUG(0,("Dumping core in %s\n",dname));
456         abort();
457         return(True);
458 }
459 #endif
460
461 /****************************************************************************
462 update the current smbd process count
463 ****************************************************************************/
464
465 static void decrement_smbd_process_count(void)
466 {
467         int total_smbds;
468
469         if (lp_max_smbd_processes()) {
470                 total_smbds = 0;
471                 tdb_change_int_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
472         }
473 }
474
475 /****************************************************************************
476 exit the server
477 ****************************************************************************/
478 void exit_server(char *reason)
479 {
480         static int firsttime=1;
481         extern char *last_inbuf;
482
483
484         if (!firsttime) exit(0);
485         firsttime = 0;
486
487         unbecome_user();
488         DEBUG(2,("Closing connections\n"));
489
490         conn_close_all();
491
492         invalidate_all_vuids();
493
494         /* delete our entry in the connections database. */
495         yield_connection(NULL,"",MAXSTATUS);
496
497         respond_to_all_remaining_local_messages();
498         decrement_smbd_process_count();
499
500 #ifdef WITH_DFS
501         if (dcelogin_atmost_once) {
502                 dfs_unlogin();
503         }
504 #endif
505
506         if (!reason) {   
507                 int oldlevel = DEBUGLEVEL;
508                 DEBUGLEVEL = 10;
509                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
510                 if (last_inbuf)
511                         show_msg(last_inbuf);
512                 DEBUGLEVEL = oldlevel;
513                 DEBUG(0,("===============================================================\n"));
514 #if DUMP_CORE
515                 if (dump_core()) return;
516 #endif
517         }    
518
519         locking_end();
520
521         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
522         exit(0);
523 }
524
525 /****************************************************************************
526   initialise connect, service and file structs
527 ****************************************************************************/
528 static void init_structs(void )
529 {
530         /*
531          * Set the machine NETBIOS name if not already
532          * set from the config file.
533          */
534
535         if (!*global_myname) {
536                 char *p;
537                 fstrcpy( global_myname, myhostname() );
538                 p = strchr_m( global_myname, '.' );
539                 if (p) 
540                         *p = 0;
541         }
542
543         strupper( global_myname );
544
545         conn_init();
546
547         file_init();
548
549         /* for RPC pipes */
550         init_rpc_pipe_hnd();
551
552         init_dptrs();
553
554         secrets_init();
555 }
556
557 /****************************************************************************
558 usage on the program
559 ****************************************************************************/
560 static void usage(char *pname)
561 {
562
563         printf("Usage: %s [-DaoPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
564         printf("       [-O socket options] [-s services file]\n");
565         printf("\t-D                    Become a daemon\n");
566         printf("\t-a                    Append to log file (default)\n");
567         printf("\t-o                    Overwrite log file, don't append\n");
568         printf("\t-h                    Print usage\n");
569         printf("\t-?                    Print usage\n");
570         printf("\t-V                    Print version\n");
571         printf("\t-d debuglevel         Set the debuglevel\n");
572         printf("\t-l log basename.      Basename for log/debug files\n");
573         printf("\t-p port               Listen on the specified port\n");
574         printf("\t-O socket options     Socket options\n");
575         printf("\t-s services file.     Filename of services file\n");
576         printf("\n");
577 }
578
579
580 /****************************************************************************
581   main program
582 ****************************************************************************/
583  int main(int argc,char *argv[])
584 {
585         extern BOOL append_log;
586         /* shall I run as a daemon */
587         BOOL is_daemon = False;
588         BOOL specified_logfile = False;
589         int port = SMB_PORT;
590         int opt;
591         extern char *optarg;
592         
593 #ifdef HAVE_SET_AUTH_PARAMETERS
594         set_auth_parameters(argc,argv);
595 #endif
596
597         /* this is for people who can't start the program correctly */
598         while (argc > 1 && (*argv[1] != '-')) {
599                 argv++;
600                 argc--;
601         }
602
603         while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?Vaof:")) )
604                 switch (opt)  {
605                 case 'O':
606                         pstrcpy(user_socket_options,optarg);
607                         break;
608
609                 case 's':
610                         pstrcpy(servicesf,optarg);
611                         break;
612
613                 case 'l':
614                         specified_logfile = True;
615                         slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", optarg);
616                         break;
617
618                 case 'a':
619                         append_log = True;
620                         break;
621
622                 case 'o':
623                         append_log = False;
624                         break;
625
626                 case 'D':
627                         is_daemon = True;
628                         break;
629
630                 case 'd':
631                         if (*optarg == 'A')
632                                 DEBUGLEVEL = 10000;
633                         else
634                                 DEBUGLEVEL = atoi(optarg);
635                         break;
636
637                 case 'p':
638                         port = atoi(optarg);
639                         break;
640
641                 case 'h':
642                 case '?':
643                         usage(argv[0]);
644                         exit(0);
645                         break;
646
647                 case 'V':
648                         d_printf("Version %s\n",VERSION);
649                         exit(0);
650                         break;
651                 default:
652                         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
653                         usage(argv[0]);
654                         exit(1);
655                 }
656
657 #ifdef HAVE_SETLUID
658         /* needed for SecureWare on SCO */
659         setluid(0);
660 #endif
661
662         sec_init();
663
664         append_log = True;
665
666         TimeInit();
667
668         if(!specified_logfile) {
669                 slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", LOGFILEBASE);
670         }
671
672         pstrcpy(remote_machine, "smbd");
673
674         setup_logging(argv[0],False);
675
676         /* we want to re-seed early to prevent time delays causing
677            client problems at a later date. (tridge) */
678         generate_random_buffer(NULL, 0, False);
679
680         /* make absolutely sure we run as root - to handle cases where people
681            are crazy enough to have it setuid */
682
683         gain_root_privilege();
684         gain_root_group_privilege();
685
686         fault_setup((void (*)(void *))exit_server);
687         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
688
689         /* we are never interested in SIGPIPE */
690         BlockSignals(True,SIGPIPE);
691
692 #if defined(SIGFPE)
693         /* we are never interested in SIGFPE */
694         BlockSignals(True,SIGFPE);
695 #endif
696
697 #if defined(SIGUSR2)
698         /* We are no longer interested in USR2 */
699         BlockSignals(True,SIGUSR2);
700 #endif
701
702         /* POSIX demands that signals are inherited. If the invoking process has
703          * these signals masked, we will have problems, as we won't recieve them. */
704         BlockSignals(False, SIGHUP);
705         BlockSignals(False, SIGUSR1);
706
707         /* we want total control over the permissions on created files,
708            so set our umask to 0 */
709         umask(0);
710
711         init_sec_ctx();
712
713         reopen_logs();
714
715         DEBUG(1,( "smbd version %s started.\n", VERSION));
716         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
717
718         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
719                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
720
721         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
722                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
723                 exit(1);
724         }
725
726         /*
727          * Do this before reload_services.
728          */
729
730         if (!reload_services(False))
731                 return(-1);     
732
733         init_structs();
734
735         /* don't call winbind for our domain if we are the DC */
736         if (lp_domain_logons()) {
737                 winbind_exclude_domain(lp_workgroup());
738         }
739         
740 #ifdef WITH_PROFILE
741         if (!profile_setup(False)) {
742                 DEBUG(0,("ERROR: failed to setup profiling\n"));
743                 return -1;
744         }
745 #endif
746
747 #ifdef WITH_SSL
748         {
749                 extern BOOL sslEnabled;
750                 sslEnabled = lp_ssl_enabled();
751                 if(sslEnabled)
752                         sslutil_init(True);
753         }
754 #endif        /* WITH_SSL */
755
756         fstrcpy(global_myworkgroup, lp_workgroup());
757
758         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
759         
760         DEBUG(3,( "loaded services\n"));
761
762         if (!is_daemon && !is_a_socket(0)) {
763                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
764                 is_daemon = True;
765         }
766
767         if (is_daemon) {
768                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
769                 become_daemon();
770         }
771
772         if (!directory_exist(lp_lockdir(), NULL)) {
773                 mkdir(lp_lockdir(), 0755);
774         }
775
776         if (is_daemon) {
777                 pidfile_create("smbd");
778         }
779
780         if (!message_init()) {
781                 exit(1);
782         }
783
784         /* Setup the main smbd so that we can get messages. */
785         claim_connection(NULL,"",MAXSTATUS,True);
786
787         if (!open_sockets(is_daemon,port))
788                 exit(1);
789
790         /*
791          * everything after this point is run after the fork()
792          */ 
793
794         if (!locking_init(0)) {
795                 exit(1);
796         }
797
798         if (!print_backend_init()) {
799                 exit(1);
800         }
801
802         if (!share_info_db_init()) {
803                 exit(1);
804         }
805
806         if(!initialize_password_db(False)) {
807                 exit(1);
808         }
809
810         /* possibly reload the services file. */
811         reload_services(True);
812
813         if (init_group_mapping()==False) {
814                 printf("Could not open tdb mapping file.\n");
815                 return 0;
816         }
817
818         if(!pdb_generate_sam_sid()) {
819                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
820                 exit(1);
821         }
822
823         if (*lp_rootdir()) {
824                 if (sys_chroot(lp_rootdir()) == 0)
825                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
826         }
827
828         /* Setup oplocks */
829         if (!init_oplocks()) {
830                 exit(1);
831         }
832
833         /* Setup change notify */
834         if (!init_change_notify()) {
835                 exit(1);
836         }
837
838         smbd_process();
839         
840         exit_server("normal exit");
841         return(0);
842 }