rpc_parse/parse_misc.c : defined a new BUFFER5 struct
[ambi/samba-autobuild/.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         conn_init();
450         file_init();
451         init_rpc_pipe_hnd(); /* for RPC pipes */
452         init_lsa_policy_hnd(); /* for LSA handles */
453         init_printer_hnd(); /* for SPOOLSS handles */
454         init_dptrs();
455 }
456
457 /****************************************************************************
458 usage on the program
459 ****************************************************************************/
460 static void usage(char *pname)
461 {
462         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
463
464         printf("Usage: %s [-D] [-p port] [-d debuglevel] ", pname);
465         printf("[-l log basename] [-s services file]\n" );
466         printf("Version %s\n",VERSION);
467         printf("\t-D                    become a daemon\n");
468         printf("\t-p port               listen on the specified port\n");
469         printf("\t-d debuglevel         set the debuglevel\n");
470         printf("\t-l log basename.      Basename for log/debug files\n");
471         printf("\t-s services file.     Filename of services file\n");
472         printf("\t-P                    passive only\n");
473         printf("\t-a                    append to log file (default)\n");
474         printf("\t-o                    overwrite log file, don't append\n");
475         printf("\t-i scope              NetBIOS scope to use (default none)\n");
476         printf("\n");
477 }
478
479
480 /****************************************************************************
481   main program
482 ****************************************************************************/
483  int main(int argc,char *argv[])
484 {
485         extern BOOL append_log;
486         /* shall I run as a daemon */
487         BOOL is_daemon = False;
488         int port = SMB_PORT;
489         int opt;
490         extern char *optarg;
491         
492 #ifdef HAVE_SET_AUTH_PARAMETERS
493         set_auth_parameters(argc,argv);
494 #endif
495
496 #ifdef HAVE_SETLUID
497         /* needed for SecureWare on SCO */
498         setluid(0);
499 #endif
500
501         append_log = True;
502
503         TimeInit();
504
505         pstrcpy(debugf,SMBLOGFILE);  
506
507         pstrcpy(remote_machine, "smb");
508
509         setup_logging(argv[0],False);
510
511         charset_initialise();
512
513         /* make absolutely sure we run as root - to handle cases where people
514            are crazy enough to have it setuid */
515 #ifdef HAVE_SETRESUID
516         setresuid(0,0,0);
517 #else
518         setuid(0);
519         seteuid(0);
520         setuid(0);
521         seteuid(0);
522 #endif
523
524         fault_setup((void (*)(void *))exit_server);
525         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
526
527         /* we are never interested in SIGPIPE */
528         BlockSignals(True,SIGPIPE);
529
530         /* we want total control over the permissions on created files,
531            so set our umask to 0 */
532         umask(0);
533
534         dos_GetWd(OriginalDir);
535
536         init_uid();
537
538         /* this is for people who can't start the program correctly */
539         while (argc > 1 && (*argv[1] != '-')) {
540                 argv++;
541                 argc--;
542         }
543
544         while ( EOF != (opt = getopt(argc, argv, "O:i:l:s:d:Dp:h?Paof:")) )
545                 switch (opt)  {
546                 case 'O':
547                         pstrcpy(user_socket_options,optarg);
548                         break;
549
550                 case 'i':
551                         pstrcpy(scope,optarg);
552                         break;
553
554                 case 'P':
555                         {
556                                 extern BOOL passive;
557                                 passive = True;
558                         }
559                         break;  
560
561                 case 's':
562                         pstrcpy(servicesf,optarg);
563                         break;
564
565                 case 'l':
566                         pstrcpy(debugf,optarg);
567                         break;
568
569                 case 'a':
570                         append_log = True;
571                         break;
572
573                 case 'o':
574                         append_log = False;
575                         break;
576
577                 case 'D':
578                         is_daemon = True;
579                         break;
580
581                 case 'd':
582                         if (*optarg == 'A')
583                                 DEBUGLEVEL = 10000;
584                         else
585                                 DEBUGLEVEL = atoi(optarg);
586                         break;
587
588                 case 'p':
589                         port = atoi(optarg);
590                         break;
591
592                 case 'h':
593                 case '?':
594                         usage(argv[0]);
595                         exit(0);
596                         break;
597
598                 default:
599                         usage(argv[0]);
600                         exit(1);
601                 }
602
603         reopen_logs();
604
605         DEBUG(1,( "smbd version %s started.\n", VERSION));
606         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
607
608         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
609                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
610
611         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
612                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
613                 exit(1);
614         }
615
616         get_myname(myhostname,NULL);
617
618         if (!reload_services(False))
619                 return(-1);     
620
621         init_structs();
622
623 #ifdef WITH_PROFILE
624         if (!profile_setup(False)) {
625                 DEBUG(0,("ERROR: failed to setup profiling\n"));
626                 return -1;
627         }
628 #endif
629
630         /*
631          * Set the machine NETBIOS name if not already
632          * set from the config file.
633          */
634         if (!*global_myname)
635         {
636                 fstrcpy(global_myname, dns_to_netbios_name(myhostname));
637         }
638         strupper(global_myname);
639
640 #ifdef WITH_SSL
641         {
642                 extern BOOL sslEnabled;
643                 sslEnabled = lp_ssl_enabled();
644                 if(sslEnabled)
645                         sslutil_init(True);
646         }
647 #endif        /* WITH_SSL */
648
649         codepage_initialise(lp_client_code_page());
650
651         if (!pwdb_initialise(True))
652         {
653                 exit(1);
654         }
655
656         if(!initialise_sam_password_db())
657         {
658                 exit(1);
659         }
660
661         if(!initialise_passgrp_db())
662         {
663                 exit(1);
664         }
665
666         if(!initialise_group_db())
667         {
668                 exit(1);
669         }
670
671         if(!initialise_alias_db())
672         {
673                 exit(1);
674         }
675
676         if(!initialise_builtin_db())
677         {
678                 exit(1);
679         }
680
681         if (!get_member_domain_sid())
682         {
683                 DEBUG(0,("ERROR: Samba cannot obtain PDC SID from PDC(s) %s.\n",
684                           lp_passwordserver()));
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 (!open_sockets(is_daemon,port))
729                 exit(1);
730
731         if (!locking_init(0))
732                 exit(1);
733
734         /* possibly reload the services file. */
735         reload_services(True);
736         
737         if (*lp_rootdir()) {
738                 if (sys_chroot(lp_rootdir()) == 0)
739                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
740         }
741
742         /* Setup the oplock IPC socket. */
743         if( !open_oplock_ipc() )
744                 exit(1);
745
746         smbd_process();
747         close_sockets();
748         
749         exit_server("normal exit");
750         return(0);
751 }