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.
27 static int am_parent = 1;
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 struct auth_context *negprot_global_auth_context;
36 extern pstring user_socket_options;
37 extern SIG_ATOMIC_T got_sig_term;
38 extern SIG_ATOMIC_T reload_after_sighup;
39 static SIG_ATOMIC_T got_sig_cld;
42 extern int dcelogin_atmost_once;
45 /* really we should have a top level context structure that has the
46 client file descriptor as an element. That would require a major rewrite :(
48 the following 2 functions are an alternative - they make the file
49 descriptor private to smbd
51 static int server_fd = -1;
53 int smbd_server_fd(void)
58 static void smbd_set_server_fd(int fd)
64 struct event_context *smbd_event_context(void)
66 static struct event_context *ctx;
68 if (!ctx && !(ctx = event_context_init(NULL))) {
69 smb_panic("Could not init smbd event context\n");
74 /*******************************************************************
75 What to do when smb.conf is updated.
76 ********************************************************************/
78 static void smb_conf_updated(int msg_type, struct process_id src,
79 void *buf, size_t len)
81 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was updated. Reloading.\n"));
82 reload_services(False);
86 /****************************************************************************
88 ****************************************************************************/
90 static void sig_term(void)
93 sys_select_signal(SIGTERM);
96 /****************************************************************************
98 ****************************************************************************/
100 static void sig_hup(int sig)
102 reload_after_sighup = 1;
103 sys_select_signal(SIGHUP);
106 /****************************************************************************
108 ****************************************************************************/
109 static void sig_cld(int sig)
112 sys_select_signal(SIGCLD);
115 /****************************************************************************
116 Send a SIGTERM to our process group.
117 *****************************************************************************/
119 static void killkids(void)
121 if(am_parent) kill(0,SIGTERM);
124 /****************************************************************************
125 Process a sam sync message - not sure whether to do this here or
127 ****************************************************************************/
129 static void msg_sam_sync(int UNUSED(msg_type), struct process_id UNUSED(pid),
130 void *UNUSED(buf), size_t UNUSED(len))
132 DEBUG(10, ("** sam sync message received, ignoring\n"));
135 /****************************************************************************
136 Process a sam sync replicate message - not sure whether to do this here or
138 ****************************************************************************/
140 static void msg_sam_repl(int msg_type, struct process_id pid,
141 void *buf, size_t len)
145 if (len != sizeof(uint32))
148 low_serial = *((uint32 *)buf);
150 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
154 /****************************************************************************
155 Open the socket communication - inetd.
156 ****************************************************************************/
158 static BOOL open_sockets_inetd(void)
160 /* Started from inetd. fd 0 is the socket. */
161 /* We will abort gracefully when the client or remote system
163 smbd_set_server_fd(dup(0));
165 /* close our standard file descriptors */
166 close_low_fds(False); /* Don't close stderr */
168 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
169 set_socket_options(smbd_server_fd(), user_socket_options);
174 static void msg_exit_server(int msg_type, struct process_id src,
175 void *buf, size_t len)
177 DEBUG(3, ("got a SHUTDOWN message\n"));
178 exit_server_cleanly(NULL);
182 static void msg_inject_fault(int msg_type, struct process_id src,
183 void *buf, size_t len)
187 if (len != sizeof(int)) {
189 DEBUG(0, ("Process %llu sent bogus signal injection request\n",
190 (unsigned long long)src.pid));
196 exit_server("internal error injected");
201 DEBUG(0, ("Process %llu requested injection of signal %d (%s)\n",
202 (unsigned long long)src.pid, sig, strsignal(sig)));
204 DEBUG(0, ("Process %llu requested injection of signal %d\n",
205 (unsigned long long)src.pid, sig));
208 kill(sys_getpid(), sig);
210 #endif /* DEVELOPER */
213 struct child_pid *prev, *next;
217 static struct child_pid *children;
218 static int num_children;
220 static void add_child_pid(pid_t pid)
222 struct child_pid *child;
224 if (lp_max_smbd_processes() == 0) {
225 /* Don't bother with the child list if we don't care anyway */
229 child = SMB_MALLOC_P(struct child_pid);
231 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
235 DLIST_ADD(children, child);
239 static void remove_child_pid(pid_t pid)
241 struct child_pid *child;
243 if (lp_max_smbd_processes() == 0) {
244 /* Don't bother with the child list if we don't care anyway */
248 for (child = children; child != NULL; child = child->next) {
249 if (child->pid == pid) {
250 struct child_pid *tmp = child;
251 DLIST_REMOVE(children, child);
258 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
261 /****************************************************************************
262 Have we reached the process limit ?
263 ****************************************************************************/
265 static BOOL allowable_number_of_smbd_processes(void)
267 int max_processes = lp_max_smbd_processes();
272 return num_children < max_processes;
275 /****************************************************************************
276 Open the socket communication.
277 ****************************************************************************/
279 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
281 int num_interfaces = iface_count();
283 int fd_listenset[FD_SETSIZE];
291 return open_sockets_inetd();
297 static int atexit_set;
298 if(atexit_set == 0) {
306 CatchSignal(SIGCLD, sig_cld);
308 FD_ZERO(&listen_set);
310 /* use a reasonable default set of ports - listing on 445 and 139 */
312 ports = lp_smb_ports();
313 if (!ports || !*ports) {
314 ports = smb_xstrdup(SMB_PORTS);
316 ports = smb_xstrdup(ports);
319 ports = smb_xstrdup(smb_ports);
322 if (lp_interfaces() && lp_bind_interfaces_only()) {
323 /* We have been given an interfaces line, and been
324 told to only bind to those interfaces. Create a
325 socket per interface and bind to only these.
328 /* Now open a listen socket for each of the
330 for(i = 0; i < num_interfaces; i++) {
331 struct in_addr *ifip = iface_n_ip(i);
336 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
340 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
341 unsigned port = atoi(tok);
345 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
349 /* ready to listen */
350 set_socket_options(s,"SO_KEEPALIVE");
351 set_socket_options(s,user_socket_options);
353 /* Set server socket to non-blocking for the accept. */
354 set_blocking(s,False);
356 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
357 DEBUG(0,("listen: %s\n",strerror(errno)));
361 FD_SET(s,&listen_set);
362 maxfd = MAX( maxfd, s);
365 if (num_sockets >= FD_SETSIZE) {
366 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
372 /* Just bind to 0.0.0.0 - accept connections
380 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
381 unsigned port = atoi(tok);
382 if (port == 0) continue;
383 /* open an incoming socket */
384 s = open_socket_in(SOCK_STREAM, port, 0,
385 interpret_addr(lp_socket_address()),True);
389 /* ready to listen */
390 set_socket_options(s,"SO_KEEPALIVE");
391 set_socket_options(s,user_socket_options);
393 /* Set server socket to non-blocking for the accept. */
394 set_blocking(s,False);
396 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
397 DEBUG(0,("open_sockets_smbd: listen: %s\n",
403 fd_listenset[num_sockets] = s;
404 FD_SET(s,&listen_set);
405 maxfd = MAX( maxfd, s);
409 if (num_sockets >= FD_SETSIZE) {
410 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
418 /* Listen to messages */
420 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
421 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
422 message_register(MSG_SHUTDOWN, msg_exit_server);
423 message_register(MSG_SMB_FILE_RENAME, msg_file_was_renamed);
424 message_register(MSG_SMB_CONF_UPDATED, smb_conf_updated);
427 message_register(MSG_SMB_INJECT_FAULT, msg_inject_fault);
430 /* now accept incoming connections - forking a new process
431 for each incoming connection */
432 DEBUG(2,("waiting for a connection\n"));
437 /* Free up temporary memory from the main smbd. */
440 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
447 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
448 remove_child_pid(pid);
452 memcpy((char *)&lfds, (char *)&listen_set,
455 num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
457 if (num == -1 && errno == EINTR) {
459 exit_server_cleanly(NULL);
462 /* check for sighup processing */
463 if (reload_after_sighup) {
464 change_to_root_user();
465 DEBUG(1,("Reloading services after SIGHUP\n"));
466 reload_services(False);
467 reload_after_sighup = 0;
473 /* check if we need to reload services */
474 check_reload(time(NULL));
476 /* Find the sockets that are read-ready -
478 for( ; num > 0; num--) {
479 struct sockaddr addr;
480 socklen_t in_addrlen = sizeof(addr);
484 for(i = 0; i < num_sockets; i++) {
485 if(FD_ISSET(fd_listenset[i],&lfds)) {
487 /* Clear this so we don't look
489 FD_CLR(fd_listenset[i],&lfds);
494 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
496 if (smbd_server_fd() == -1 && errno == EINTR)
499 if (smbd_server_fd() == -1) {
500 DEBUG(0,("open_sockets_smbd: accept: %s\n",
505 /* Ensure child is set to blocking mode */
506 set_blocking(smbd_server_fd(),True);
508 if (smbd_server_fd() != -1 && interactive)
511 if (allowable_number_of_smbd_processes() &&
512 smbd_server_fd() != -1 &&
513 ((child = sys_fork())==0)) {
516 /* Stop zombies, the parent explicitly handles
517 * them, counting worker smbds. */
520 /* close the listening socket(s) */
521 for(i = 0; i < num_sockets; i++)
522 close(fd_listenset[i]);
524 /* close our standard file
526 close_low_fds(False);
529 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
530 set_socket_options(smbd_server_fd(),user_socket_options);
532 /* this is needed so that we get decent entries
533 in smbstatus for port 445 connects */
534 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
537 /* Reset the state of the random
538 * number generation system, so
539 * children do not get the same random
540 * numbers as each other */
542 set_need_random_reseed();
543 /* tdb needs special fork handling - remove
544 * CLEAR_IF_FIRST flags */
545 if (tdb_reopen_all(1) == -1) {
546 DEBUG(0,("tdb_reopen_all failed.\n"));
547 smb_panic("tdb_reopen_all failed.");
552 /* The parent doesn't need this socket */
553 close(smbd_server_fd());
555 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
556 Clear the closed fd info out of server_fd --
557 and more importantly, out of client_fd in
558 util_sock.c, to avoid a possible
559 getpeername failure if we reopen the logs
560 and use %I in the filename.
563 smbd_set_server_fd(-1);
566 add_child_pid(child);
569 /* Force parent to check log size after
570 * spawning child. Fix from
571 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
572 * parent smbd will log to logserver.smb. It
573 * writes only two messages for each child
574 * started/finished. But each child writes,
575 * say, 50 messages also in logserver.smb,
576 * begining with the debug_count of the
577 * parent, before the child opens its own log
578 * file logserver.client. In a worst case
579 * scenario the size of logserver.smb would be
580 * checked after about 50*50=2500 messages
583 force_check_log_size();
588 /* NOTREACHED return True; */
591 /****************************************************************************
593 **************************************************************************/
594 void reload_printers(void)
597 int n_services = lp_numservices();
598 int pnum = lp_servicenumber(PRINTERS_NAME);
603 /* remove stale printers */
604 for (snum = 0; snum < n_services; snum++) {
605 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
606 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
607 lp_autoloaded(snum)))
610 pname = lp_printername(snum);
611 if (!pcap_printername_ok(pname)) {
612 DEBUG(3, ("removing stale printer %s\n", pname));
614 if (is_printer_published(NULL, snum, NULL))
615 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
616 del_a_printer(pname);
617 lp_killservice(snum);
624 /****************************************************************************
625 Reload the services file.
626 **************************************************************************/
628 BOOL reload_services(BOOL test)
634 pstrcpy(fname,lp_configfile());
635 if (file_exist(fname, NULL) &&
636 !strcsequal(fname, dyn_CONFIGFILE)) {
637 pstrcpy(dyn_CONFIGFILE, fname);
644 if (test && !lp_file_list_changed())
647 lp_killunused(conn_snum_used);
649 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
653 /* perhaps the config filename is now set */
655 reload_services(True);
661 if (smbd_server_fd() != -1) {
662 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
663 set_socket_options(smbd_server_fd(), user_socket_options);
666 mangle_reset_cache();
669 /* this forces service parameters to be flushed */
670 set_current_service(NULL,0,True);
675 /****************************************************************************
677 ****************************************************************************/
679 /* Reasons for shutting down a server process. */
680 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
682 static void exit_server_common(enum server_exit_reason how,
683 const char *const reason) NORETURN_ATTRIBUTE;
685 static void exit_server_common(enum server_exit_reason how,
686 const char *const reason)
688 static int firsttime=1;
694 change_to_root_user();
696 if (negprot_global_auth_context) {
697 (negprot_global_auth_context->free)(&negprot_global_auth_context);
702 invalidate_all_vuids();
704 print_notify_send_messages(3); /* 3 second timeout. */
706 /* delete our entry in the connections database. */
707 yield_connection(NULL,"");
709 respond_to_all_remaining_local_messages();
712 if (dcelogin_atmost_once) {
720 if (how != SERVER_EXIT_NORMAL) {
721 int oldlevel = DEBUGLEVEL;
722 char *last_inbuf = get_InBuffer();
727 DEBUG(0,("Abnormal server exit: %s\n",
728 reason ? reason : "no explanation provided"));
733 DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
734 show_msg(last_inbuf);
737 DEBUGLEVEL = oldlevel;
741 DEBUG(3,("Server exit (%s)\n",
742 (reason ? reason : "normal exit")));
748 void exit_server(const char *const explanation)
750 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
753 void exit_server_cleanly(const char *const explanation)
755 exit_server_common(SERVER_EXIT_NORMAL, explanation);
758 void exit_server_fault(void)
760 exit_server("critical server fault");
763 /****************************************************************************
764 Initialise connect, service and file structs.
765 ****************************************************************************/
767 static BOOL init_structs(void )
770 * Set the machine NETBIOS name if not already
771 * set from the config file.
791 /****************************************************************************
793 ****************************************************************************/
795 /* Declare prototype for build_options() to avoid having to run it through
796 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
797 prototype generation system is too complicated. */
799 extern void build_options(BOOL screen);
801 int main(int argc,const char *argv[])
803 /* shall I run as a daemon */
804 static BOOL is_daemon = False;
805 static BOOL interactive = False;
806 static BOOL Fork = True;
807 static BOOL no_process_group = False;
808 static BOOL log_stdout = False;
809 static char *ports = NULL;
813 struct poptOption long_options[] = {
815 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
816 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
817 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools, etc.)" },
818 {"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
819 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
820 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
821 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
823 POPT_COMMON_DYNCONFIG
829 #ifdef HAVE_SET_AUTH_PARAMETERS
830 set_auth_parameters(argc,argv);
833 pc = poptGetContext("smbd", argc, argv, long_options, 0);
835 while((opt = poptGetNextOpt(pc)) != -1) {
838 build_options(True); /* Display output to screen as well as debug */
847 /* needed for SecureWare on SCO */
853 set_remote_machine_name("smbd", False);
860 if (interactive && (DEBUGLEVEL >= 9)) {
861 talloc_enable_leak_report();
864 if (log_stdout && Fork) {
865 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
869 setup_logging(argv[0],log_stdout);
871 /* we want to re-seed early to prevent time delays causing
872 client problems at a later date. (tridge) */
873 generate_random_buffer(NULL, 0);
875 /* make absolutely sure we run as root - to handle cases where people
876 are crazy enough to have it setuid */
878 gain_root_privilege();
879 gain_root_group_privilege();
881 fault_setup((void (*)(void *))exit_server_fault);
882 dump_core_setup("smbd");
884 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
885 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
887 /* we are never interested in SIGPIPE */
888 BlockSignals(True,SIGPIPE);
891 /* we are never interested in SIGFPE */
892 BlockSignals(True,SIGFPE);
896 /* We are no longer interested in USR2 */
897 BlockSignals(True,SIGUSR2);
900 /* POSIX demands that signals are inherited. If the invoking process has
901 * these signals masked, we will have problems, as we won't recieve them. */
902 BlockSignals(False, SIGHUP);
903 BlockSignals(False, SIGUSR1);
904 BlockSignals(False, SIGTERM);
906 /* we want total control over the permissions on created files,
907 so set our umask to 0 */
914 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
915 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
917 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
918 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
920 /* Output the build options to the debug log */
921 build_options(False);
923 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
924 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
929 * Do this before reload_services.
932 if (!reload_services(False))
938 if (!profile_setup(False)) {
939 DEBUG(0,("ERROR: failed to setup profiling\n"));
944 DEBUG(3,( "loaded services\n"));
946 if (!is_daemon && !is_a_socket(0)) {
948 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
951 * Setting is_daemon here prevents us from eventually calling
952 * the open_sockets_inetd()
958 if (is_daemon && !interactive) {
959 DEBUG( 3, ( "Becoming a daemon.\n" ) );
960 become_daemon(Fork, no_process_group);
965 * If we're interactive we want to set our own process group for
968 if (interactive && !no_process_group)
969 setpgid( (pid_t)0, (pid_t)0);
972 if (!directory_exist(lp_lockdir(), NULL))
973 mkdir(lp_lockdir(), 0755);
976 pidfile_create("smbd");
978 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
982 /* Initialise the password backed before the global_sam_sid
983 to ensure that we fetch from ldap before we make a domain sid up */
985 if(!initialize_password_db(False))
988 if (!secrets_init()) {
989 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
993 if(!get_global_sam_sid()) {
994 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1001 if (conn_tdb_ctx() == NULL)
1004 if (!locking_init(0))
1009 if (!init_registry())
1013 if (!init_svcctl_db())
1017 if (!print_backend_init())
1020 if (!init_guest_info()) {
1021 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1025 /* Setup the main smbd so that we can get messages. */
1026 /* don't worry about general printing messages here */
1028 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
1030 /* only start the background queue daemon if we are
1031 running as a daemon -- bad things will happen if
1032 smbd is launched via inetd and we fork a copy of
1035 if ( is_daemon && !interactive )
1036 start_background_queue();
1038 /* Always attempt to initialize DMAPI. We will only use it later if
1039 * lp_dmapi_support is set on the share, but we need a single global
1040 * session to work with.
1042 dmapi_init_session();
1044 if (!open_sockets_smbd(is_daemon, interactive, ports))
1048 * everything after this point is run after the fork()
1055 /* possibly reload the services file. */
1056 reload_services(True);
1058 if (!init_account_policy()) {
1059 DEBUG(0,("Could not open account policy tdb.\n"));
1063 if (*lp_rootdir()) {
1064 if (sys_chroot(lp_rootdir()) == 0)
1065 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1069 if (!init_oplocks())
1072 /* Setup change notify */
1073 if (!init_change_notify())
1076 /* Setup aio signal handler. */
1077 initialize_async_io_handler();
1079 /* re-initialise the timezone */
1082 /* register our message handlers */
1083 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1087 namecache_shutdown();
1089 exit_server_cleanly(NULL);