2 Unix SMB/CIFS implementation.
3 Main SMB server routines
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Martin Pool 2002
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.
24 extern fstring global_myworkgroup;
25 extern pstring global_myname;
29 /* the last message the was processed */
30 int last_message = -1;
32 /* a useful macro to debug the last message processed */
33 #define LAST_MESSAGE() smb_fn_name(last_message)
35 extern pstring user_socket_options;
38 extern int dcelogin_atmost_once;
41 extern fstring remote_machine;
43 /* really we should have a top level context structure that has the
44 client file descriptor as an element. That would require a major rewrite :(
46 the following 2 functions are an alternative - they make the file
47 descriptor private to smbd
49 static int server_fd = -1;
51 int smbd_server_fd(void)
56 void smbd_set_server_fd(int fd)
62 /****************************************************************************
64 ****************************************************************************/
66 VOLATILE sig_atomic_t got_sig_term = 0;
68 static void sig_term(void)
74 /****************************************************************************
76 ****************************************************************************/
78 VOLATILE sig_atomic_t reload_after_sighup = 0;
80 static void sig_hup(int sig)
82 reload_after_sighup = 1;
86 /****************************************************************************
87 Send a SIGTERM to our process group.
88 *****************************************************************************/
90 static void killkids(void)
92 if(am_parent) kill(0,SIGTERM);
95 /****************************************************************************
96 Process a sam sync message - not sure whether to do this here or
98 ****************************************************************************/
100 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
101 void *UNUSED(buf), size_t UNUSED(len))
103 DEBUG(10, ("** sam sync message received, ignoring\n"));
106 /****************************************************************************
107 Process a sam sync replicate message - not sure whether to do this here or
109 ****************************************************************************/
111 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
115 if (len != sizeof(uint32))
118 low_serial = *((uint32 *)buf);
120 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
124 /****************************************************************************
125 Open the socket communication - inetd.
126 ****************************************************************************/
128 static BOOL open_sockets_inetd(void)
130 /* Started from inetd. fd 0 is the socket. */
131 /* We will abort gracefully when the client or remote system
133 smbd_set_server_fd(dup(0));
135 /* close our standard file descriptors */
138 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
139 set_socket_options(smbd_server_fd(), user_socket_options);
144 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
146 exit_server("Got a SHUTDOWN message");
150 /****************************************************************************
151 Open the socket communication.
152 ****************************************************************************/
154 static BOOL open_sockets(BOOL is_daemon,int port)
156 int num_interfaces = iface_count();
157 int fd_listenset[FD_SETSIZE];
163 return open_sockets_inetd();
169 static int atexit_set;
170 if(atexit_set == 0) {
181 FD_ZERO(&listen_set);
183 if(lp_interfaces() && lp_bind_interfaces_only()) {
184 /* We have been given an interfaces line, and been
185 told to only bind to those interfaces. Create a
186 socket per interface and bind to only these.
189 if(num_interfaces > FD_SETSIZE) {
190 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
192 num_interfaces, FD_SETSIZE));
196 /* Now open a listen socket for each of the
198 for(i = 0; i < num_interfaces; i++) {
199 struct in_addr *ifip = iface_n_ip(i);
202 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
205 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
209 /* ready to listen */
210 set_socket_options(s,"SO_KEEPALIVE");
211 set_socket_options(s,user_socket_options);
213 if (listen(s, 5) == -1) {
214 DEBUG(0,("listen: %s\n",strerror(errno)));
218 FD_SET(s,&listen_set);
221 /* Just bind to 0.0.0.0 - accept connections
225 /* open an incoming socket */
226 s = open_socket_in(SOCK_STREAM, port, 0,
227 interpret_addr(lp_socket_address()),True);
231 /* ready to listen */
232 set_socket_options(s,"SO_KEEPALIVE");
233 set_socket_options(s,user_socket_options);
235 if (listen(s, 5) == -1) {
236 DEBUG(0,("open_sockets: listen: %s\n",
243 FD_SET(s,&listen_set);
246 /* Listen to messages */
248 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
249 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
250 message_register(MSG_SHUTDOWN, msg_exit_server);
252 /* now accept incoming connections - forking a new process
253 for each incoming connection */
254 DEBUG(2,("waiting for a connection\n"));
259 /* Free up temporary memory from the main smbd. */
262 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
265 memcpy((char *)&lfds, (char *)&listen_set,
268 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
270 if (num == -1 && errno == EINTR) {
272 exit_server("Caught TERM signal");
275 /* check for sighup processing */
276 if (reload_after_sighup) {
277 change_to_root_user();
278 DEBUG(1,("Reloading services after SIGHUP\n"));
279 reload_services(False);
280 reload_after_sighup = 0;
286 /* check if we need to reload services */
287 check_reload(time(NULL));
289 /* Find the sockets that are read-ready -
291 for( ; num > 0; num--) {
292 struct sockaddr addr;
293 socklen_t in_addrlen = sizeof(addr);
296 for(i = 0; i < num_interfaces; i++) {
297 if(FD_ISSET(fd_listenset[i],&lfds)) {
299 /* Clear this so we don't look
301 FD_CLR(fd_listenset[i],&lfds);
306 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
308 if (smbd_server_fd() == -1 && errno == EINTR)
311 if (smbd_server_fd() == -1) {
312 DEBUG(0,("open_sockets: accept: %s\n",
317 if (smbd_server_fd() != -1 && sys_fork()==0) {
320 /* close the listening socket(s) */
321 for(i = 0; i < num_interfaces; i++)
322 close(fd_listenset[i]);
324 /* close our standard file
329 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
330 set_socket_options(smbd_server_fd(),user_socket_options);
332 /* Reset global variables in util.c so
333 that client substitutions will be
334 done correctly in the process. */
335 reset_globals_after_fork();
337 /* tdb needs special fork handling */
342 /* The parent doesn't need this socket */
343 close(smbd_server_fd());
345 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
346 Clear the closed fd info out of server_fd --
347 and more importantly, out of client_fd in
348 util_sock.c, to avoid a possible
349 getpeername failure if we reopen the logs
350 and use %I in the filename.
353 smbd_set_server_fd(-1);
355 /* Force parent to check log size after
356 * spawning child. Fix from
357 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
358 * parent smbd will log to logserver.smb. It
359 * writes only two messages for each child
360 * started/finished. But each child writes,
361 * say, 50 messages also in logserver.smb,
362 * begining with the debug_count of the
363 * parent, before the child opens its own log
364 * file logserver.client. In a worst case
365 * scenario the size of logserver.smb would be
366 * checked after about 50*50=2500 messages
369 force_check_log_size();
374 /* NOTREACHED return True; */
377 /****************************************************************************
378 Reload the services file.
379 **************************************************************************/
381 BOOL reload_services(BOOL test)
387 pstrcpy(fname,lp_configfile());
388 if (file_exist(fname, NULL) &&
389 !strcsequal(fname, dyn_CONFIGFILE)) {
390 pstrcpy(dyn_CONFIGFILE, fname);
397 if (test && !lp_file_list_changed())
400 lp_killunused(conn_snum_used);
402 ret = lp_load(dyn_CONFIGFILE, False, False, True);
406 /* perhaps the config filename is now set */
408 reload_services(True);
415 if (smbd_server_fd() != -1) {
416 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
417 set_socket_options(smbd_server_fd(), user_socket_options);
421 mangle_reset_cache();
424 /* this forces service parameters to be flushed */
425 set_current_service(NULL,True);
431 /*******************************************************************
432 prepare to dump a core file - carefully!
433 ********************************************************************/
434 static BOOL dump_core(void)
439 pstrcpy(dname,lp_logfile());
440 if ((p=strrchr_m(dname,'/'))) *p=0;
441 pstrcat(dname,"/corefiles");
443 sys_chown(dname,getuid(),getgid());
445 if (chdir(dname)) return(False);
448 #ifdef HAVE_GETRLIMIT
452 getrlimit(RLIMIT_CORE, &rlp);
453 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
454 setrlimit(RLIMIT_CORE, &rlp);
455 getrlimit(RLIMIT_CORE, &rlp);
456 DEBUG(3,("Core limits now %d %d\n",
457 (int)rlp.rlim_cur,(int)rlp.rlim_max));
463 DEBUG(0,("Dumping core in %s\n", dname));
469 /****************************************************************************
470 update the current smbd process count
471 ****************************************************************************/
473 static void decrement_smbd_process_count(void)
477 if (lp_max_smbd_processes()) {
479 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
483 /****************************************************************************
485 ****************************************************************************/
487 void exit_server(char *reason)
489 static int firsttime=1;
490 extern char *last_inbuf;
491 extern struct auth_context *negprot_global_auth_context;
497 change_to_root_user();
498 DEBUG(2,("Closing connections\n"));
500 if (negprot_global_auth_context) {
501 (negprot_global_auth_context->free)(&negprot_global_auth_context);
506 invalidate_all_vuids();
508 /* delete our entry in the connections database. */
509 yield_connection(NULL,"");
511 respond_to_all_remaining_local_messages();
512 decrement_smbd_process_count();
515 if (dcelogin_atmost_once) {
521 int oldlevel = DEBUGLEVEL;
523 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
525 show_msg(last_inbuf);
526 DEBUGLEVEL = oldlevel;
527 DEBUG(0,("===============================================================\n"));
529 if (dump_core()) return;
535 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
539 /****************************************************************************
540 Initialise connect, service and file structs.
541 ****************************************************************************/
543 static void init_structs(void )
546 * Set the machine NETBIOS name if not already
547 * set from the config file.
550 if (!*global_myname) {
552 pstrcpy( global_myname, myhostname() );
553 p = strchr_m(global_myname, '.' );
558 strupper(global_myname);
573 /****************************************************************************
574 Usage on the program.
575 ****************************************************************************/
577 static void usage(char *pname)
580 d_printf("Usage: %s [-DaioPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
581 d_printf(" [-O socket options] [-s services file]\n");
582 d_printf("\t-D Become a daemon (default)\n");
583 d_printf("\t-a Append to log file (default)\n");
584 d_printf("\t-i Run interactive (not a daemon)\n" );
585 d_printf("\t-o Overwrite log file, don't append\n");
586 d_printf("\t-h Print usage\n");
587 d_printf("\t-? Print usage\n");
588 d_printf("\t-V Print version\n");
589 d_printf("\t-b Print build options\n");
590 d_printf("\t-d debuglevel Set the debuglevel\n");
591 d_printf("\t-l log basename. Basename for log/debug files\n");
592 d_printf("\t-p port Listen on the specified port\n");
593 d_printf("\t-O socket options Socket options\n");
594 d_printf("\t-s services file. Filename of services file\n");
598 /****************************************************************************
600 ****************************************************************************/
602 int main(int argc,char *argv[])
604 extern BOOL append_log;
605 extern BOOL AllowDebugChange;
607 /* shall I run as a daemon */
608 BOOL is_daemon = False;
609 BOOL interactive = False;
610 BOOL specified_logfile = False;
615 #ifdef HAVE_SET_AUTH_PARAMETERS
616 set_auth_parameters(argc,argv);
619 /* this is for people who can't start the program correctly */
620 while (argc > 1 && (*argv[1] != '-')) {
625 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaiof:")) )
628 pstrcpy(user_socket_options,optarg);
632 pstrcpy(dyn_CONFIGFILE,optarg);
636 specified_logfile = True;
637 pstr_sprintf(logfile, "%s/log.smbd", optarg);
638 lp_set_logfile(logfile);
661 DEBUGLEVEL = atoi(optarg);
662 AllowDebugChange = False;
676 d_printf("Version %s\n",VERSION);
680 build_options(True); /* Display output to screen as well as debug */
684 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
690 /* needed for SecureWare on SCO */
700 if(!specified_logfile) {
701 pstr_sprintf(logfile, "%s/log.smbd", dyn_LOGFILEBASE);
702 lp_set_logfile(logfile);
705 fstrcpy(remote_machine, "smbd");
707 setup_logging(argv[0],interactive);
709 /* we want to re-seed early to prevent time delays causing
710 client problems at a later date. (tridge) */
711 generate_random_buffer(NULL, 0, False);
713 /* make absolutely sure we run as root - to handle cases where people
714 are crazy enough to have it setuid */
716 gain_root_privilege();
717 gain_root_group_privilege();
719 fault_setup((void (*)(void *))exit_server);
720 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
721 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
723 /* we are never interested in SIGPIPE */
724 BlockSignals(True,SIGPIPE);
727 /* we are never interested in SIGFPE */
728 BlockSignals(True,SIGFPE);
732 /* We are no longer interested in USR2 */
733 BlockSignals(True,SIGUSR2);
736 /* POSIX demands that signals are inherited. If the invoking process has
737 * these signals masked, we will have problems, as we won't recieve them. */
738 BlockSignals(False, SIGHUP);
739 BlockSignals(False, SIGUSR1);
740 BlockSignals(False, SIGTERM);
742 /* we want total control over the permissions on created files,
743 so set our umask to 0 */
750 DEBUG(0,( "smbd version %s started.\n", VERSION));
751 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
753 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
754 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
756 /* Output the build options to the debug log */
757 build_options(False);
759 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
760 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
765 * Do this before reload_services.
768 if (!reload_services(False))
773 /* don't call winbind for our domain if we are the DC */
774 if (lp_domain_logons()) {
775 winbind_exclude_domain(lp_workgroup());
779 if (!profile_setup(False)) {
780 DEBUG(0,("ERROR: failed to setup profiling\n"));
787 extern BOOL sslEnabled;
788 sslEnabled = lp_ssl_enabled();
792 #endif /* WITH_SSL */
794 fstrcpy(global_myworkgroup, lp_workgroup());
796 DEBUG(3,( "loaded services\n"));
798 if (!is_daemon && !is_a_socket(0)) {
800 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
803 * Setting is_daemon here prevents us from eventually calling
804 * the open_sockets_inetd()
810 if (is_daemon && !interactive) {
811 DEBUG( 3, ( "Becoming a daemon.\n" ) );
817 * If we're interactive we want to set our own process group for
821 setpgid( (pid_t)0, (pid_t)0);
824 if (!directory_exist(lp_lockdir(), NULL)) {
825 mkdir(lp_lockdir(), 0755);
829 pidfile_create("smbd");
832 if (!message_init()) {
835 register_msg_pool_usage();
836 register_dmalloc_msgs();
838 /* Setup the main smbd so that we can get messages. */
839 claim_connection(NULL,"",0,True);
842 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
843 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
844 smbd PROCESSES THAT NEVER DIE
845 start_background_queue();
848 if (!open_sockets(is_daemon,port))
852 * everything after this point is run after the fork()
855 if (!locking_init(0))
858 if (!print_backend_init())
861 if (!share_info_db_init())
864 if(!initialize_password_db(False))
867 uni_group_cache_init(); /* Non-critical */
869 /* possibly reload the services file. */
870 reload_services(True);
872 if(!pdb_generate_sam_sid()) {
873 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
877 if (!init_account_policy()) {
878 DEBUG(0,("Could not open account policy tdb.\n"));
883 if (sys_chroot(lp_rootdir()) == 0)
884 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
891 /* Setup change notify */
892 if (!init_change_notify())
897 uni_group_cache_shutdown();
898 exit_server("normal exit");