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