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