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 struct auth_context *negprot_global_auth_context;
34 extern pstring user_socket_options;
35 extern SIG_ATOMIC_T got_sig_term;
36 extern SIG_ATOMIC_T reload_after_sighup;
39 extern int dcelogin_atmost_once;
42 /* really we should have a top level context structure that has the
43 client file descriptor as an element. That would require a major rewrite :(
45 the following 2 functions are an alternative - they make the file
46 descriptor private to smbd
48 static int server_fd = -1;
50 int smbd_server_fd(void)
55 static void smbd_set_server_fd(int fd)
61 /*******************************************************************
62 What to do when smb.conf is updated.
63 ********************************************************************/
65 static void smb_conf_updated(int msg_type, struct process_id src,
66 void *buf, size_t len)
68 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was updated. Reloading.\n"));
69 reload_services(False);
73 /****************************************************************************
75 ****************************************************************************/
77 static void sig_term(void)
80 sys_select_signal(SIGTERM);
83 /****************************************************************************
85 ****************************************************************************/
87 static void sig_hup(int sig)
89 reload_after_sighup = 1;
90 sys_select_signal(SIGHUP);
93 /****************************************************************************
94 Send a SIGTERM to our process group.
95 *****************************************************************************/
97 static void killkids(void)
99 if(am_parent) kill(0,SIGTERM);
102 /****************************************************************************
103 Process a sam sync message - not sure whether to do this here or
105 ****************************************************************************/
107 static void msg_sam_sync(int UNUSED(msg_type), struct process_id UNUSED(pid),
108 void *UNUSED(buf), size_t UNUSED(len))
110 DEBUG(10, ("** sam sync message received, ignoring\n"));
113 /****************************************************************************
114 Process a sam sync replicate message - not sure whether to do this here or
116 ****************************************************************************/
118 static void msg_sam_repl(int msg_type, struct process_id pid,
119 void *buf, size_t len)
123 if (len != sizeof(uint32))
126 low_serial = *((uint32 *)buf);
128 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
132 /****************************************************************************
133 Open the socket communication - inetd.
134 ****************************************************************************/
136 static BOOL open_sockets_inetd(void)
138 /* Started from inetd. fd 0 is the socket. */
139 /* We will abort gracefully when the client or remote system
141 smbd_set_server_fd(dup(0));
143 /* close our standard file descriptors */
144 close_low_fds(False); /* Don't close stderr */
146 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
147 set_socket_options(smbd_server_fd(), user_socket_options);
152 static void msg_exit_server(int msg_type, struct process_id src,
153 void *buf, size_t len)
155 DEBUG(3, ("got a SHUTDOWN message\n"));
156 exit_server_cleanly();
160 static void msg_inject_fault(int msg_type, struct process_id src,
161 void *buf, size_t len)
165 if (len != sizeof(int)) {
167 DEBUG(0, ("Process %llu sent bogus signal injection request\n",
168 (unsigned long long)src.pid));
174 exit_server("internal error injected");
179 DEBUG(0, ("Process %llu requested injection of signal %d (%s)\n",
180 (unsigned long long)src.pid, sig, strsignal(sig)));
182 DEBUG(0, ("Process %llu requested injection of signal %d\n",
183 (unsigned long long)src.pid, sig));
186 kill(sys_getpid(), sig);
188 #endif /* DEVELOPER */
191 /****************************************************************************
192 Have we reached the process limit ?
193 ****************************************************************************/
195 static BOOL allowable_number_of_smbd_processes(void)
197 int max_processes = lp_max_smbd_processes();
203 TDB_CONTEXT *tdb = conn_tdb_ctx();
206 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
210 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
211 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
212 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
213 tdb_errorstr(tdb) ));
216 if (val > max_processes) {
217 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
218 val, max_processes ));
225 /****************************************************************************
226 Open the socket communication.
227 ****************************************************************************/
229 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
231 int num_interfaces = iface_count();
233 int fd_listenset[FD_SETSIZE];
241 return open_sockets_inetd();
247 static int atexit_set;
248 if(atexit_set == 0) {
258 FD_ZERO(&listen_set);
260 /* use a reasonable default set of ports - listing on 445 and 139 */
262 ports = lp_smb_ports();
263 if (!ports || !*ports) {
264 ports = smb_xstrdup(SMB_PORTS);
266 ports = smb_xstrdup(ports);
269 ports = smb_xstrdup(smb_ports);
272 if (lp_interfaces() && lp_bind_interfaces_only()) {
273 /* We have been given an interfaces line, and been
274 told to only bind to those interfaces. Create a
275 socket per interface and bind to only these.
278 /* Now open a listen socket for each of the
280 for(i = 0; i < num_interfaces; i++) {
281 struct in_addr *ifip = iface_n_ip(i);
286 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
290 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
291 unsigned port = atoi(tok);
295 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, 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,("listen: %s\n",strerror(errno)));
311 FD_SET(s,&listen_set);
312 maxfd = MAX( maxfd, s);
315 if (num_sockets >= FD_SETSIZE) {
316 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
322 /* Just bind to 0.0.0.0 - accept connections
330 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
331 unsigned port = atoi(tok);
332 if (port == 0) continue;
333 /* open an incoming socket */
334 s = open_socket_in(SOCK_STREAM, port, 0,
335 interpret_addr(lp_socket_address()),True);
339 /* ready to listen */
340 set_socket_options(s,"SO_KEEPALIVE");
341 set_socket_options(s,user_socket_options);
343 /* Set server socket to non-blocking for the accept. */
344 set_blocking(s,False);
346 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
347 DEBUG(0,("open_sockets_smbd: listen: %s\n",
353 fd_listenset[num_sockets] = s;
354 FD_SET(s,&listen_set);
355 maxfd = MAX( maxfd, s);
359 if (num_sockets >= FD_SETSIZE) {
360 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
368 /* Listen to messages */
370 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
371 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
372 message_register(MSG_SHUTDOWN, msg_exit_server);
373 message_register(MSG_SMB_FILE_RENAME, msg_file_was_renamed);
374 message_register(MSG_SMB_CONF_UPDATED, smb_conf_updated);
377 message_register(MSG_SMB_INJECT_FAULT, msg_inject_fault);
380 /* now accept incoming connections - forking a new process
381 for each incoming connection */
382 DEBUG(2,("waiting for a connection\n"));
387 /* Free up temporary memory from the main smbd. */
390 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
393 memcpy((char *)&lfds, (char *)&listen_set,
396 num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
398 if (num == -1 && errno == EINTR) {
400 exit_server_cleanly();
403 /* check for sighup processing */
404 if (reload_after_sighup) {
405 change_to_root_user();
406 DEBUG(1,("Reloading services after SIGHUP\n"));
407 reload_services(False);
408 reload_after_sighup = 0;
414 /* check if we need to reload services */
415 check_reload(time(NULL));
417 /* Find the sockets that are read-ready -
419 for( ; num > 0; num--) {
420 struct sockaddr addr;
421 socklen_t in_addrlen = sizeof(addr);
424 for(i = 0; i < num_sockets; i++) {
425 if(FD_ISSET(fd_listenset[i],&lfds)) {
427 /* Clear this so we don't look
429 FD_CLR(fd_listenset[i],&lfds);
434 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
436 if (smbd_server_fd() == -1 && errno == EINTR)
439 if (smbd_server_fd() == -1) {
440 DEBUG(0,("open_sockets_smbd: accept: %s\n",
445 /* Ensure child is set to blocking mode */
446 set_blocking(smbd_server_fd(),True);
448 if (smbd_server_fd() != -1 && interactive)
451 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
454 /* close the listening socket(s) */
455 for(i = 0; i < num_sockets; i++)
456 close(fd_listenset[i]);
458 /* close our standard file
460 close_low_fds(False);
463 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
464 set_socket_options(smbd_server_fd(),user_socket_options);
466 /* this is needed so that we get decent entries
467 in smbstatus for port 445 connects */
468 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
470 /* Reset the state of the random
471 * number generation system, so
472 * children do not get the same random
473 * numbers as each other */
475 set_need_random_reseed();
476 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
477 if (tdb_reopen_all() == -1) {
478 DEBUG(0,("tdb_reopen_all failed.\n"));
479 smb_panic("tdb_reopen_all failed.");
484 /* The parent doesn't need this socket */
485 close(smbd_server_fd());
487 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
488 Clear the closed fd info out of server_fd --
489 and more importantly, out of client_fd in
490 util_sock.c, to avoid a possible
491 getpeername failure if we reopen the logs
492 and use %I in the filename.
495 smbd_set_server_fd(-1);
497 /* Force parent to check log size after
498 * spawning child. Fix from
499 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
500 * parent smbd will log to logserver.smb. It
501 * writes only two messages for each child
502 * started/finished. But each child writes,
503 * say, 50 messages also in logserver.smb,
504 * begining with the debug_count of the
505 * parent, before the child opens its own log
506 * file logserver.client. In a worst case
507 * scenario the size of logserver.smb would be
508 * checked after about 50*50=2500 messages
511 force_check_log_size();
516 /* NOTREACHED return True; */
519 /****************************************************************************
521 **************************************************************************/
522 void reload_printers(void)
525 int n_services = lp_numservices();
526 int pnum = lp_servicenumber(PRINTERS_NAME);
531 /* remove stale printers */
532 for (snum = 0; snum < n_services; snum++) {
533 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
534 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
535 lp_autoloaded(snum)))
538 pname = lp_printername(snum);
539 if (!pcap_printername_ok(pname)) {
540 DEBUG(3, ("removing stale printer %s\n", pname));
542 if (is_printer_published(NULL, snum, NULL))
543 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
544 del_a_printer(pname);
545 lp_killservice(snum);
552 /****************************************************************************
553 Reload the services file.
554 **************************************************************************/
556 BOOL reload_services(BOOL test)
562 pstrcpy(fname,lp_configfile());
563 if (file_exist(fname, NULL) &&
564 !strcsequal(fname, dyn_CONFIGFILE)) {
565 pstrcpy(dyn_CONFIGFILE, fname);
572 if (test && !lp_file_list_changed())
575 lp_killunused(conn_snum_used);
577 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
581 /* perhaps the config filename is now set */
583 reload_services(True);
589 if (smbd_server_fd() != -1) {
590 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
591 set_socket_options(smbd_server_fd(), user_socket_options);
594 mangle_reset_cache();
597 /* this forces service parameters to be flushed */
598 set_current_service(NULL,0,True);
603 /****************************************************************************
605 ****************************************************************************/
607 /* Reasons for shutting down a server process. */
608 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
610 static void exit_server_common(enum server_exit_reason how,
611 const char *const reason) NORETURN_ATTRIBUTE;
613 static void exit_server_common(enum server_exit_reason how,
614 const char *const reason)
616 static int firsttime=1;
622 change_to_root_user();
624 if (negprot_global_auth_context) {
625 (negprot_global_auth_context->free)(&negprot_global_auth_context);
630 invalidate_all_vuids();
632 print_notify_send_messages(3); /* 3 second timeout. */
634 /* delete our entry in the connections database. */
635 yield_connection(NULL,"");
637 respond_to_all_remaining_local_messages();
638 decrement_smbd_process_count();
641 if (dcelogin_atmost_once) {
649 if (how != SERVER_EXIT_NORMAL) {
650 int oldlevel = DEBUGLEVEL;
651 char *last_inbuf = get_InBuffer();
656 DEBUG(0,("Abnormal server exit: %s\n",
657 reason ? reason : "no explanation provided"));
662 DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
663 show_msg(last_inbuf);
666 DEBUGLEVEL = oldlevel;
672 DEBUG(3,("Server exit (%s)\n",
673 (reason ? reason : "normal exit")));
679 void exit_server(const char *const explanation)
681 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
684 void exit_server_cleanly(void)
686 exit_server_common(SERVER_EXIT_NORMAL, NULL);
689 void exit_server_fault(void)
691 exit_server("critical server fault");
694 /****************************************************************************
695 Initialise connect, service and file structs.
696 ****************************************************************************/
698 static BOOL init_structs(void )
701 * Set the machine NETBIOS name if not already
702 * set from the config file.
722 /****************************************************************************
724 ****************************************************************************/
726 /* Declare prototype for build_options() to avoid having to run it through
727 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
728 prototype generation system is too complicated. */
730 void build_options(BOOL screen);
732 int main(int argc,const char *argv[])
734 extern BOOL in_server;
735 /* shall I run as a daemon */
736 static BOOL is_daemon = False;
737 static BOOL interactive = False;
738 static BOOL Fork = True;
739 static BOOL no_process_group = False;
740 static BOOL log_stdout = False;
741 static char *ports = NULL;
745 struct poptOption long_options[] = {
747 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
748 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
749 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
750 {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
751 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
752 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
753 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
762 #ifdef HAVE_SET_AUTH_PARAMETERS
763 set_auth_parameters(argc,argv);
766 pc = poptGetContext("smbd", argc, argv, long_options, 0);
768 while((opt = poptGetNextOpt(pc)) != -1) {
771 build_options(True); /* Display output to screen as well as debug */
780 /* needed for SecureWare on SCO */
786 set_remote_machine_name("smbd", False);
793 if (interactive && (DEBUGLEVEL >= 9)) {
794 talloc_enable_leak_report();
797 if (log_stdout && Fork) {
798 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
802 setup_logging(argv[0],log_stdout);
804 /* we want to re-seed early to prevent time delays causing
805 client problems at a later date. (tridge) */
806 generate_random_buffer(NULL, 0);
808 /* make absolutely sure we run as root - to handle cases where people
809 are crazy enough to have it setuid */
811 gain_root_privilege();
812 gain_root_group_privilege();
814 fault_setup((void (*)(void *))exit_server_fault);
815 dump_core_setup("smbd");
817 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
818 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
820 /* we are never interested in SIGPIPE */
821 BlockSignals(True,SIGPIPE);
824 /* we are never interested in SIGFPE */
825 BlockSignals(True,SIGFPE);
829 /* We are no longer interested in USR2 */
830 BlockSignals(True,SIGUSR2);
833 /* POSIX demands that signals are inherited. If the invoking process has
834 * these signals masked, we will have problems, as we won't recieve them. */
835 BlockSignals(False, SIGHUP);
836 BlockSignals(False, SIGUSR1);
837 BlockSignals(False, SIGTERM);
839 /* we want total control over the permissions on created files,
840 so set our umask to 0 */
847 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
848 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
850 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
851 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
853 /* Output the build options to the debug log */
854 build_options(False);
856 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
857 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
862 * Do this before reload_services.
865 if (!reload_services(False))
871 if (!profile_setup(False)) {
872 DEBUG(0,("ERROR: failed to setup profiling\n"));
877 DEBUG(3,( "loaded services\n"));
879 if (!is_daemon && !is_a_socket(0)) {
881 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
884 * Setting is_daemon here prevents us from eventually calling
885 * the open_sockets_inetd()
891 if (is_daemon && !interactive) {
892 DEBUG( 3, ( "Becoming a daemon.\n" ) );
893 become_daemon(Fork, no_process_group);
898 * If we're interactive we want to set our own process group for
901 if (interactive && !no_process_group) {
902 setpgid( (pid_t)0, (pid_t)0);
906 if (!directory_exist(lp_lockdir(), NULL))
907 mkdir(lp_lockdir(), 0755);
910 pidfile_create("smbd");
912 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
919 if (conn_tdb_ctx() == NULL)
922 if (!locking_init(0))
927 if (!init_registry())
931 if (!init_svcctl_db())
935 if (!print_backend_init())
938 if (!init_guest_info()) {
939 DEBUG(0,("ERROR: failed to setup guest info.\n"));
943 /* Setup the main smbd so that we can get messages. */
944 /* don't worry about general printing messages here */
946 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
948 /* only start the background queue daemon if we are
949 running as a daemon -- bad things will happen if
950 smbd is launched via inetd and we fork a copy of
953 if ( is_daemon && !interactive )
954 start_background_queue();
956 /* Always attempt to initialize DMAPI. We will only use it later if
957 * lp_dmapi_support is set on the share, but we need a single global
958 * session to work with.
960 dmapi_init_session();
962 if (!open_sockets_smbd(is_daemon, interactive, ports))
966 * everything after this point is run after the fork()
969 /* Initialise the password backed before the global_sam_sid
970 to ensure that we fetch from ldap before we make a domain sid up */
972 if(!initialize_password_db(False))
975 if(!get_global_sam_sid()) {
976 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
984 /* possibly reload the services file. */
985 reload_services(True);
987 if (!init_account_policy()) {
988 DEBUG(0,("Could not open account policy tdb.\n"));
993 if (sys_chroot(lp_rootdir()) == 0)
994 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1001 /* Setup change notify */
1002 if (!init_change_notify())
1005 /* Setup aio signal handler. */
1006 initialize_async_io_handler();
1008 /* re-initialise the timezone */
1011 /* register our message handlers */
1012 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1016 namecache_shutdown();
1018 exit_server_cleanly();