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