Merge of new 2.2 code into HEAD (Gerald I hate you :-) :-). Allows new SAMR
[nivanova/samba-autobuild/.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                         /* Force parent to check log size after
281                          * spawning child.  Fix from
282                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
283                          * parent smbd will log to logserver.smb.  It
284                          * writes only two messages for each child
285                          * started/finished. But each child writes,
286                          * say, 50 messages also in logserver.smb,
287                          * begining with the debug_count of the
288                          * parent, before the child opens its own log
289                          * file logserver.client. In a worst case
290                          * scenario the size of logserver.smb would be
291                          * checked after about 50*50=2500 messages
292                          * (ca. 100kb).
293                          * */
294                         force_check_log_size();
295  
296                 } /* end for num */
297         } /* end while 1 */
298
299 /* NOTREACHED   return True; */
300 }
301
302 /****************************************************************************
303   reload the services file
304   **************************************************************************/
305 BOOL reload_services(BOOL test)
306 {
307         BOOL ret;
308         
309         if (lp_loaded()) {
310                 pstring fname;
311                 pstrcpy(fname,lp_configfile());
312                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
313                         pstrcpy(servicesf,fname);
314                         test = False;
315                 }
316         }
317
318         reopen_logs();
319
320         if (test && !lp_file_list_changed())
321                 return(True);
322
323         lp_killunused(conn_snum_used);
324         
325         ret = lp_load(servicesf,False,False,True);
326
327         load_printers();
328
329         /* perhaps the config filename is now set */
330         if (!test)
331                 reload_services(True);
332
333         reopen_logs();
334
335         load_interfaces();
336
337         {
338                 if (smbd_server_fd() != -1) {      
339                         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
340                         set_socket_options(smbd_server_fd(),user_socket_options);
341                 }
342         }
343
344         reset_mangled_cache();
345         reset_stat_cache();
346
347         /* this forces service parameters to be flushed */
348         become_service(NULL,True);
349
350         return(ret);
351 }
352
353
354
355 /****************************************************************************
356  Catch a sighup.
357 ****************************************************************************/
358
359 VOLATILE SIG_ATOMIC_T reload_after_sighup = False;
360
361 static void sig_hup(int sig)
362 {
363         BlockSignals(True,SIGHUP);
364         DEBUG(0,("Got SIGHUP\n"));
365
366         sys_select_signal();
367         reload_after_sighup = True;
368         BlockSignals(False,SIGHUP);
369 }
370
371
372
373 #if DUMP_CORE
374 /*******************************************************************
375 prepare to dump a core file - carefully!
376 ********************************************************************/
377 static BOOL dump_core(void)
378 {
379         char *p;
380         pstring dname;
381         pstrcpy(dname,debugf);
382         if ((p=strrchr(dname,'/'))) *p=0;
383         pstrcat(dname,"/corefiles");
384         mkdir(dname,0700);
385         sys_chown(dname,getuid(),getgid());
386         chmod(dname,0700);
387         if (chdir(dname)) return(False);
388         umask(~(0700));
389
390 #ifdef HAVE_GETRLIMIT
391 #ifdef RLIMIT_CORE
392         {
393                 struct rlimit rlp;
394                 getrlimit(RLIMIT_CORE, &rlp);
395                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
396                 setrlimit(RLIMIT_CORE, &rlp);
397                 getrlimit(RLIMIT_CORE, &rlp);
398                 DEBUG(3,("Core limits now %d %d\n",
399                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
400         }
401 #endif
402 #endif
403
404
405         DEBUG(0,("Dumping core in %s\n",dname));
406         abort();
407         return(True);
408 }
409 #endif
410
411 /****************************************************************************
412 update the current smbd process count
413 ****************************************************************************/
414 static void decrement_smbd_process_count(void)
415 {
416         int total_smbds;
417
418         if (lp_max_smbd_processes()) {
419                 tdb_lock_bystring(conn_tdb_ctx(), "INFO/total_smbds");
420                 if ((total_smbds = tdb_fetch_int(conn_tdb_ctx(), "INFO/total_smbds")) > 0)
421                         tdb_store_int(conn_tdb_ctx(), "INFO/total_smbds", total_smbds - 1);
422                 
423                 tdb_unlock_bystring(conn_tdb_ctx(), "INFO/total_smbds");
424         }
425 }
426
427 /****************************************************************************
428 exit the server
429 ****************************************************************************/
430 void exit_server(char *reason)
431 {
432         static int firsttime=1;
433         extern char *last_inbuf;
434
435
436         if (!firsttime) exit(0);
437         firsttime = 0;
438
439         unbecome_user();
440         DEBUG(2,("Closing connections\n"));
441
442         conn_close_all();
443
444         /* delete our entry in the connections database. */
445         if (lp_status(-1)) {
446                 yield_connection(NULL,"",MAXSTATUS);
447         }
448
449     respond_to_all_remaining_local_messages();
450         decrement_smbd_process_count();
451
452 #ifdef WITH_DFS
453         if (dcelogin_atmost_once) {
454                 dfs_unlogin();
455         }
456 #endif
457
458         if (!reason) {   
459                 int oldlevel = DEBUGLEVEL;
460                 DEBUGLEVEL = 10;
461                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
462                 if (last_inbuf)
463                         show_msg(last_inbuf);
464                 DEBUGLEVEL = oldlevel;
465                 DEBUG(0,("===============================================================\n"));
466 #if DUMP_CORE
467                 if (dump_core()) return;
468 #endif
469         }    
470
471         locking_end();
472
473         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
474         exit(0);
475 }
476
477 /****************************************************************************
478   initialise connect, service and file structs
479 ****************************************************************************/
480 static void init_structs(void )
481 {
482         /*
483          * Set the machine NETBIOS name if not already
484          * set from the config file.
485          */
486
487         if (!*global_myname) {
488                 char *p;
489                 fstrcpy( global_myname, myhostname() );
490                 p = strchr( global_myname, '.' );
491                 if (p) 
492                         *p = 0;
493         }
494
495         strupper( global_myname );
496
497         conn_init();
498
499         file_init();
500
501         /* for RPC pipes */
502         init_rpc_pipe_hnd();
503
504         init_dptrs();
505
506         secrets_init();
507 }
508
509 /****************************************************************************
510 usage on the program
511 ****************************************************************************/
512 static void usage(char *pname)
513 {
514
515         printf("Usage: %s [-DaoPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
516         printf("       [-O socket options] [-s services file]\n");
517         printf("\t-D                    Become a daemon\n");
518         printf("\t-a                    Append to log file (default)\n");
519         printf("\t-o                    Overwrite log file, don't append\n");
520         printf("\t-h                    Print usage\n");
521         printf("\t-?                    Print usage\n");
522         printf("\t-V                    Print version\n");
523         printf("\t-d debuglevel         Set the debuglevel\n");
524         printf("\t-l log basename.      Basename for log/debug files\n");
525         printf("\t-p port               Listen on the specified port\n");
526         printf("\t-O socket options     Socket options\n");
527         printf("\t-s services file.     Filename of services file\n");
528         printf("\n");
529 }
530
531
532 /****************************************************************************
533   main program
534 ****************************************************************************/
535  int main(int argc,char *argv[])
536 {
537         extern BOOL append_log;
538         /* shall I run as a daemon */
539         BOOL is_daemon = False;
540         BOOL specified_logfile = False;
541         int port = SMB_PORT;
542         int opt;
543         extern char *optarg;
544         
545 #ifdef HAVE_SET_AUTH_PARAMETERS
546         set_auth_parameters(argc,argv);
547 #endif
548
549         /* this is for people who can't start the program correctly */
550         while (argc > 1 && (*argv[1] != '-')) {
551                 argv++;
552                 argc--;
553         }
554
555         while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?Vaof:")) )
556                 switch (opt)  {
557                 case 'O':
558                         pstrcpy(user_socket_options,optarg);
559                         break;
560
561                 case 's':
562                         pstrcpy(servicesf,optarg);
563                         break;
564
565                 case 'l':
566                         specified_logfile = True;
567                         pstrcpy(debugf,optarg);
568                         break;
569
570                 case 'a':
571                         append_log = True;
572                         break;
573
574                 case 'o':
575                         append_log = False;
576                         break;
577
578                 case 'D':
579                         is_daemon = True;
580                         break;
581
582                 case 'd':
583                         if (*optarg == 'A')
584                                 DEBUGLEVEL = 10000;
585                         else
586                                 DEBUGLEVEL = atoi(optarg);
587                         break;
588
589                 case 'p':
590                         port = atoi(optarg);
591                         break;
592
593                 case 'h':
594                 case '?':
595                         usage(argv[0]);
596                         exit(0);
597                         break;
598
599                 case 'V':
600                         printf("Version %s\n",VERSION);
601                         exit(0);
602                         break;
603                 default:
604                         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
605                         usage(argv[0]);
606                         exit(1);
607                 }
608
609 #ifdef HAVE_SETLUID
610         /* needed for SecureWare on SCO */
611         setluid(0);
612 #endif
613
614         /*
615          * gain_root_privilege uses an assert than will cause a core
616          * dump if euid != 0. Ensure this is the case.
617          */
618
619         if(geteuid() != (uid_t)0) {
620                 fprintf(stderr, "%s: Version %s : Must have effective user id of zero to run.\n", argv[0], VERSION);
621                 exit(1);
622         }
623
624         append_log = True;
625
626         TimeInit();
627
628         if(!specified_logfile) {
629                 slprintf(debugf, sizeof(debugf), "%s/log.smbd", LOGFILEBASE);
630         }
631
632         pstrcpy(remote_machine, "smbd");
633
634         setup_logging(argv[0],False);
635
636         charset_initialise();
637
638         /* we want to re-seed early to prevent time delays causing
639            client problems at a later date. (tridge) */
640         generate_random_buffer(NULL, 0, False);
641
642         /* make absolutely sure we run as root - to handle cases where people
643            are crazy enough to have it setuid */
644
645         gain_root_privilege();
646         gain_root_group_privilege();
647
648         fault_setup((void (*)(void *))exit_server);
649         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
650
651         /* we are never interested in SIGPIPE */
652         BlockSignals(True,SIGPIPE);
653
654 #if defined(SIGFPE)
655         /* we are never interested in SIGFPE */
656         BlockSignals(True,SIGFPE);
657 #endif
658
659 #if defined(SIGUSR2)
660         /* We are no longer interested in USR2 */
661         BlockSignals(True,SIGUSR2);
662 #endif
663
664         /* POSIX demands that signals are inherited. If the invoking process has
665          * these signals masked, we will have problems, as we won't recieve them. */
666         BlockSignals(False, SIGHUP);
667         BlockSignals(False, SIGUSR1);
668
669         /* we want total control over the permissions on created files,
670            so set our umask to 0 */
671         umask(0);
672
673         init_sec_ctx();
674
675         reopen_logs();
676
677         DEBUG(1,( "smbd version %s started.\n", VERSION));
678         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
679
680         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
681                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
682
683         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
684                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
685                 exit(1);
686         }
687
688         /*
689          * Do this before reload_services.
690          */
691
692         if (!reload_services(False))
693                 return(-1);     
694
695         init_structs();
696         
697 #ifdef WITH_PROFILE
698         if (!profile_setup(False)) {
699                 DEBUG(0,("ERROR: failed to setup profiling\n"));
700                 return -1;
701         }
702 #endif
703
704 #ifdef WITH_SSL
705         {
706                 extern BOOL sslEnabled;
707                 sslEnabled = lp_ssl_enabled();
708                 if(sslEnabled)
709                         sslutil_init(True);
710         }
711 #endif        /* WITH_SSL */
712
713         codepage_initialise(lp_client_code_page());
714
715         fstrcpy(global_myworkgroup, lp_workgroup());
716
717         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
718         
719         DEBUG(3,( "loaded services\n"));
720
721         if (!is_daemon && !is_a_socket(0)) {
722                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
723                 is_daemon = True;
724         }
725
726         if (is_daemon) {
727                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
728                 become_daemon();
729         }
730
731         if (!directory_exist(lp_lockdir(), NULL)) {
732                 mkdir(lp_lockdir(), 0755);
733         }
734
735         if (is_daemon) {
736                 pidfile_create("smbd");
737         }
738
739         if (!message_init()) {
740                 exit(1);
741         }
742
743         /* Setup the main smbd so that we can get messages. */
744         if (lp_status(-1)) {
745                 claim_connection(NULL,"",MAXSTATUS,True);
746         }
747
748         /* Attempt to migrate from an old 2.0.x machine account file. */
749         if (!migrate_from_old_password_file(global_myworkgroup)) {
750                 DEBUG(0,("Failed to migrate from old MAC file.\n"));
751         }
752
753         if (!open_sockets(is_daemon,port))
754                 exit(1);
755
756         /*
757          * everything after this point is run after the fork()
758          */ 
759
760         if (!locking_init(0)) {
761                 exit(1);
762         }
763
764         if (!print_backend_init()) {
765                 exit(1);
766         }
767
768         if(!initialize_password_db(False)) {
769                 exit(1);
770         }
771
772         /* possibly reload the services file. */
773         reload_services(True);
774
775         if(!pdb_generate_sam_sid()) {
776                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
777                 exit(1);
778         }
779
780         if (*lp_rootdir()) {
781                 if (sys_chroot(lp_rootdir()) == 0)
782                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
783         }
784
785         /* Setup oplocks */
786         if (!init_oplocks()) {
787                 exit(1);
788         }
789
790         /* Setup change notify */
791         if (!init_change_notify()) {
792                 exit(1);
793         }
794
795         smbd_process();
796         
797         exit_server("normal exit");
798         return(0);
799 }