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() &&
454 smbd_server_fd() != -1 && sys_fork()==0) {
457 /* close the listening socket(s) */
458 for(i = 0; i < num_sockets; i++)
459 close(fd_listenset[i]);
461 /* close our standard file
463 close_low_fds(False);
466 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
467 set_socket_options(smbd_server_fd(),user_socket_options);
469 /* this is needed so that we get decent entries
470 in smbstatus for port 445 connects */
471 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
474 /* Reset the state of the random
475 * number generation system, so
476 * children do not get the same random
477 * numbers as each other */
479 set_need_random_reseed();
480 /* tdb needs special fork handling - remove
481 * CLEAR_IF_FIRST flags */
482 if (tdb_reopen_all(1) == -1) {
483 DEBUG(0,("tdb_reopen_all failed.\n"));
484 smb_panic("tdb_reopen_all failed.");
489 /* The parent doesn't need this socket */
490 close(smbd_server_fd());
492 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
493 Clear the closed fd info out of server_fd --
494 and more importantly, out of client_fd in
495 util_sock.c, to avoid a possible
496 getpeername failure if we reopen the logs
497 and use %I in the filename.
500 smbd_set_server_fd(-1);
502 /* Force parent to check log size after
503 * spawning child. Fix from
504 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
505 * parent smbd will log to logserver.smb. It
506 * writes only two messages for each child
507 * started/finished. But each child writes,
508 * say, 50 messages also in logserver.smb,
509 * begining with the debug_count of the
510 * parent, before the child opens its own log
511 * file logserver.client. In a worst case
512 * scenario the size of logserver.smb would be
513 * checked after about 50*50=2500 messages
516 force_check_log_size();
521 /* NOTREACHED return True; */
524 /****************************************************************************
526 **************************************************************************/
527 void reload_printers(void)
530 int n_services = lp_numservices();
531 int pnum = lp_servicenumber(PRINTERS_NAME);
536 /* remove stale printers */
537 for (snum = 0; snum < n_services; snum++) {
538 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
539 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
540 lp_autoloaded(snum)))
543 pname = lp_printername(snum);
544 if (!pcap_printername_ok(pname)) {
545 DEBUG(3, ("removing stale printer %s\n", pname));
547 if (is_printer_published(NULL, snum, NULL))
548 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
549 del_a_printer(pname);
550 lp_killservice(snum);
557 /****************************************************************************
558 Reload the services file.
559 **************************************************************************/
561 BOOL reload_services(BOOL test)
567 pstrcpy(fname,lp_configfile());
568 if (file_exist(fname, NULL) &&
569 !strcsequal(fname, dyn_CONFIGFILE)) {
570 pstrcpy(dyn_CONFIGFILE, fname);
577 if (test && !lp_file_list_changed())
580 lp_killunused(conn_snum_used);
582 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
586 /* perhaps the config filename is now set */
588 reload_services(True);
594 if (smbd_server_fd() != -1) {
595 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
596 set_socket_options(smbd_server_fd(), user_socket_options);
599 mangle_reset_cache();
602 /* this forces service parameters to be flushed */
603 set_current_service(NULL,0,True);
608 /****************************************************************************
610 ****************************************************************************/
612 /* Reasons for shutting down a server process. */
613 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
615 static void exit_server_common(enum server_exit_reason how,
616 const char *const reason) NORETURN_ATTRIBUTE;
618 static void exit_server_common(enum server_exit_reason how,
619 const char *const reason)
621 static int firsttime=1;
627 change_to_root_user();
629 if (negprot_global_auth_context) {
630 (negprot_global_auth_context->free)(&negprot_global_auth_context);
635 invalidate_all_vuids();
637 print_notify_send_messages(3); /* 3 second timeout. */
639 /* delete our entry in the connections database. */
640 yield_connection(NULL,"");
642 respond_to_all_remaining_local_messages();
643 decrement_smbd_process_count();
646 if (dcelogin_atmost_once) {
654 if (how != SERVER_EXIT_NORMAL) {
655 int oldlevel = DEBUGLEVEL;
656 char *last_inbuf = get_InBuffer();
661 DEBUG(0,("Abnormal server exit: %s\n",
662 reason ? reason : "no explanation provided"));
667 DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
668 show_msg(last_inbuf);
671 DEBUGLEVEL = oldlevel;
677 DEBUG(3,("Server exit (%s)\n",
678 (reason ? reason : "normal exit")));
684 void exit_server(const char *const explanation)
686 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
689 void exit_server_cleanly(const char *const explanation)
691 exit_server_common(SERVER_EXIT_NORMAL, explanation);
694 void exit_server_fault(void)
696 exit_server("critical server fault");
699 /****************************************************************************
700 Initialise connect, service and file structs.
701 ****************************************************************************/
703 static BOOL init_structs(void )
706 * Set the machine NETBIOS name if not already
707 * set from the config file.
727 /****************************************************************************
729 ****************************************************************************/
731 /* Declare prototype for build_options() to avoid having to run it through
732 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
733 prototype generation system is too complicated. */
735 void build_options(BOOL screen);
737 int main(int argc,const char *argv[])
739 /* shall I run as a daemon */
740 static BOOL is_daemon = False;
741 static BOOL interactive = False;
742 static BOOL Fork = True;
743 static BOOL no_process_group = False;
744 static BOOL log_stdout = False;
745 static char *ports = NULL;
749 struct poptOption long_options[] = {
751 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
752 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
753 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools, etc.)" },
754 {"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
755 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
756 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
757 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
759 POPT_COMMON_DYNCONFIG
765 #ifdef HAVE_SET_AUTH_PARAMETERS
766 set_auth_parameters(argc,argv);
769 pc = poptGetContext("smbd", argc, argv, long_options, 0);
771 while((opt = poptGetNextOpt(pc)) != -1) {
774 build_options(True); /* Display output to screen as well as debug */
783 /* needed for SecureWare on SCO */
789 set_remote_machine_name("smbd", False);
796 if (interactive && (DEBUGLEVEL >= 9)) {
797 talloc_enable_leak_report();
800 if (log_stdout && Fork) {
801 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
805 setup_logging(argv[0],log_stdout);
807 /* we want to re-seed early to prevent time delays causing
808 client problems at a later date. (tridge) */
809 generate_random_buffer(NULL, 0);
811 /* make absolutely sure we run as root - to handle cases where people
812 are crazy enough to have it setuid */
814 gain_root_privilege();
815 gain_root_group_privilege();
817 fault_setup((void (*)(void *))exit_server_fault);
818 dump_core_setup("smbd");
820 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
821 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
823 /* we are never interested in SIGPIPE */
824 BlockSignals(True,SIGPIPE);
827 /* we are never interested in SIGFPE */
828 BlockSignals(True,SIGFPE);
832 /* We are no longer interested in USR2 */
833 BlockSignals(True,SIGUSR2);
836 /* POSIX demands that signals are inherited. If the invoking process has
837 * these signals masked, we will have problems, as we won't recieve them. */
838 BlockSignals(False, SIGHUP);
839 BlockSignals(False, SIGUSR1);
840 BlockSignals(False, SIGTERM);
842 /* we want total control over the permissions on created files,
843 so set our umask to 0 */
850 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
851 DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
853 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
854 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
856 /* Output the build options to the debug log */
857 build_options(False);
859 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
860 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
865 * Do this before reload_services.
868 if (!reload_services(False))
874 if (!profile_setup(False)) {
875 DEBUG(0,("ERROR: failed to setup profiling\n"));
880 DEBUG(3,( "loaded services\n"));
882 if (!is_daemon && !is_a_socket(0)) {
884 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
887 * Setting is_daemon here prevents us from eventually calling
888 * the open_sockets_inetd()
894 if (is_daemon && !interactive) {
895 DEBUG( 3, ( "Becoming a daemon.\n" ) );
896 become_daemon(Fork, no_process_group);
901 * If we're interactive we want to set our own process group for
904 if (interactive && !no_process_group)
905 setpgid( (pid_t)0, (pid_t)0);
908 if (!directory_exist(lp_lockdir(), NULL))
909 mkdir(lp_lockdir(), 0755);
912 pidfile_create("smbd");
914 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
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 if (!secrets_init()) {
925 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
929 if(!get_global_sam_sid()) {
930 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
937 if (conn_tdb_ctx() == NULL)
940 if (!locking_init(0))
945 if (!init_registry())
949 if (!init_svcctl_db())
953 if (!print_backend_init())
956 if (!init_guest_info()) {
957 DEBUG(0,("ERROR: failed to setup guest info.\n"));
961 /* Setup the main smbd so that we can get messages. */
962 /* don't worry about general printing messages here */
964 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
966 /* only start the background queue daemon if we are
967 running as a daemon -- bad things will happen if
968 smbd is launched via inetd and we fork a copy of
971 if ( is_daemon && !interactive )
972 start_background_queue();
974 /* Always attempt to initialize DMAPI. We will only use it later if
975 * lp_dmapi_support is set on the share, but we need a single global
976 * session to work with.
978 dmapi_init_session();
980 if (!open_sockets_smbd(is_daemon, interactive, ports))
984 * everything after this point is run after the fork()
991 /* possibly reload the services file. */
992 reload_services(True);
994 if (!init_account_policy()) {
995 DEBUG(0,("Could not open account policy tdb.\n"));
1000 if (sys_chroot(lp_rootdir()) == 0)
1001 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1005 if (!init_oplocks())
1008 /* Setup change notify */
1009 if (!init_change_notify())
1012 /* Setup aio signal handler. */
1013 initialize_async_io_handler();
1015 /* re-initialise the timezone */
1018 /* register our message handlers */
1019 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
1023 namecache_shutdown();
1025 exit_server_cleanly(NULL);