2 Unix SMB/CIFS implementation.
3 Main SMB server routines
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Martin Pool 2002
6 Copyright (C) Jelmer Vernooij 2002-2003
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 static int am_parent = 1;
27 /* the last message the was processed */
28 int last_message = -1;
30 /* a useful macro to debug the last message processed */
31 #define LAST_MESSAGE() smb_fn_name(last_message)
33 extern pstring user_socket_options;
34 extern SIG_ATOMIC_T got_sig_term;
35 extern SIG_ATOMIC_T reload_after_sighup;
38 extern int dcelogin_atmost_once;
41 /* really we should have a top level context structure that has the
42 client file descriptor as an element. That would require a major rewrite :(
44 the following 2 functions are an alternative - they make the file
45 descriptor private to smbd
47 static int server_fd = -1;
49 int smbd_server_fd(void)
54 static void smbd_set_server_fd(int fd)
60 /****************************************************************************
62 ****************************************************************************/
64 static void sig_term(void)
70 /****************************************************************************
72 ****************************************************************************/
74 static void sig_hup(int sig)
76 reload_after_sighup = 1;
80 /****************************************************************************
81 Send a SIGTERM to our process group.
82 *****************************************************************************/
84 static void killkids(void)
86 if(am_parent) kill(0,SIGTERM);
89 /****************************************************************************
90 Process a sam sync message - not sure whether to do this here or
92 ****************************************************************************/
94 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
95 void *UNUSED(buf), size_t UNUSED(len))
97 DEBUG(10, ("** sam sync message received, ignoring\n"));
100 /****************************************************************************
101 Process a sam sync replicate message - not sure whether to do this here or
103 ****************************************************************************/
105 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
109 if (len != sizeof(uint32))
112 low_serial = *((uint32 *)buf);
114 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
118 /****************************************************************************
119 Open the socket communication - inetd.
120 ****************************************************************************/
122 static BOOL open_sockets_inetd(void)
124 /* Started from inetd. fd 0 is the socket. */
125 /* We will abort gracefully when the client or remote system
127 smbd_set_server_fd(dup(0));
129 /* close our standard file descriptors */
130 close_low_fds(False); /* Don't close stderr */
132 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
133 set_socket_options(smbd_server_fd(), user_socket_options);
138 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
140 exit_server("Got a SHUTDOWN message");
144 /****************************************************************************
145 Have we reached the process limit ?
146 ****************************************************************************/
148 static BOOL allowable_number_of_smbd_processes(void)
150 int max_processes = lp_max_smbd_processes();
156 TDB_CONTEXT *tdb = conn_tdb_ctx();
159 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
163 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
164 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
165 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
166 tdb_errorstr(tdb) ));
169 if (val > max_processes) {
170 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
171 val, max_processes ));
178 /****************************************************************************
179 Open the socket communication.
180 ****************************************************************************/
182 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
184 int num_interfaces = iface_count();
186 int fd_listenset[FD_SETSIZE];
193 return open_sockets_inetd();
199 static int atexit_set;
200 if(atexit_set == 0) {
210 FD_ZERO(&listen_set);
212 /* use a reasonable default set of ports - listing on 445 and 139 */
214 ports = lp_smb_ports();
215 if (!ports || !*ports) {
216 ports = smb_xstrdup(SMB_PORTS);
218 ports = smb_xstrdup(ports);
221 ports = smb_xstrdup(smb_ports);
224 if (lp_interfaces() && lp_bind_interfaces_only()) {
225 /* We have been given an interfaces line, and been
226 told to only bind to those interfaces. Create a
227 socket per interface and bind to only these.
230 /* Now open a listen socket for each of the
232 for(i = 0; i < num_interfaces; i++) {
233 struct in_addr *ifip = iface_n_ip(i);
238 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
242 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
243 unsigned port = atoi(tok);
244 if (port == 0) continue;
245 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
249 /* ready to listen */
250 set_socket_options(s,"SO_KEEPALIVE");
251 set_socket_options(s,user_socket_options);
253 /* Set server socket to non-blocking for the accept. */
254 set_blocking(s,False);
256 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
257 DEBUG(0,("listen: %s\n",strerror(errno)));
261 FD_SET(s,&listen_set);
264 if (num_sockets >= FD_SETSIZE) {
265 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
271 /* Just bind to 0.0.0.0 - accept connections
279 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
280 unsigned port = atoi(tok);
281 if (port == 0) continue;
282 /* open an incoming socket */
283 s = open_socket_in(SOCK_STREAM, port, 0,
284 interpret_addr(lp_socket_address()),True);
288 /* ready to listen */
289 set_socket_options(s,"SO_KEEPALIVE");
290 set_socket_options(s,user_socket_options);
292 /* Set server socket to non-blocking for the accept. */
293 set_blocking(s,False);
295 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
296 DEBUG(0,("open_sockets_smbd: listen: %s\n",
302 fd_listenset[num_sockets] = s;
303 FD_SET(s,&listen_set);
307 if (num_sockets >= FD_SETSIZE) {
308 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
316 /* Listen to messages */
318 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
319 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
320 message_register(MSG_SHUTDOWN, msg_exit_server);
322 /* now accept incoming connections - forking a new process
323 for each incoming connection */
324 DEBUG(2,("waiting for a connection\n"));
329 /* Free up temporary memory from the main smbd. */
332 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
335 memcpy((char *)&lfds, (char *)&listen_set,
338 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
340 if (num == -1 && errno == EINTR) {
342 exit_server("Caught TERM signal");
345 /* check for sighup processing */
346 if (reload_after_sighup) {
347 change_to_root_user();
348 DEBUG(1,("Reloading services after SIGHUP\n"));
349 reload_services(False);
350 reload_after_sighup = 0;
356 /* check if we need to reload services */
357 check_reload(time(NULL));
359 /* Find the sockets that are read-ready -
361 for( ; num > 0; num--) {
362 struct sockaddr addr;
363 socklen_t in_addrlen = sizeof(addr);
366 for(i = 0; i < num_sockets; i++) {
367 if(FD_ISSET(fd_listenset[i],&lfds)) {
369 /* Clear this so we don't look
371 FD_CLR(fd_listenset[i],&lfds);
376 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
378 if (smbd_server_fd() == -1 && errno == EINTR)
381 if (smbd_server_fd() == -1) {
382 DEBUG(0,("open_sockets_smbd: accept: %s\n",
387 /* Ensure child is set to blocking mode */
388 set_blocking(smbd_server_fd(),True);
390 if (smbd_server_fd() != -1 && interactive)
393 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
396 /* close the listening socket(s) */
397 for(i = 0; i < num_sockets; i++)
398 close(fd_listenset[i]);
400 /* close our standard file
402 close_low_fds(False);
405 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
406 set_socket_options(smbd_server_fd(),user_socket_options);
408 /* this is needed so that we get decent entries
409 in smbstatus for port 445 connects */
410 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
412 /* Reset the state of the random
413 * number generation system, so
414 * children do not get the same random
415 * numbers as each other */
417 set_need_random_reseed();
418 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
419 if (tdb_reopen_all() == -1) {
420 DEBUG(0,("tdb_reopen_all failed.\n"));
421 smb_panic("tdb_reopen_all failed.");
426 /* The parent doesn't need this socket */
427 close(smbd_server_fd());
429 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
430 Clear the closed fd info out of server_fd --
431 and more importantly, out of client_fd in
432 util_sock.c, to avoid a possible
433 getpeername failure if we reopen the logs
434 and use %I in the filename.
437 smbd_set_server_fd(-1);
439 /* Force parent to check log size after
440 * spawning child. Fix from
441 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
442 * parent smbd will log to logserver.smb. It
443 * writes only two messages for each child
444 * started/finished. But each child writes,
445 * say, 50 messages also in logserver.smb,
446 * begining with the debug_count of the
447 * parent, before the child opens its own log
448 * file logserver.client. In a worst case
449 * scenario the size of logserver.smb would be
450 * checked after about 50*50=2500 messages
453 force_check_log_size();
458 /* NOTREACHED return True; */
461 /****************************************************************************
462 Reload the services file.
463 **************************************************************************/
465 BOOL reload_services(BOOL test)
471 pstrcpy(fname,lp_configfile());
472 if (file_exist(fname, NULL) &&
473 !strcsequal(fname, dyn_CONFIGFILE)) {
474 pstrcpy(dyn_CONFIGFILE, fname);
481 if (test && !lp_file_list_changed())
484 lp_killunused(conn_snum_used);
486 ret = lp_load(dyn_CONFIGFILE, False, False, True);
490 /* perhaps the config filename is now set */
492 reload_services(True);
498 if (smbd_server_fd() != -1) {
499 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
500 set_socket_options(smbd_server_fd(), user_socket_options);
503 mangle_reset_cache();
506 /* this forces service parameters to be flushed */
507 set_current_service(NULL,0,True);
514 /*******************************************************************
515 prepare to dump a core file - carefully!
516 ********************************************************************/
517 static BOOL dump_core(void)
522 pstrcpy(dname,lp_logfile());
523 if ((p=strrchr_m(dname,'/'))) *p=0;
524 pstrcat(dname,"/corefiles");
526 sys_chown(dname,getuid(),getgid());
528 if (chdir(dname)) return(False);
531 #ifdef HAVE_GETRLIMIT
535 getrlimit(RLIMIT_CORE, &rlp);
536 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
537 setrlimit(RLIMIT_CORE, &rlp);
538 getrlimit(RLIMIT_CORE, &rlp);
539 DEBUG(3,("Core limits now %d %d\n",
540 (int)rlp.rlim_cur,(int)rlp.rlim_max));
546 DEBUG(0,("Dumping core in %s\n", dname));
547 /* Ensure we don't have a signal handler for abort. */
549 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
556 /****************************************************************************
558 ****************************************************************************/
560 void exit_server(const char *reason)
562 static int firsttime=1;
563 extern char *last_inbuf;
564 extern struct auth_context *negprot_global_auth_context;
570 change_to_root_user();
571 DEBUG(2,("Closing connections\n"));
573 if (negprot_global_auth_context) {
574 (negprot_global_auth_context->free)(&negprot_global_auth_context);
579 invalidate_all_vuids();
581 print_notify_send_messages(3); /* 3 second timeout. */
583 /* run all registered exit events */
584 smb_run_exit_events();
586 /* delete our entry in the connections database. */
587 yield_connection(NULL,"");
589 respond_to_all_remaining_local_messages();
590 decrement_smbd_process_count();
593 if (dcelogin_atmost_once) {
599 int oldlevel = DEBUGLEVEL;
601 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
603 show_msg(last_inbuf);
604 DEBUGLEVEL = oldlevel;
605 DEBUG(0,("===============================================================\n"));
607 if (dump_core()) return;
614 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
618 /****************************************************************************
619 Initialise connect, service and file structs.
620 ****************************************************************************/
622 static BOOL init_structs(void )
625 * Set the machine NETBIOS name if not already
626 * set from the config file.
646 /****************************************************************************
648 ****************************************************************************/
650 /* Declare prototype for build_options() to avoid having to run it through
651 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
652 prototype generation system is too complicated. */
654 void build_options(BOOL screen);
656 int main(int argc,const char *argv[])
658 /* shall I run as a daemon */
659 static BOOL is_daemon = False;
660 static BOOL interactive = False;
661 static BOOL Fork = True;
662 static BOOL log_stdout = False;
663 static char *ports = NULL;
667 struct poptOption long_options[] = {
669 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
670 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
671 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
672 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
673 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
674 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
679 #ifdef HAVE_SET_AUTH_PARAMETERS
680 set_auth_parameters(argc,argv);
683 pc = poptGetContext("smbd", argc, argv, long_options, 0);
685 while((opt = poptGetNextOpt(pc)) != -1) {
688 build_options(True); /* Display output to screen as well as debug */
697 /* needed for SecureWare on SCO */
705 set_remote_machine_name("smbd", False);
712 if (log_stdout && Fork) {
713 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
717 setup_logging(argv[0],log_stdout);
719 /* we want to re-seed early to prevent time delays causing
720 client problems at a later date. (tridge) */
721 generate_random_buffer(NULL, 0);
723 /* make absolutely sure we run as root - to handle cases where people
724 are crazy enough to have it setuid */
726 gain_root_privilege();
727 gain_root_group_privilege();
729 fault_setup((void (*)(void *))exit_server);
730 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
731 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
733 /* we are never interested in SIGPIPE */
734 BlockSignals(True,SIGPIPE);
737 /* we are never interested in SIGFPE */
738 BlockSignals(True,SIGFPE);
742 /* We are no longer interested in USR2 */
743 BlockSignals(True,SIGUSR2);
746 /* POSIX demands that signals are inherited. If the invoking process has
747 * these signals masked, we will have problems, as we won't recieve them. */
748 BlockSignals(False, SIGHUP);
749 BlockSignals(False, SIGUSR1);
750 BlockSignals(False, SIGTERM);
752 /* we want total control over the permissions on created files,
753 so set our umask to 0 */
760 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
761 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2004\n"));
763 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
764 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
766 /* Output the build options to the debug log */
767 build_options(False);
769 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
770 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
775 * Do this before reload_services.
778 if (!reload_services(False))
783 if (!init_guest_info())
787 if (!profile_setup(False)) {
788 DEBUG(0,("ERROR: failed to setup profiling\n"));
793 DEBUG(3,( "loaded services\n"));
795 if (!is_daemon && !is_a_socket(0)) {
797 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
800 * Setting is_daemon here prevents us from eventually calling
801 * the open_sockets_inetd()
807 if (is_daemon && !interactive) {
808 DEBUG( 3, ( "Becoming a daemon.\n" ) );
814 * If we're interactive we want to set our own process group for
818 setpgid( (pid_t)0, (pid_t)0);
821 if (!directory_exist(lp_lockdir(), NULL))
822 mkdir(lp_lockdir(), 0755);
825 pidfile_create("smbd");
827 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
834 if (conn_tdb_ctx() == NULL)
837 if (!locking_init(0))
840 if (!share_info_db_init())
845 if (!init_registry())
848 if (!print_backend_init())
851 /* Setup the main smbd so that we can get messages. */
852 /* don't worry about general printing messages here */
854 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
856 /* only start the background queue daemon if we are
857 running as a daemon -- bad things will happen if
858 smbd is launched via inetd and we fork a copy of
862 start_background_queue();
864 if (!open_sockets_smbd(is_daemon, interactive, ports))
868 * everything after this point is run after the fork()
871 /* Initialise the password backed before the global_sam_sid
872 to ensure that we fetch from ldap before we make a domain sid up */
874 if(!initialize_password_db(False))
877 if(!get_global_sam_sid()) {
878 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
886 /* possibly reload the services file. */
887 reload_services(True);
889 if (!init_account_policy()) {
890 DEBUG(0,("Could not open account policy tdb.\n"));
895 if (sys_chroot(lp_rootdir()) == 0)
896 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
903 /* Setup change notify */
904 if (!init_change_notify())
907 /* re-initialise the timezone */
910 /* register our message handlers */
911 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
915 namecache_shutdown();
918 TALLOC_CTX *mem_ctx = talloc_init("end_description");
919 char *description = talloc_describe_all(mem_ctx);
921 DEBUG(3, ("tallocs left:\n%s\n", description));
922 talloc_destroy(mem_ctx);
925 exit_server("normal exit");