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 /*******************************************************************
66 What to do when smb.conf is updated.
67 ********************************************************************/
69 static void smb_conf_updated(int msg_type, struct process_id src,
70 void *buf, size_t len)
72 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was updated. Reloading.\n"));
73 reload_services(False);
77 /****************************************************************************
79 ****************************************************************************/
81 static void sig_term(void)
84 sys_select_signal(SIGTERM);
87 /****************************************************************************
89 ****************************************************************************/
91 static void sig_hup(int sig)
93 reload_after_sighup = 1;
94 sys_select_signal(SIGHUP);
97 /****************************************************************************
98 Send a SIGTERM to our process group.
99 *****************************************************************************/
101 static void killkids(void)
103 if(am_parent) kill(0,SIGTERM);
106 /****************************************************************************
107 Process a sam sync message - not sure whether to do this here or
109 ****************************************************************************/
111 static void msg_sam_sync(int UNUSED(msg_type), struct process_id UNUSED(pid),
112 void *UNUSED(buf), size_t UNUSED(len))
114 DEBUG(10, ("** sam sync message received, ignoring\n"));
117 /****************************************************************************
118 Process a sam sync replicate message - not sure whether to do this here or
120 ****************************************************************************/
122 static void msg_sam_repl(int msg_type, struct process_id pid,
123 void *buf, size_t len)
127 if (len != sizeof(uint32))
130 low_serial = *((uint32 *)buf);
132 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
136 /****************************************************************************
137 Open the socket communication - inetd.
138 ****************************************************************************/
140 static BOOL open_sockets_inetd(void)
142 /* Started from inetd. fd 0 is the socket. */
143 /* We will abort gracefully when the client or remote system
145 smbd_set_server_fd(dup(0));
147 /* close our standard file descriptors */
148 close_low_fds(False); /* Don't close stderr */
150 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
151 set_socket_options(smbd_server_fd(), user_socket_options);
156 static void msg_exit_server(int msg_type, struct process_id src,
157 void *buf, size_t len)
159 exit_server("Got a SHUTDOWN message");
163 /****************************************************************************
164 Have we reached the process limit ?
165 ****************************************************************************/
167 static BOOL allowable_number_of_smbd_processes(void)
169 int max_processes = lp_max_smbd_processes();
175 TDB_CONTEXT *tdb = conn_tdb_ctx();
178 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
182 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
183 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
184 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
185 tdb_errorstr(tdb) ));
188 if (val > max_processes) {
189 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
190 val, max_processes ));
197 /****************************************************************************
198 Open the socket communication.
199 ****************************************************************************/
201 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
203 int num_interfaces = iface_count();
205 int fd_listenset[FD_SETSIZE];
213 return open_sockets_inetd();
219 static int atexit_set;
220 if(atexit_set == 0) {
230 FD_ZERO(&listen_set);
232 /* use a reasonable default set of ports - listing on 445 and 139 */
234 ports = lp_smb_ports();
235 if (!ports || !*ports) {
236 ports = smb_xstrdup(SMB_PORTS);
238 ports = smb_xstrdup(ports);
241 ports = smb_xstrdup(smb_ports);
244 if (lp_interfaces() && lp_bind_interfaces_only()) {
245 /* We have been given an interfaces line, and been
246 told to only bind to those interfaces. Create a
247 socket per interface and bind to only these.
250 /* Now open a listen socket for each of the
252 for(i = 0; i < num_interfaces; i++) {
253 struct in_addr *ifip = iface_n_ip(i);
258 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
262 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
263 unsigned port = atoi(tok);
267 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
271 /* ready to listen */
272 set_socket_options(s,"SO_KEEPALIVE");
273 set_socket_options(s,user_socket_options);
275 /* Set server socket to non-blocking for the accept. */
276 set_blocking(s,False);
278 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
279 DEBUG(0,("listen: %s\n",strerror(errno)));
283 FD_SET(s,&listen_set);
284 maxfd = MAX( maxfd, s);
287 if (num_sockets >= FD_SETSIZE) {
288 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
294 /* Just bind to 0.0.0.0 - accept connections
302 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
303 unsigned port = atoi(tok);
304 if (port == 0) continue;
305 /* open an incoming socket */
306 s = open_socket_in(SOCK_STREAM, port, 0,
307 interpret_addr(lp_socket_address()),True);
311 /* ready to listen */
312 set_socket_options(s,"SO_KEEPALIVE");
313 set_socket_options(s,user_socket_options);
315 /* Set server socket to non-blocking for the accept. */
316 set_blocking(s,False);
318 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
319 DEBUG(0,("open_sockets_smbd: listen: %s\n",
325 fd_listenset[num_sockets] = s;
326 FD_SET(s,&listen_set);
327 maxfd = MAX( maxfd, s);
331 if (num_sockets >= FD_SETSIZE) {
332 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
340 /* Listen to messages */
342 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
343 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
344 message_register(MSG_SHUTDOWN, msg_exit_server);
345 message_register(MSG_SMB_FILE_RENAME, msg_file_was_renamed);
346 message_register(MSG_SMB_CONF_UPDATED, smb_conf_updated);
348 /* now accept incoming connections - forking a new process
349 for each incoming connection */
350 DEBUG(2,("waiting for a connection\n"));
355 /* Free up temporary memory from the main smbd. */
358 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
361 memcpy((char *)&lfds, (char *)&listen_set,
364 num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
366 if (num == -1 && errno == EINTR) {
368 exit_server("Caught TERM signal");
371 /* check for sighup processing */
372 if (reload_after_sighup) {
373 change_to_root_user();
374 DEBUG(1,("Reloading services after SIGHUP\n"));
375 reload_services(False);
376 reload_after_sighup = 0;
382 /* check if we need to reload services */
383 check_reload(time(NULL));
385 /* Find the sockets that are read-ready -
387 for( ; num > 0; num--) {
388 struct sockaddr addr;
389 socklen_t in_addrlen = sizeof(addr);
392 for(i = 0; i < num_sockets; i++) {
393 if(FD_ISSET(fd_listenset[i],&lfds)) {
395 /* Clear this so we don't look
397 FD_CLR(fd_listenset[i],&lfds);
402 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
404 if (smbd_server_fd() == -1 && errno == EINTR)
407 if (smbd_server_fd() == -1) {
408 DEBUG(0,("open_sockets_smbd: accept: %s\n",
413 /* Ensure child is set to blocking mode */
414 set_blocking(smbd_server_fd(),True);
416 if (smbd_server_fd() != -1 && interactive)
419 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
422 /* close the listening socket(s) */
423 for(i = 0; i < num_sockets; i++)
424 close(fd_listenset[i]);
426 /* close our standard file
428 close_low_fds(False);
431 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
432 set_socket_options(smbd_server_fd(),user_socket_options);
434 /* this is needed so that we get decent entries
435 in smbstatus for port 445 connects */
436 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
438 /* Reset the state of the random
439 * number generation system, so
440 * children do not get the same random
441 * numbers as each other */
443 set_need_random_reseed();
444 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
445 if (tdb_reopen_all() == -1) {
446 DEBUG(0,("tdb_reopen_all failed.\n"));
447 smb_panic("tdb_reopen_all failed.");
452 /* The parent doesn't need this socket */
453 close(smbd_server_fd());
455 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
456 Clear the closed fd info out of server_fd --
457 and more importantly, out of client_fd in
458 util_sock.c, to avoid a possible
459 getpeername failure if we reopen the logs
460 and use %I in the filename.
463 smbd_set_server_fd(-1);
465 /* Force parent to check log size after
466 * spawning child. Fix from
467 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
468 * parent smbd will log to logserver.smb. It
469 * writes only two messages for each child
470 * started/finished. But each child writes,
471 * say, 50 messages also in logserver.smb,
472 * begining with the debug_count of the
473 * parent, before the child opens its own log
474 * file logserver.client. In a worst case
475 * scenario the size of logserver.smb would be
476 * checked after about 50*50=2500 messages
479 force_check_log_size();
484 /* NOTREACHED return True; */
487 /****************************************************************************
489 **************************************************************************/
490 void reload_printers(void)
493 int n_services = lp_numservices();
494 int pnum = lp_servicenumber(PRINTERS_NAME);
499 /* remove stale printers */
500 for (snum = 0; snum < n_services; snum++) {
501 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
502 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
503 lp_autoloaded(snum)))
506 pname = lp_printername(snum);
507 if (!pcap_printername_ok(pname)) {
508 DEBUG(3, ("removing stale printer %s\n", pname));
510 if (is_printer_published(NULL, snum, NULL))
511 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
512 del_a_printer(pname);
513 lp_killservice(snum);
520 /****************************************************************************
521 Reload the services file.
522 **************************************************************************/
524 BOOL reload_services(BOOL test)
530 pstrcpy(fname,lp_configfile());
531 if (file_exist(fname, NULL) &&
532 !strcsequal(fname, dyn_CONFIGFILE)) {
533 pstrcpy(dyn_CONFIGFILE, fname);
540 if (test && !lp_file_list_changed())
543 lp_killunused(conn_snum_used);
545 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
549 /* perhaps the config filename is now set */
551 reload_services(True);
557 if (smbd_server_fd() != -1) {
558 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
559 set_socket_options(smbd_server_fd(), user_socket_options);
562 mangle_reset_cache();
565 /* this forces service parameters to be flushed */
566 set_current_service(NULL,0,True);
573 /*******************************************************************
574 prepare to dump a core file - carefully!
575 ********************************************************************/
576 static BOOL dump_core(void)
581 pstrcpy(dname,lp_logfile());
582 if ((p=strrchr_m(dname,'/'))) *p=0;
583 pstrcat(dname,"/corefiles");
585 sys_chown(dname,getuid(),getgid());
587 if (chdir(dname)) return(False);
590 #ifdef HAVE_GETRLIMIT
594 getrlimit(RLIMIT_CORE, &rlp);
595 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
596 setrlimit(RLIMIT_CORE, &rlp);
597 getrlimit(RLIMIT_CORE, &rlp);
598 DEBUG(3,("Core limits now %d %d\n",
599 (int)rlp.rlim_cur,(int)rlp.rlim_max));
605 DEBUG(0,("Dumping core in %s\n", dname));
606 /* Ensure we don't have a signal handler for abort. */
608 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
615 /****************************************************************************
617 ****************************************************************************/
619 void exit_server(const char *reason)
621 static int firsttime=1;
627 change_to_root_user();
628 DEBUG(2,("Closing connections\n"));
630 if (negprot_global_auth_context) {
631 (negprot_global_auth_context->free)(&negprot_global_auth_context);
636 invalidate_all_vuids();
638 print_notify_send_messages(3); /* 3 second timeout. */
640 /* delete our entry in the connections database. */
641 yield_connection(NULL,"");
643 respond_to_all_remaining_local_messages();
644 decrement_smbd_process_count();
647 if (dcelogin_atmost_once) {
653 int oldlevel = DEBUGLEVEL;
654 char *last_inbuf = get_InBuffer();
656 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
658 show_msg(last_inbuf);
659 DEBUGLEVEL = oldlevel;
660 DEBUG(0,("===============================================================\n"));
662 if (dump_core()) return;
669 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
673 /****************************************************************************
674 Initialise connect, service and file structs.
675 ****************************************************************************/
677 static BOOL init_structs(void )
680 * Set the machine NETBIOS name if not already
681 * set from the config file.
701 /****************************************************************************
703 ****************************************************************************/
705 /* Declare prototype for build_options() to avoid having to run it through
706 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
707 prototype generation system is too complicated. */
709 void build_options(BOOL screen);
711 int main(int argc,const char *argv[])
713 extern BOOL in_server;
714 /* shall I run as a daemon */
715 static BOOL is_daemon = False;
716 static BOOL interactive = False;
717 static BOOL Fork = True;
718 static BOOL no_process_group = False;
719 static BOOL log_stdout = False;
720 static char *ports = NULL;
724 struct poptOption long_options[] = {
726 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
727 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
728 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
729 {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
730 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
731 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
732 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
741 #ifdef HAVE_SET_AUTH_PARAMETERS
742 set_auth_parameters(argc,argv);
745 pc = poptGetContext("smbd", argc, argv, long_options, 0);
747 while((opt = poptGetNextOpt(pc)) != -1) {
750 build_options(True); /* Display output to screen as well as debug */
759 /* needed for SecureWare on SCO */
765 set_remote_machine_name("smbd", False);
772 if (interactive && (DEBUGLEVEL >= 9)) {
773 talloc_enable_leak_report();
776 if (log_stdout && Fork) {
777 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
781 setup_logging(argv[0],log_stdout);
783 /* we want to re-seed early to prevent time delays causing
784 client problems at a later date. (tridge) */
785 generate_random_buffer(NULL, 0);
787 /* make absolutely sure we run as root - to handle cases where people
788 are crazy enough to have it setuid */
790 gain_root_privilege();
791 gain_root_group_privilege();
793 fault_setup((void (*)(void *))exit_server);
794 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
795 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
797 /* we are never interested in SIGPIPE */
798 BlockSignals(True,SIGPIPE);
801 /* we are never interested in SIGFPE */
802 BlockSignals(True,SIGFPE);
806 /* We are no longer interested in USR2 */
807 BlockSignals(True,SIGUSR2);
810 /* POSIX demands that signals are inherited. If the invoking process has
811 * these signals masked, we will have problems, as we won't recieve them. */
812 BlockSignals(False, SIGHUP);
813 BlockSignals(False, SIGUSR1);
814 BlockSignals(False, SIGTERM);
816 /* we want total control over the permissions on created files,
817 so set our umask to 0 */
824 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
825 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
827 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
828 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
830 /* Output the build options to the debug log */
831 build_options(False);
833 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
834 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
839 * Do this before reload_services.
842 if (!reload_services(False))
848 if (!profile_setup(False)) {
849 DEBUG(0,("ERROR: failed to setup profiling\n"));
854 DEBUG(3,( "loaded services\n"));
856 if (!is_daemon && !is_a_socket(0)) {
858 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
861 * Setting is_daemon here prevents us from eventually calling
862 * the open_sockets_inetd()
868 if (is_daemon && !interactive) {
869 DEBUG( 3, ( "Becoming a daemon.\n" ) );
870 become_daemon(Fork, no_process_group);
875 * If we're interactive we want to set our own process group for
878 if (interactive && !no_process_group) {
879 setpgid( (pid_t)0, (pid_t)0);
883 if (!directory_exist(lp_lockdir(), NULL))
884 mkdir(lp_lockdir(), 0755);
887 pidfile_create("smbd");
889 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
896 if (conn_tdb_ctx() == NULL)
899 if (!locking_init(0))
904 if (!init_registry())
908 if (!init_svcctl_db())
912 if (!print_backend_init())
915 if (!init_guest_info()) {
916 DEBUG(0,("ERROR: failed to setup guest info.\n"));
920 /* Setup the main smbd so that we can get messages. */
921 /* don't worry about general printing messages here */
923 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
925 /* only start the background queue daemon if we are
926 running as a daemon -- bad things will happen if
927 smbd is launched via inetd and we fork a copy of
930 if ( is_daemon && !interactive )
931 start_background_queue();
933 /* Always attempt to initialize DMAPI. We will only use it later if
934 * lp_dmapi_support is set on the share, but we need a single global
935 * session to work with.
937 dmapi_init_session();
939 if (!open_sockets_smbd(is_daemon, interactive, ports))
943 * everything after this point is run after the fork()
946 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
947 /* On Linux we lose the ability to dump core when we change our user
948 * ID. We know how to dump core safely, so let's make sure we have our
951 prctl(PR_SET_DUMPABLE, 1);
954 /* Initialise the password backed before the global_sam_sid
955 to ensure that we fetch from ldap before we make a domain sid up */
957 if(!initialize_password_db(False))
960 if(!get_global_sam_sid()) {
961 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
969 /* possibly reload the services file. */
970 reload_services(True);
972 if (!init_account_policy()) {
973 DEBUG(0,("Could not open account policy tdb.\n"));
978 if (sys_chroot(lp_rootdir()) == 0)
979 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
986 /* Setup change notify */
987 if (!init_change_notify())
990 /* Setup aio signal handler. */
991 initialize_async_io_handler();
993 /* re-initialise the timezone */
996 /* register our message handlers */
997 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1001 namecache_shutdown();
1003 exit_server("normal exit");