Merge the become_XXX -> change_to_XXX fixes from 2.2.2 to HEAD.
[Samba/ekacnet.git] / source / smbd / server.c
blob2e0fb1868d444eea86a007b14c504988f3cc3a23
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 Main SMB server routines
5 Copyright (C) Andrew Tridgell 1992-1998
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.
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.
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.
22 #include "includes.h"
24 pstring servicesf = CONFIGFILE;
25 extern pstring debugf;
26 extern fstring global_myworkgroup;
27 extern pstring global_myname;
29 int am_parent = 1;
31 /* the last message the was processed */
32 int last_message = -1;
34 /* a useful macro to debug the last message processed */
35 #define LAST_MESSAGE() smb_fn_name(last_message)
37 extern pstring user_socket_options;
39 #ifdef WITH_DFS
40 extern int dcelogin_atmost_once;
41 #endif /* WITH_DFS */
43 extern fstring remote_machine;
45 /* really we should have a top level context structure that has the
46 client file descriptor as an element. That would require a major rewrite :(
48 the following 2 functions are an alternative - they make the file
49 descriptor private to smbd
51 static int server_fd = -1;
53 int smbd_server_fd(void)
55 return server_fd;
58 void smbd_set_server_fd(int fd)
60 server_fd = fd;
61 client_setfd(fd);
64 /****************************************************************************
65 when exiting, take the whole family
66 ****************************************************************************/
67 static void *dflt_sig(void)
69 exit_server("caught signal");
70 return NULL;
73 /****************************************************************************
74 Send a SIGTERM to our process group.
75 *****************************************************************************/
76 static void killkids(void)
78 if(am_parent) kill(0,SIGTERM);
81 /****************************************************************************
82 process a sam sync message - not sure whether to do this here or
83 somewhere else
84 ****************************************************************************/
85 static void msg_sam_sync(int msg_type, pid_t pid, void *buf, size_t len)
87 DEBUG(10, ("** sam sync message received, ignoring\n"));
90 /****************************************************************************
91 process a sam sync replicate message - not sure whether to do this here or
92 somewhere else
93 ****************************************************************************/
94 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
96 uint32 low_serial;
98 if (len != sizeof(uint32))
99 return;
101 low_serial = *((uint32 *)buf);
103 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
104 low_serial));
107 /****************************************************************************
108 open the socket communication
109 ****************************************************************************/
110 static BOOL open_sockets_inetd(void)
112 /* Started from inetd. fd 0 is the socket. */
113 /* We will abort gracefully when the client or remote system
114 goes away */
115 smbd_set_server_fd(dup(0));
117 /* close our standard file descriptors */
118 close_low_fds();
120 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
121 set_socket_options(smbd_server_fd(),user_socket_options);
123 return True;
127 /****************************************************************************
128 open the socket communication
129 ****************************************************************************/
130 static BOOL open_sockets(BOOL is_daemon,int port)
132 int num_interfaces = iface_count();
133 int fd_listenset[FD_SETSIZE];
134 fd_set listen_set;
135 int s;
136 int i;
138 if (!is_daemon) {
139 return open_sockets_inetd();
143 #ifdef HAVE_ATEXIT
145 static int atexit_set;
146 if(atexit_set == 0) {
147 atexit_set=1;
148 atexit(killkids);
151 #endif
153 /* Stop zombies */
154 CatchChild();
157 FD_ZERO(&listen_set);
159 if(lp_interfaces() && lp_bind_interfaces_only()) {
160 /* We have been given an interfaces line, and been
161 told to only bind to those interfaces. Create a
162 socket per interface and bind to only these.
165 if(num_interfaces > FD_SETSIZE) {
166 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
167 max can be %d\n",
168 num_interfaces, FD_SETSIZE));
169 return False;
172 /* Now open a listen socket for each of the
173 interfaces. */
174 for(i = 0; i < num_interfaces; i++) {
175 struct in_addr *ifip = iface_n_ip(i);
177 if(ifip == NULL) {
178 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
179 continue;
181 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
182 if(s == -1)
183 return False;
185 /* ready to listen */
186 set_socket_options(s,"SO_KEEPALIVE");
187 set_socket_options(s,user_socket_options);
189 if (listen(s, 5) == -1) {
190 DEBUG(0,("listen: %s\n",strerror(errno)));
191 close(s);
192 return False;
194 FD_SET(s,&listen_set);
196 } else {
197 /* Just bind to 0.0.0.0 - accept connections
198 from anywhere. */
199 num_interfaces = 1;
201 /* open an incoming socket */
202 s = open_socket_in(SOCK_STREAM, port, 0,
203 interpret_addr(lp_socket_address()),True);
204 if (s == -1)
205 return(False);
207 /* ready to listen */
208 set_socket_options(s,"SO_KEEPALIVE");
209 set_socket_options(s,user_socket_options);
211 if (listen(s, 5) == -1) {
212 DEBUG(0,("open_sockets: listen: %s\n",
213 strerror(errno)));
214 close(s);
215 return False;
218 fd_listenset[0] = s;
219 FD_SET(s,&listen_set);
222 /* Listen to messages */
224 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
225 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
227 /* now accept incoming connections - forking a new process
228 for each incoming connection */
229 DEBUG(2,("waiting for a connection\n"));
230 while (1) {
231 fd_set lfds;
232 int num;
234 /* Free up temporary memory from the main smbd. */
235 lp_talloc_free();
237 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
238 message_dispatch();
240 memcpy((char *)&lfds, (char *)&listen_set,
241 sizeof(listen_set));
243 num = sys_select(FD_SETSIZE,&lfds,NULL);
245 if (num == -1 && errno == EINTR) {
246 extern VOLATILE sig_atomic_t reload_after_sighup;
248 /* check for sighup processing */
249 if (reload_after_sighup) {
250 change_to_root_user();
251 DEBUG(1,("Reloading services after SIGHUP\n"));
252 reload_services(False);
253 reload_after_sighup = False;
256 continue;
259 /* check if we need to reload services */
260 check_reload(time(NULL));
262 /* Find the sockets that are read-ready -
263 accept on these. */
264 for( ; num > 0; num--) {
265 struct sockaddr addr;
266 socklen_t in_addrlen = sizeof(addr);
268 s = -1;
269 for(i = 0; i < num_interfaces; i++) {
270 if(FD_ISSET(fd_listenset[i],&lfds)) {
271 s = fd_listenset[i];
272 /* Clear this so we don't look
273 at it again. */
274 FD_CLR(fd_listenset[i],&lfds);
275 break;
279 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
281 if (smbd_server_fd() == -1 && errno == EINTR)
282 continue;
284 if (smbd_server_fd() == -1) {
285 DEBUG(0,("open_sockets: accept: %s\n",
286 strerror(errno)));
287 continue;
290 if (smbd_server_fd() != -1 && sys_fork()==0) {
291 /* Child code ... */
293 /* close the listening socket(s) */
294 for(i = 0; i < num_interfaces; i++)
295 close(fd_listenset[i]);
297 /* close our standard file
298 descriptors */
299 close_low_fds();
300 am_parent = 0;
302 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
303 set_socket_options(smbd_server_fd(),user_socket_options);
305 /* Reset global variables in util.c so
306 that client substitutions will be
307 done correctly in the process. */
308 reset_globals_after_fork();
310 /* tdb needs special fork handling */
311 tdb_reopen_all();
313 return True;
315 /* The parent doesn't need this socket */
316 close(smbd_server_fd());
318 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
319 Clear the closed fd info out of server_fd --
320 and more importantly, out of client_fd in
321 util_sock.c, to avoid a possible
322 getpeername failure if we reopen the logs
323 and use %I in the filename.
326 smbd_set_server_fd(-1);
328 /* Force parent to check log size after
329 * spawning child. Fix from
330 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
331 * parent smbd will log to logserver.smb. It
332 * writes only two messages for each child
333 * started/finished. But each child writes,
334 * say, 50 messages also in logserver.smb,
335 * begining with the debug_count of the
336 * parent, before the child opens its own log
337 * file logserver.client. In a worst case
338 * scenario the size of logserver.smb would be
339 * checked after about 50*50=2500 messages
340 * (ca. 100kb).
341 * */
342 force_check_log_size();
344 } /* end for num */
345 } /* end while 1 */
347 /* NOTREACHED return True; */
350 /****************************************************************************
351 reload the services file
352 **************************************************************************/
353 BOOL reload_services(BOOL test)
355 BOOL ret;
357 if (lp_loaded()) {
358 pstring fname;
359 pstrcpy(fname,lp_configfile());
360 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
361 pstrcpy(servicesf,fname);
362 test = False;
366 reopen_logs();
368 if (test && !lp_file_list_changed())
369 return(True);
371 lp_killunused(conn_snum_used);
373 ret = lp_load(servicesf,False,False,True);
375 load_printers();
377 /* perhaps the config filename is now set */
378 if (!test)
379 reload_services(True);
381 reopen_logs();
383 load_interfaces();
386 if (smbd_server_fd() != -1) {
387 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
388 set_socket_options(smbd_server_fd(),user_socket_options);
392 reset_mangled_cache();
393 reset_stat_cache();
395 /* this forces service parameters to be flushed */
396 set_current_service(NULL,True);
398 return(ret);
403 /****************************************************************************
404 Catch a sighup.
405 ****************************************************************************/
407 VOLATILE sig_atomic_t reload_after_sighup = False;
409 static void sig_hup(int sig)
411 BlockSignals(True,SIGHUP);
412 DEBUG(0,("Got SIGHUP\n"));
414 sys_select_signal();
415 reload_after_sighup = True;
416 BlockSignals(False,SIGHUP);
421 #if DUMP_CORE
422 /*******************************************************************
423 prepare to dump a core file - carefully!
424 ********************************************************************/
425 static BOOL dump_core(void)
427 char *p;
428 pstring dname;
429 pstrcpy(dname,debugf);
430 if ((p=strrchr_m(dname,'/'))) *p=0;
431 pstrcat(dname,"/corefiles");
432 mkdir(dname,0700);
433 sys_chown(dname,getuid(),getgid());
434 chmod(dname,0700);
435 if (chdir(dname)) return(False);
436 umask(~(0700));
438 #ifdef HAVE_GETRLIMIT
439 #ifdef RLIMIT_CORE
441 struct rlimit rlp;
442 getrlimit(RLIMIT_CORE, &rlp);
443 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
444 setrlimit(RLIMIT_CORE, &rlp);
445 getrlimit(RLIMIT_CORE, &rlp);
446 DEBUG(3,("Core limits now %d %d\n",
447 (int)rlp.rlim_cur,(int)rlp.rlim_max));
449 #endif
450 #endif
453 DEBUG(0,("Dumping core in %s\n",dname));
454 abort();
455 return(True);
457 #endif
459 /****************************************************************************
460 update the current smbd process count
461 ****************************************************************************/
463 static void decrement_smbd_process_count(void)
465 int total_smbds;
467 if (lp_max_smbd_processes()) {
468 total_smbds = 0;
469 tdb_change_int_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
473 /****************************************************************************
474 exit the server
475 ****************************************************************************/
476 void exit_server(char *reason)
478 static int firsttime=1;
479 extern char *last_inbuf;
482 if (!firsttime)
483 exit(0);
484 firsttime = 0;
486 change_to_root_user();
487 DEBUG(2,("Closing connections\n"));
489 conn_close_all();
491 invalidate_all_vuids();
493 /* delete our entry in the connections database. */
494 yield_connection(NULL,"",MAXSTATUS);
496 respond_to_all_remaining_local_messages();
497 decrement_smbd_process_count();
499 #ifdef WITH_DFS
500 if (dcelogin_atmost_once) {
501 dfs_unlogin();
503 #endif
505 if (!reason) {
506 int oldlevel = DEBUGLEVEL;
507 DEBUGLEVEL = 10;
508 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
509 if (last_inbuf)
510 show_msg(last_inbuf);
511 DEBUGLEVEL = oldlevel;
512 DEBUG(0,("===============================================================\n"));
513 #if DUMP_CORE
514 if (dump_core()) return;
515 #endif
518 locking_end();
520 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
521 exit(0);
524 /****************************************************************************
525 initialise connect, service and file structs
526 ****************************************************************************/
527 static void init_structs(void )
530 * Set the machine NETBIOS name if not already
531 * set from the config file.
534 if (!*global_myname) {
535 char *p;
536 fstrcpy( global_myname, myhostname() );
537 p = strchr_m( global_myname, '.' );
538 if (p)
539 *p = 0;
542 strupper( global_myname );
544 conn_init();
546 file_init();
548 /* for RPC pipes */
549 init_rpc_pipe_hnd();
551 init_dptrs();
553 secrets_init();
556 /****************************************************************************
557 usage on the program
558 ****************************************************************************/
559 static void usage(char *pname)
562 d_printf("Usage: %s [-DaoPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
563 d_printf(" [-O socket options] [-s services file]\n");
564 d_printf("\t-D Become a daemon\n");
565 d_printf("\t-a Append to log file (default)\n");
566 d_printf("\t-o Overwrite log file, don't append\n");
567 d_printf("\t-h Print usage\n");
568 d_printf("\t-? Print usage\n");
569 d_printf("\t-V Print version\n");
570 d_printf("\t-b Print build options\n");
571 d_printf("\t-d debuglevel Set the debuglevel\n");
572 d_printf("\t-l log basename. Basename for log/debug files\n");
573 d_printf("\t-p port Listen on the specified port\n");
574 d_printf("\t-O socket options Socket options\n");
575 d_printf("\t-s services file. Filename of services file\n");
576 d_printf("\n");
579 /****************************************************************************
580 main program
581 ****************************************************************************/
582 int main(int argc,char *argv[])
584 extern BOOL append_log;
585 /* shall I run as a daemon */
586 BOOL is_daemon = False;
587 BOOL specified_logfile = False;
588 int port = SMB_PORT;
589 int opt;
590 extern char *optarg;
592 #ifdef HAVE_SET_AUTH_PARAMETERS
593 set_auth_parameters(argc,argv);
594 #endif
596 /* this is for people who can't start the program correctly */
597 while (argc > 1 && (*argv[1] != '-')) {
598 argv++;
599 argc--;
602 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaof:")) )
603 switch (opt) {
604 case 'O':
605 pstrcpy(user_socket_options,optarg);
606 break;
608 case 's':
609 pstrcpy(servicesf,optarg);
610 break;
612 case 'l':
613 specified_logfile = True;
614 slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", optarg);
615 break;
617 case 'a':
618 append_log = True;
619 break;
621 case 'o':
622 append_log = False;
623 break;
625 case 'D':
626 is_daemon = True;
627 break;
629 case 'd':
630 if (*optarg == 'A')
631 DEBUGLEVEL = 10000;
632 else
633 DEBUGLEVEL = atoi(optarg);
634 break;
636 case 'p':
637 port = atoi(optarg);
638 break;
640 case 'h':
641 case '?':
642 usage(argv[0]);
643 exit(0);
644 break;
646 case 'V':
647 d_printf("Version %s\n",VERSION);
648 exit(0);
649 break;
650 case 'b':
651 build_options(True); /* Display output to screen as well as debug */
652 exit(0);
653 break;
654 default:
655 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
656 usage(argv[0]);
657 exit(1);
660 #ifdef HAVE_SETLUID
661 /* needed for SecureWare on SCO */
662 setluid(0);
663 #endif
665 sec_init();
667 load_case_tables();
669 append_log = True;
671 TimeInit();
673 if(!specified_logfile) {
674 slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", LOGFILEBASE);
677 pstrcpy(remote_machine, "smbd");
679 setup_logging(argv[0],False);
681 /* we want to re-seed early to prevent time delays causing
682 client problems at a later date. (tridge) */
683 generate_random_buffer(NULL, 0, False);
685 /* make absolutely sure we run as root - to handle cases where people
686 are crazy enough to have it setuid */
688 gain_root_privilege();
689 gain_root_group_privilege();
691 fault_setup((void (*)(void *))exit_server);
692 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
694 /* we are never interested in SIGPIPE */
695 BlockSignals(True,SIGPIPE);
697 #if defined(SIGFPE)
698 /* we are never interested in SIGFPE */
699 BlockSignals(True,SIGFPE);
700 #endif
702 #if defined(SIGUSR2)
703 /* We are no longer interested in USR2 */
704 BlockSignals(True,SIGUSR2);
705 #endif
707 /* POSIX demands that signals are inherited. If the invoking process has
708 * these signals masked, we will have problems, as we won't recieve them. */
709 BlockSignals(False, SIGHUP);
710 BlockSignals(False, SIGUSR1);
712 /* we want total control over the permissions on created files,
713 so set our umask to 0 */
714 umask(0);
716 init_sec_ctx();
718 reopen_logs();
720 DEBUG(1,( "smbd version %s started.\n", VERSION));
721 DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
723 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
724 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
726 /* Output the build options to the debug log */
727 build_options(False);
729 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
730 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
731 exit(1);
735 * Do this before reload_services.
738 if (!reload_services(False))
739 return(-1);
741 init_structs();
743 /* don't call winbind for our domain if we are the DC */
744 if (lp_domain_logons()) {
745 winbind_exclude_domain(lp_workgroup());
748 #ifdef WITH_PROFILE
749 if (!profile_setup(False)) {
750 DEBUG(0,("ERROR: failed to setup profiling\n"));
751 return -1;
753 #endif
755 #ifdef WITH_SSL
757 extern BOOL sslEnabled;
758 sslEnabled = lp_ssl_enabled();
759 if(sslEnabled)
760 sslutil_init(True);
762 #endif /* WITH_SSL */
764 fstrcpy(global_myworkgroup, lp_workgroup());
766 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
768 DEBUG(3,( "loaded services\n"));
770 if (!is_daemon && !is_a_socket(0)) {
771 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
772 is_daemon = True;
775 if (is_daemon) {
776 DEBUG( 3, ( "Becoming a daemon.\n" ) );
777 become_daemon();
780 if (!directory_exist(lp_lockdir(), NULL)) {
781 mkdir(lp_lockdir(), 0755);
784 if (is_daemon) {
785 pidfile_create("smbd");
788 if (!message_init()) {
789 exit(1);
792 /* Setup the main smbd so that we can get messages. */
793 claim_connection(NULL,"",MAXSTATUS,True);
796 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
797 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
798 smbd PROCESSES THAT NEVER DIE
799 start_background_queue();
802 if (!open_sockets(is_daemon,port))
803 exit(1);
806 * everything after this point is run after the fork()
809 if (!locking_init(0)) {
810 exit(1);
813 if (!print_backend_init()) {
814 exit(1);
817 if (!share_info_db_init()) {
818 exit(1);
821 if(!initialize_password_db(False)) {
822 exit(1);
825 /* possibly reload the services file. */
826 reload_services(True);
828 if (init_group_mapping()==False) {
829 printf("Could not open tdb mapping file.\n");
830 return 0;
833 if(!pdb_generate_sam_sid()) {
834 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
835 exit(1);
838 if (*lp_rootdir()) {
839 if (sys_chroot(lp_rootdir()) == 0)
840 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
843 /* Setup oplocks */
844 if (!init_oplocks()) {
845 exit(1);
848 /* Setup change notify */
849 if (!init_change_notify()) {
850 exit(1);
853 smbd_process();
855 exit_server("normal exit");
856 return(0);