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