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