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;
41 extern int dcelogin_atmost_once;
44 /* really we should have a top level context structure that has the
45 client file descriptor as an element. That would require a major rewrite :(
47 the following 2 functions are an alternative - they make the file
48 descriptor private to smbd
50 static int server_fd = -1;
52 int smbd_server_fd(void)
57 static void smbd_set_server_fd(int fd)
63 /*******************************************************************
64 What to do when smb.conf is updated.
65 ********************************************************************/
67 static void smb_conf_updated(int msg_type, struct process_id src,
68 void *buf, size_t len)
70 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was updated. Reloading.\n"));
71 reload_services(False);
75 /****************************************************************************
77 ****************************************************************************/
79 static void sig_term(void)
82 sys_select_signal(SIGTERM);
85 /****************************************************************************
87 ****************************************************************************/
89 static void sig_hup(int sig)
91 reload_after_sighup = 1;
92 sys_select_signal(SIGHUP);
95 /****************************************************************************
96 Send a SIGTERM to our process group.
97 *****************************************************************************/
99 static void killkids(void)
101 if(am_parent) kill(0,SIGTERM);
104 /****************************************************************************
105 Process a sam sync message - not sure whether to do this here or
107 ****************************************************************************/
109 static void msg_sam_sync(int UNUSED(msg_type), struct process_id UNUSED(pid),
110 void *UNUSED(buf), size_t UNUSED(len))
112 DEBUG(10, ("** sam sync message received, ignoring\n"));
115 /****************************************************************************
116 Process a sam sync replicate message - not sure whether to do this here or
118 ****************************************************************************/
120 static void msg_sam_repl(int msg_type, struct process_id pid,
121 void *buf, size_t len)
125 if (len != sizeof(uint32))
128 low_serial = *((uint32 *)buf);
130 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
134 /****************************************************************************
135 Open the socket communication - inetd.
136 ****************************************************************************/
138 static BOOL open_sockets_inetd(void)
140 /* Started from inetd. fd 0 is the socket. */
141 /* We will abort gracefully when the client or remote system
143 smbd_set_server_fd(dup(0));
145 /* close our standard file descriptors */
146 close_low_fds(False); /* Don't close stderr */
148 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
149 set_socket_options(smbd_server_fd(), user_socket_options);
154 static void msg_exit_server(int msg_type, struct process_id src,
155 void *buf, size_t len)
157 DEBUG(3, ("got a SHUTDOWN message\n"));
158 exit_server_cleanly(NULL);
162 static void msg_inject_fault(int msg_type, struct process_id src,
163 void *buf, size_t len)
167 if (len != sizeof(int)) {
169 DEBUG(0, ("Process %llu sent bogus signal injection request\n",
170 (unsigned long long)src.pid));
176 exit_server("internal error injected");
181 DEBUG(0, ("Process %llu requested injection of signal %d (%s)\n",
182 (unsigned long long)src.pid, sig, strsignal(sig)));
184 DEBUG(0, ("Process %llu requested injection of signal %d\n",
185 (unsigned long long)src.pid, sig));
188 kill(sys_getpid(), sig);
190 #endif /* DEVELOPER */
193 /****************************************************************************
194 Have we reached the process limit ?
195 ****************************************************************************/
197 static BOOL allowable_number_of_smbd_processes(void)
199 int max_processes = lp_max_smbd_processes();
205 TDB_CONTEXT *tdb = conn_tdb_ctx();
208 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
212 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
213 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
214 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
215 tdb_errorstr(tdb) ));
218 if (val > max_processes) {
219 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
220 val, max_processes ));
227 /****************************************************************************
228 Open the socket communication.
229 ****************************************************************************/
231 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
233 int num_interfaces = iface_count();
235 int fd_listenset[FD_SETSIZE];
243 return open_sockets_inetd();
249 static int atexit_set;
250 if(atexit_set == 0) {
260 FD_ZERO(&listen_set);
262 /* use a reasonable default set of ports - listing on 445 and 139 */
264 ports = lp_smb_ports();
265 if (!ports || !*ports) {
266 ports = smb_xstrdup(SMB_PORTS);
268 ports = smb_xstrdup(ports);
271 ports = smb_xstrdup(smb_ports);
274 if (lp_interfaces() && lp_bind_interfaces_only()) {
275 /* We have been given an interfaces line, and been
276 told to only bind to those interfaces. Create a
277 socket per interface and bind to only these.
280 /* Now open a listen socket for each of the
282 for(i = 0; i < num_interfaces; i++) {
283 struct in_addr *ifip = iface_n_ip(i);
288 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
292 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
293 unsigned port = atoi(tok);
297 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
301 /* ready to listen */
302 set_socket_options(s,"SO_KEEPALIVE");
303 set_socket_options(s,user_socket_options);
305 /* Set server socket to non-blocking for the accept. */
306 set_blocking(s,False);
308 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
309 DEBUG(0,("listen: %s\n",strerror(errno)));
313 FD_SET(s,&listen_set);
314 maxfd = MAX( maxfd, s);
317 if (num_sockets >= FD_SETSIZE) {
318 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
324 /* Just bind to 0.0.0.0 - accept connections
332 for (ptr=ports; next_token(&ptr, tok, " \t,", sizeof(tok)); ) {
333 unsigned port = atoi(tok);
334 if (port == 0) continue;
335 /* open an incoming socket */
336 s = open_socket_in(SOCK_STREAM, port, 0,
337 interpret_addr(lp_socket_address()),True);
341 /* ready to listen */
342 set_socket_options(s,"SO_KEEPALIVE");
343 set_socket_options(s,user_socket_options);
345 /* Set server socket to non-blocking for the accept. */
346 set_blocking(s,False);
348 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
349 DEBUG(0,("open_sockets_smbd: listen: %s\n",
355 fd_listenset[num_sockets] = s;
356 FD_SET(s,&listen_set);
357 maxfd = MAX( maxfd, s);
361 if (num_sockets >= FD_SETSIZE) {
362 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
370 /* Listen to messages */
372 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
373 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
374 message_register(MSG_SHUTDOWN, msg_exit_server);
375 message_register(MSG_SMB_FILE_RENAME, msg_file_was_renamed);
376 message_register(MSG_SMB_CONF_UPDATED, smb_conf_updated);
379 message_register(MSG_SMB_INJECT_FAULT, msg_inject_fault);
382 /* now accept incoming connections - forking a new process
383 for each incoming connection */
384 DEBUG(2,("waiting for a connection\n"));
389 /* Free up temporary memory from the main smbd. */
392 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
395 memcpy((char *)&lfds, (char *)&listen_set,
398 num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
400 if (num == -1 && errno == EINTR) {
402 exit_server_cleanly(NULL);
405 /* check for sighup processing */
406 if (reload_after_sighup) {
407 change_to_root_user();
408 DEBUG(1,("Reloading services after SIGHUP\n"));
409 reload_services(False);
410 reload_after_sighup = 0;
416 /* check if we need to reload services */
417 check_reload(time(NULL));
419 /* Find the sockets that are read-ready -
421 for( ; num > 0; num--) {
422 struct sockaddr addr;
423 socklen_t in_addrlen = sizeof(addr);
426 for(i = 0; i < num_sockets; i++) {
427 if(FD_ISSET(fd_listenset[i],&lfds)) {
429 /* Clear this so we don't look
431 FD_CLR(fd_listenset[i],&lfds);
436 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
438 if (smbd_server_fd() == -1 && errno == EINTR)
441 if (smbd_server_fd() == -1) {
442 DEBUG(0,("open_sockets_smbd: accept: %s\n",
447 /* Ensure child is set to blocking mode */
448 set_blocking(smbd_server_fd(),True);
450 if (smbd_server_fd() != -1 && interactive)
453 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
456 /* close the listening socket(s) */
457 for(i = 0; i < num_sockets; i++)
458 close(fd_listenset[i]);
460 /* close our standard file
462 close_low_fds(False);
465 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
466 set_socket_options(smbd_server_fd(),user_socket_options);
468 /* this is needed so that we get decent entries
469 in smbstatus for port 445 connects */
470 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
472 /* Reset the state of the random
473 * number generation system, so
474 * children do not get the same random
475 * numbers as each other */
477 set_need_random_reseed();
478 /* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
479 if (tdb_reopen_all(1) == -1) {
480 DEBUG(0,("tdb_reopen_all failed.\n"));
481 smb_panic("tdb_reopen_all failed.");
486 /* The parent doesn't need this socket */
487 close(smbd_server_fd());
489 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
490 Clear the closed fd info out of server_fd --
491 and more importantly, out of client_fd in
492 util_sock.c, to avoid a possible
493 getpeername failure if we reopen the logs
494 and use %I in the filename.
497 smbd_set_server_fd(-1);
499 /* Force parent to check log size after
500 * spawning child. Fix from
501 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
502 * parent smbd will log to logserver.smb. It
503 * writes only two messages for each child
504 * started/finished. But each child writes,
505 * say, 50 messages also in logserver.smb,
506 * begining with the debug_count of the
507 * parent, before the child opens its own log
508 * file logserver.client. In a worst case
509 * scenario the size of logserver.smb would be
510 * checked after about 50*50=2500 messages
513 force_check_log_size();
518 /* NOTREACHED return True; */
521 /****************************************************************************
523 **************************************************************************/
524 void reload_printers(void)
527 int n_services = lp_numservices();
528 int pnum = lp_servicenumber(PRINTERS_NAME);
533 /* remove stale printers */
534 for (snum = 0; snum < n_services; snum++) {
535 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
536 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
537 lp_autoloaded(snum)))
540 pname = lp_printername(snum);
541 if (!pcap_printername_ok(pname)) {
542 DEBUG(3, ("removing stale printer %s\n", pname));
544 if (is_printer_published(NULL, snum, NULL))
545 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
546 del_a_printer(pname);
547 lp_killservice(snum);
554 /****************************************************************************
555 Reload the services file.
556 **************************************************************************/
558 BOOL reload_services(BOOL test)
564 pstrcpy(fname,lp_configfile());
565 if (file_exist(fname, NULL) &&
566 !strcsequal(fname, dyn_CONFIGFILE)) {
567 pstrcpy(dyn_CONFIGFILE, fname);
574 if (test && !lp_file_list_changed())
577 lp_killunused(conn_snum_used);
579 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
583 /* perhaps the config filename is now set */
585 reload_services(True);
591 if (smbd_server_fd() != -1) {
592 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
593 set_socket_options(smbd_server_fd(), user_socket_options);
596 mangle_reset_cache();
599 /* this forces service parameters to be flushed */
600 set_current_service(NULL,0,True);
605 /****************************************************************************
607 ****************************************************************************/
609 /* Reasons for shutting down a server process. */
610 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
612 static void exit_server_common(enum server_exit_reason how,
613 const char *const reason) NORETURN_ATTRIBUTE;
615 static void exit_server_common(enum server_exit_reason how,
616 const char *const reason)
618 static int firsttime=1;
624 change_to_root_user();
626 if (negprot_global_auth_context) {
627 (negprot_global_auth_context->free)(&negprot_global_auth_context);
632 invalidate_all_vuids();
634 print_notify_send_messages(3); /* 3 second timeout. */
636 /* delete our entry in the connections database. */
637 yield_connection(NULL,"");
639 respond_to_all_remaining_local_messages();
640 decrement_smbd_process_count();
643 if (dcelogin_atmost_once) {
651 if (how != SERVER_EXIT_NORMAL) {
652 int oldlevel = DEBUGLEVEL;
653 char *last_inbuf = get_InBuffer();
658 DEBUG(0,("Abnormal server exit: %s\n",
659 reason ? reason : "no explanation provided"));
664 DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
665 show_msg(last_inbuf);
668 DEBUGLEVEL = oldlevel;
674 DEBUG(3,("Server exit (%s)\n",
675 (reason ? reason : "normal exit")));
681 void exit_server(const char *const explanation)
683 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
686 void exit_server_cleanly(const char *const explanation)
688 exit_server_common(SERVER_EXIT_NORMAL, explanation);
691 void exit_server_fault(void)
693 exit_server("critical server fault");
696 /****************************************************************************
697 Initialise connect, service and file structs.
698 ****************************************************************************/
700 static BOOL init_structs(void )
703 * Set the machine NETBIOS name if not already
704 * set from the config file.
724 /****************************************************************************
726 ****************************************************************************/
728 /* Declare prototype for build_options() to avoid having to run it through
729 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
730 prototype generation system is too complicated. */
732 void build_options(BOOL screen);
734 int main(int argc,const char *argv[])
736 /* shall I run as a daemon */
737 static BOOL is_daemon = False;
738 static BOOL interactive = False;
739 static BOOL Fork = True;
740 static BOOL no_process_group = False;
741 static BOOL log_stdout = False;
742 static char *ports = NULL;
746 struct poptOption long_options[] = {
748 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
749 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
750 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
751 {"no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
752 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
753 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
754 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
761 #ifdef HAVE_SET_AUTH_PARAMETERS
762 set_auth_parameters(argc,argv);
765 pc = poptGetContext("smbd", argc, argv, long_options, 0);
767 while((opt = poptGetNextOpt(pc)) != -1) {
770 build_options(True); /* Display output to screen as well as debug */
779 /* needed for SecureWare on SCO */
785 set_remote_machine_name("smbd", False);
792 if (interactive && (DEBUGLEVEL >= 9)) {
793 talloc_enable_leak_report();
796 if (log_stdout && Fork) {
797 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
801 setup_logging(argv[0],log_stdout);
803 /* we want to re-seed early to prevent time delays causing
804 client problems at a later date. (tridge) */
805 generate_random_buffer(NULL, 0);
807 /* make absolutely sure we run as root - to handle cases where people
808 are crazy enough to have it setuid */
810 gain_root_privilege();
811 gain_root_group_privilege();
813 fault_setup((void (*)(void *))exit_server_fault);
814 dump_core_setup("smbd");
816 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
817 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
819 /* we are never interested in SIGPIPE */
820 BlockSignals(True,SIGPIPE);
823 /* we are never interested in SIGFPE */
824 BlockSignals(True,SIGFPE);
828 /* We are no longer interested in USR2 */
829 BlockSignals(True,SIGUSR2);
832 /* POSIX demands that signals are inherited. If the invoking process has
833 * these signals masked, we will have problems, as we won't recieve them. */
834 BlockSignals(False, SIGHUP);
835 BlockSignals(False, SIGUSR1);
836 BlockSignals(False, SIGTERM);
838 /* we want total control over the permissions on created files,
839 so set our umask to 0 */
846 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
847 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
849 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
850 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
852 /* Output the build options to the debug log */
853 build_options(False);
855 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
856 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
861 * Do this before reload_services.
864 if (!reload_services(False))
870 if (!profile_setup(False)) {
871 DEBUG(0,("ERROR: failed to setup profiling\n"));
876 DEBUG(3,( "loaded services\n"));
878 if (!is_daemon && !is_a_socket(0)) {
880 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
883 * Setting is_daemon here prevents us from eventually calling
884 * the open_sockets_inetd()
890 if (is_daemon && !interactive) {
891 DEBUG( 3, ( "Becoming a daemon.\n" ) );
892 become_daemon(Fork, no_process_group);
897 * If we're interactive we want to set our own process group for
900 if (interactive && !no_process_group)
901 setpgid( (pid_t)0, (pid_t)0);
904 if (!directory_exist(lp_lockdir(), NULL))
905 mkdir(lp_lockdir(), 0755);
908 pidfile_create("smbd");
910 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
914 /* Initialize our global sam sid first -- quite a lot of the other
915 * initialization routines further down depend on it.
918 /* Initialise the password backed before the global_sam_sid
919 to ensure that we fetch from ldap before we make a domain sid up */
921 if(!initialize_password_db(False))
924 /* Fail gracefully if we can't open secrets.tdb */
926 if (!secrets_init()) {
927 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
931 if(!get_global_sam_sid()) {
932 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
939 if (conn_tdb_ctx() == NULL)
942 if (!locking_init(0))
947 if (!init_registry())
951 if (!init_svcctl_db())
955 if (!print_backend_init())
958 if (!init_guest_info()) {
959 DEBUG(0,("ERROR: failed to setup guest info.\n"));
963 /* Setup the main smbd so that we can get messages. */
964 /* don't worry about general printing messages here */
966 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
968 /* only start the background queue daemon if we are
969 running as a daemon -- bad things will happen if
970 smbd is launched via inetd and we fork a copy of
973 if ( is_daemon && !interactive )
974 start_background_queue();
976 /* Always attempt to initialize DMAPI. We will only use it later if
977 * lp_dmapi_support is set on the share, but we need a single global
978 * session to work with.
980 dmapi_init_session();
982 if (!open_sockets_smbd(is_daemon, interactive, ports))
986 * everything after this point is run after the fork()
993 /* possibly reload the services file. */
994 reload_services(True);
996 if (!init_account_policy()) {
997 DEBUG(0,("Could not open account policy tdb.\n"));
1001 if (*lp_rootdir()) {
1002 if (sys_chroot(lp_rootdir()) == 0)
1003 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1007 if (!init_oplocks())
1010 /* Setup change notify */
1011 if (!init_change_notify())
1014 /* Setup aio signal handler. */
1015 initialize_async_io_handler();
1017 /* re-initialise the timezone */
1020 /* register our message handlers */
1021 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1025 namecache_shutdown();
1027 exit_server_cleanly(NULL);