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