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