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 #ifdef HAVE_SYS_PRCTL_H
26 #include <sys/prctl.h>
29 static 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 struct auth_context *negprot_global_auth_context;
38 extern pstring user_socket_options;
39 extern SIG_ATOMIC_T got_sig_term;
40 extern SIG_ATOMIC_T reload_after_sighup;
43 extern int dcelogin_atmost_once;
46 /* really we should have a top level context structure that has the
47 client file descriptor as an element. That would require a major rewrite :(
49 the following 2 functions are an alternative - they make the file
50 descriptor private to smbd
52 static int server_fd = -1;
54 int smbd_server_fd(void)
59 static void smbd_set_server_fd(int fd)
65 /****************************************************************************
67 ****************************************************************************/
69 static void sig_term(void)
72 sys_select_signal(SIGTERM);
75 /****************************************************************************
77 ****************************************************************************/
79 static void sig_hup(int sig)
81 reload_after_sighup = 1;
82 sys_select_signal(SIGHUP);
85 /****************************************************************************
86 Send a SIGTERM to our process group.
87 *****************************************************************************/
89 static void killkids(void)
91 if(am_parent) kill(0,SIGTERM);
94 /****************************************************************************
95 Process a sam sync message - not sure whether to do this here or
97 ****************************************************************************/
99 static void msg_sam_sync(int UNUSED(msg_type), struct process_id UNUSED(pid),
100 void *UNUSED(buf), size_t UNUSED(len))
102 DEBUG(10, ("** sam sync message received, ignoring\n"));
105 /****************************************************************************
106 Process a sam sync replicate message - not sure whether to do this here or
108 ****************************************************************************/
110 static void msg_sam_repl(int msg_type, struct process_id pid,
111 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 */
136 close_low_fds(False); /* Don't close stderr */
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, struct process_id src,
145 void *buf, size_t len)
147 exit_server("Got a SHUTDOWN message");
151 /****************************************************************************
152 Have we reached the process limit ?
153 ****************************************************************************/
155 static BOOL allowable_number_of_smbd_processes(void)
157 int max_processes = lp_max_smbd_processes();
163 TDB_CONTEXT *tdb = conn_tdb_ctx();
166 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
170 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
171 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
172 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
173 tdb_errorstr(tdb) ));
176 if (val > max_processes) {
177 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
178 val, max_processes ));
185 /****************************************************************************
186 Open the socket communication.
187 ****************************************************************************/
189 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
191 int num_interfaces = iface_count();
193 int fd_listenset[FD_SETSIZE];
201 return open_sockets_inetd();
207 static int atexit_set;
208 if(atexit_set == 0) {
218 FD_ZERO(&listen_set);
220 /* use a reasonable default set of ports - listing on 445 and 139 */
222 ports = lp_smb_ports();
223 if (!ports || !*ports) {
224 ports = smb_xstrdup(SMB_PORTS);
226 ports = smb_xstrdup(ports);
229 ports = smb_xstrdup(smb_ports);
232 if (lp_interfaces() && lp_bind_interfaces_only()) {
233 /* We have been given an interfaces line, and been
234 told to only bind to those interfaces. Create a
235 socket per interface and bind to only these.
238 /* Now open a listen socket for each of the
240 for(i = 0; i < num_interfaces; i++) {
241 struct in_addr *ifip = iface_n_ip(i);
246 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
250 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
251 unsigned port = atoi(tok);
255 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
259 /* ready to listen */
260 set_socket_options(s,"SO_KEEPALIVE");
261 set_socket_options(s,user_socket_options);
263 /* Set server socket to non-blocking for the accept. */
264 set_blocking(s,False);
266 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
267 DEBUG(0,("listen: %s\n",strerror(errno)));
271 FD_SET(s,&listen_set);
272 maxfd = MAX( maxfd, s);
275 if (num_sockets >= FD_SETSIZE) {
276 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
282 /* Just bind to 0.0.0.0 - accept connections
290 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
291 unsigned port = atoi(tok);
292 if (port == 0) continue;
293 /* open an incoming socket */
294 s = open_socket_in(SOCK_STREAM, port, 0,
295 interpret_addr(lp_socket_address()),True);
299 /* ready to listen */
300 set_socket_options(s,"SO_KEEPALIVE");
301 set_socket_options(s,user_socket_options);
303 /* Set server socket to non-blocking for the accept. */
304 set_blocking(s,False);
306 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
307 DEBUG(0,("open_sockets_smbd: listen: %s\n",
313 fd_listenset[num_sockets] = s;
314 FD_SET(s,&listen_set);
315 maxfd = MAX( maxfd, s);
319 if (num_sockets >= FD_SETSIZE) {
320 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
328 /* Listen to messages */
330 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
331 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
332 message_register(MSG_SHUTDOWN, msg_exit_server);
333 message_register(MSG_SMB_FILE_RENAME, msg_file_was_renamed);
335 /* now accept incoming connections - forking a new process
336 for each incoming connection */
337 DEBUG(2,("waiting for a connection\n"));
342 /* Free up temporary memory from the main smbd. */
345 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
348 memcpy((char *)&lfds, (char *)&listen_set,
351 num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
353 if (num == -1 && errno == EINTR) {
355 exit_server("Caught TERM signal");
358 /* check for sighup processing */
359 if (reload_after_sighup) {
360 change_to_root_user();
361 DEBUG(1,("Reloading services after SIGHUP\n"));
362 reload_services(False);
363 reload_after_sighup = 0;
369 /* check if we need to reload services */
370 check_reload(time(NULL));
372 /* Find the sockets that are read-ready -
374 for( ; num > 0; num--) {
375 struct sockaddr addr;
376 socklen_t in_addrlen = sizeof(addr);
379 for(i = 0; i < num_sockets; i++) {
380 if(FD_ISSET(fd_listenset[i],&lfds)) {
382 /* Clear this so we don't look
384 FD_CLR(fd_listenset[i],&lfds);
389 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
391 if (smbd_server_fd() == -1 && errno == EINTR)
394 if (smbd_server_fd() == -1) {
395 DEBUG(0,("open_sockets_smbd: accept: %s\n",
400 /* Ensure child is set to blocking mode */
401 set_blocking(smbd_server_fd(),True);
403 if (smbd_server_fd() != -1 && interactive)
406 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
409 /* close the listening socket(s) */
410 for(i = 0; i < num_sockets; i++)
411 close(fd_listenset[i]);
413 /* close our standard file
415 close_low_fds(False);
418 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
419 set_socket_options(smbd_server_fd(),user_socket_options);
421 /* this is needed so that we get decent entries
422 in smbstatus for port 445 connects */
423 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
425 /* Reset the state of the random
426 * number generation system, so
427 * children do not get the same random
428 * numbers as each other */
430 set_need_random_reseed();
431 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
432 if (tdb_reopen_all() == -1) {
433 DEBUG(0,("tdb_reopen_all failed.\n"));
434 smb_panic("tdb_reopen_all failed.");
439 /* The parent doesn't need this socket */
440 close(smbd_server_fd());
442 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
443 Clear the closed fd info out of server_fd --
444 and more importantly, out of client_fd in
445 util_sock.c, to avoid a possible
446 getpeername failure if we reopen the logs
447 and use %I in the filename.
450 smbd_set_server_fd(-1);
452 /* Force parent to check log size after
453 * spawning child. Fix from
454 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
455 * parent smbd will log to logserver.smb. It
456 * writes only two messages for each child
457 * started/finished. But each child writes,
458 * say, 50 messages also in logserver.smb,
459 * begining with the debug_count of the
460 * parent, before the child opens its own log
461 * file logserver.client. In a worst case
462 * scenario the size of logserver.smb would be
463 * checked after about 50*50=2500 messages
466 force_check_log_size();
471 /* NOTREACHED return True; */
474 /****************************************************************************
476 **************************************************************************/
477 void reload_printers(void)
480 int n_services = lp_numservices();
481 int pnum = lp_servicenumber(PRINTERS_NAME);
486 /* remove stale printers */
487 for (snum = 0; snum < n_services; snum++) {
488 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
489 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
490 lp_autoloaded(snum)))
493 pname = lp_printername(snum);
494 if (!pcap_printername_ok(pname)) {
495 DEBUG(3, ("removing stale printer %s\n", pname));
497 if (is_printer_published(NULL, snum, NULL))
498 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
499 del_a_printer(pname);
500 lp_killservice(snum);
507 /****************************************************************************
508 Reload the services file.
509 **************************************************************************/
511 BOOL reload_services(BOOL test)
517 pstrcpy(fname,lp_configfile());
518 if (file_exist(fname, NULL) &&
519 !strcsequal(fname, dyn_CONFIGFILE)) {
520 pstrcpy(dyn_CONFIGFILE, fname);
527 if (test && !lp_file_list_changed())
530 lp_killunused(conn_snum_used);
532 ret = lp_load(dyn_CONFIGFILE, False, False, True);
536 /* perhaps the config filename is now set */
538 reload_services(True);
544 if (smbd_server_fd() != -1) {
545 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
546 set_socket_options(smbd_server_fd(), user_socket_options);
549 mangle_reset_cache();
552 /* this forces service parameters to be flushed */
553 set_current_service(NULL,0,True);
560 /*******************************************************************
561 prepare to dump a core file - carefully!
562 ********************************************************************/
563 static BOOL dump_core(void)
568 pstrcpy(dname,lp_logfile());
569 if ((p=strrchr_m(dname,'/'))) *p=0;
570 pstrcat(dname,"/corefiles");
572 sys_chown(dname,getuid(),getgid());
574 if (chdir(dname)) return(False);
577 #ifdef HAVE_GETRLIMIT
581 getrlimit(RLIMIT_CORE, &rlp);
582 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
583 setrlimit(RLIMIT_CORE, &rlp);
584 getrlimit(RLIMIT_CORE, &rlp);
585 DEBUG(3,("Core limits now %d %d\n",
586 (int)rlp.rlim_cur,(int)rlp.rlim_max));
592 DEBUG(0,("Dumping core in %s\n", dname));
593 /* Ensure we don't have a signal handler for abort. */
595 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
602 /****************************************************************************
604 ****************************************************************************/
606 void exit_server(const char *reason)
608 static int firsttime=1;
614 change_to_root_user();
615 DEBUG(2,("Closing connections\n"));
617 if (negprot_global_auth_context) {
618 (negprot_global_auth_context->free)(&negprot_global_auth_context);
623 invalidate_all_vuids();
625 print_notify_send_messages(3); /* 3 second timeout. */
627 /* delete our entry in the connections database. */
628 yield_connection(NULL,"");
630 respond_to_all_remaining_local_messages();
631 decrement_smbd_process_count();
634 if (dcelogin_atmost_once) {
640 int oldlevel = DEBUGLEVEL;
641 char *last_inbuf = get_InBuffer();
643 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
645 show_msg(last_inbuf);
646 DEBUGLEVEL = oldlevel;
647 DEBUG(0,("===============================================================\n"));
649 if (dump_core()) return;
656 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
660 /****************************************************************************
661 Initialise connect, service and file structs.
662 ****************************************************************************/
664 static BOOL init_structs(void )
667 * Set the machine NETBIOS name if not already
668 * set from the config file.
688 /****************************************************************************
690 ****************************************************************************/
692 /* Declare prototype for build_options() to avoid having to run it through
693 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
694 prototype generation system is too complicated. */
696 void build_options(BOOL screen);
698 int main(int argc,const char *argv[])
700 /* shall I run as a daemon */
701 static BOOL is_daemon = False;
702 static BOOL interactive = False;
703 static BOOL Fork = True;
704 static BOOL log_stdout = False;
705 static char *ports = NULL;
709 struct poptOption long_options[] = {
711 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
712 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
713 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
714 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
715 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
716 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
723 #ifdef HAVE_SET_AUTH_PARAMETERS
724 set_auth_parameters(argc,argv);
727 pc = poptGetContext("smbd", argc, argv, long_options, 0);
729 while((opt = poptGetNextOpt(pc)) != -1) {
732 build_options(True); /* Display output to screen as well as debug */
741 /* needed for SecureWare on SCO */
747 set_remote_machine_name("smbd", False);
754 if (interactive && (DEBUGLEVEL >= 9)) {
755 talloc_enable_leak_report();
758 if (log_stdout && Fork) {
759 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
763 setup_logging(argv[0],log_stdout);
765 /* we want to re-seed early to prevent time delays causing
766 client problems at a later date. (tridge) */
767 generate_random_buffer(NULL, 0);
769 /* make absolutely sure we run as root - to handle cases where people
770 are crazy enough to have it setuid */
772 gain_root_privilege();
773 gain_root_group_privilege();
775 fault_setup((void (*)(void *))exit_server);
776 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
777 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
779 /* we are never interested in SIGPIPE */
780 BlockSignals(True,SIGPIPE);
783 /* we are never interested in SIGFPE */
784 BlockSignals(True,SIGFPE);
788 /* We are no longer interested in USR2 */
789 BlockSignals(True,SIGUSR2);
792 /* POSIX demands that signals are inherited. If the invoking process has
793 * these signals masked, we will have problems, as we won't recieve them. */
794 BlockSignals(False, SIGHUP);
795 BlockSignals(False, SIGUSR1);
796 BlockSignals(False, SIGTERM);
798 /* we want total control over the permissions on created files,
799 so set our umask to 0 */
806 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
807 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
809 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
810 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
812 /* Output the build options to the debug log */
813 build_options(False);
815 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
816 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
821 * Do this before reload_services.
824 if (!reload_services(False))
829 if (!init_guest_info()) {
830 DEBUG(0,("ERROR: failed to setup guest info.\n"));
835 if (!profile_setup(False)) {
836 DEBUG(0,("ERROR: failed to setup profiling\n"));
841 DEBUG(3,( "loaded services\n"));
843 if (!is_daemon && !is_a_socket(0)) {
845 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
848 * Setting is_daemon here prevents us from eventually calling
849 * the open_sockets_inetd()
855 if (is_daemon && !interactive) {
856 DEBUG( 3, ( "Becoming a daemon.\n" ) );
862 * If we're interactive we want to set our own process group for
866 setpgid( (pid_t)0, (pid_t)0);
869 if (!directory_exist(lp_lockdir(), NULL))
870 mkdir(lp_lockdir(), 0755);
873 pidfile_create("smbd");
875 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
882 if (conn_tdb_ctx() == NULL)
885 if (!locking_init(0))
888 if (!share_info_db_init())
893 if (!init_registry())
897 if (!init_svcctl_db())
901 if (!print_backend_init())
904 /* Setup the main smbd so that we can get messages. */
905 /* don't worry about general printing messages here */
907 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
909 /* only start the background queue daemon if we are
910 running as a daemon -- bad things will happen if
911 smbd is launched via inetd and we fork a copy of
914 if ( is_daemon && !interactive )
915 start_background_queue();
917 if (!open_sockets_smbd(is_daemon, interactive, ports))
921 * everything after this point is run after the fork()
924 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
925 /* On Linux we lose the ability to dump core when we change our user
926 * ID. We know how to dump core safely, so let's make sure we have our
929 prctl(PR_SET_DUMPABLE, 1);
932 /* Initialise the password backed before the global_sam_sid
933 to ensure that we fetch from ldap before we make a domain sid up */
935 if(!initialize_password_db(False))
938 if(!get_global_sam_sid()) {
939 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
947 /* possibly reload the services file. */
948 reload_services(True);
950 if (!init_account_policy()) {
951 DEBUG(0,("Could not open account policy tdb.\n"));
956 if (sys_chroot(lp_rootdir()) == 0)
957 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
964 /* Setup change notify */
965 if (!init_change_notify())
968 /* Setup aio signal handler. */
969 initialize_async_io_handler();
971 /* re-initialise the timezone */
974 /* register our message handlers */
975 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
979 namecache_shutdown();
981 exit_server("normal exit");