2 Unix SMB/CIFS implementation.
3 Main SMB server routines
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Martin Pool 2002
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 extern fstring global_myworkgroup;
25 extern pstring global_myname;
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 pstring user_socket_options;
38 extern int dcelogin_atmost_once;
41 /* really we should have a top level context structure that has the
42 client file descriptor as an element. That would require a major rewrite :(
44 the following 2 functions are an alternative - they make the file
45 descriptor private to smbd
47 static int server_fd = -1;
49 int smbd_server_fd(void)
54 static void smbd_set_server_fd(int fd)
60 /****************************************************************************
62 ****************************************************************************/
64 SIG_ATOMIC_T got_sig_term = 0;
66 static void sig_term(void)
72 /****************************************************************************
74 ****************************************************************************/
76 SIG_ATOMIC_T reload_after_sighup = 0;
78 static void sig_hup(int sig)
80 reload_after_sighup = 1;
84 /****************************************************************************
85 Send a SIGTERM to our process group.
86 *****************************************************************************/
88 static void killkids(void)
90 if(am_parent) kill(0,SIGTERM);
93 /****************************************************************************
94 Process a sam sync message - not sure whether to do this here or
96 ****************************************************************************/
98 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
99 void *UNUSED(buf), size_t UNUSED(len))
101 DEBUG(10, ("** sam sync message received, ignoring\n"));
104 /****************************************************************************
105 Process a sam sync replicate message - not sure whether to do this here or
107 ****************************************************************************/
109 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
113 if (len != sizeof(uint32))
116 low_serial = *((uint32 *)buf);
118 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
122 /****************************************************************************
123 Open the socket communication - inetd.
124 ****************************************************************************/
126 static BOOL open_sockets_inetd(void)
128 /* Started from inetd. fd 0 is the socket. */
129 /* We will abort gracefully when the client or remote system
131 smbd_set_server_fd(dup(0));
133 /* close our standard file descriptors */
134 close_low_fds(False); /* Don't close stderr */
136 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
137 set_socket_options(smbd_server_fd(), user_socket_options);
142 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
144 exit_server("Got a SHUTDOWN message");
148 /****************************************************************************
149 Open the socket communication.
150 ****************************************************************************/
152 static BOOL open_sockets_smbd(BOOL is_daemon,const char *smb_ports)
154 int num_interfaces = iface_count();
156 int fd_listenset[FD_SETSIZE];
163 return open_sockets_inetd();
169 static int atexit_set;
170 if(atexit_set == 0) {
180 FD_ZERO(&listen_set);
182 /* use a reasonable default set of ports - listing on 445 and 139 */
184 ports = lp_smb_ports();
185 if (!ports || !*ports) {
188 ports = strdup(ports);
190 ports = strdup(smb_ports);
193 if (lp_interfaces() && lp_bind_interfaces_only()) {
194 /* We have been given an interfaces line, and been
195 told to only bind to those interfaces. Create a
196 socket per interface and bind to only these.
199 /* Now open a listen socket for each of the
201 for(i = 0; i < num_interfaces; i++) {
202 struct in_addr *ifip = iface_n_ip(i);
207 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
211 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
212 unsigned port = atoi(tok);
213 if (port == 0) continue;
214 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
218 /* ready to listen */
219 set_socket_options(s,"SO_KEEPALIVE");
220 set_socket_options(s,user_socket_options);
222 if (listen(s, 5) == -1) {
223 DEBUG(0,("listen: %s\n",strerror(errno)));
227 FD_SET(s,&listen_set);
230 if (num_sockets >= FD_SETSIZE) {
231 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
237 /* Just bind to 0.0.0.0 - accept connections
245 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
246 unsigned port = atoi(tok);
247 if (port == 0) continue;
248 /* open an incoming socket */
249 s = open_socket_in(SOCK_STREAM, port, 0,
250 interpret_addr(lp_socket_address()),True);
254 /* ready to listen */
255 set_socket_options(s,"SO_KEEPALIVE");
256 set_socket_options(s,user_socket_options);
258 if (listen(s, 5) == -1) {
259 DEBUG(0,("open_sockets_smbd: listen: %s\n",
265 fd_listenset[num_sockets] = s;
266 FD_SET(s,&listen_set);
270 if (num_sockets >= FD_SETSIZE) {
271 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
279 /* Listen to messages */
281 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
282 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
283 message_register(MSG_SHUTDOWN, msg_exit_server);
285 /* now accept incoming connections - forking a new process
286 for each incoming connection */
287 DEBUG(2,("waiting for a connection\n"));
292 /* Free up temporary memory from the main smbd. */
295 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
298 memcpy((char *)&lfds, (char *)&listen_set,
301 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
303 if (num == -1 && errno == EINTR) {
305 exit_server("Caught TERM signal");
308 /* check for sighup processing */
309 if (reload_after_sighup) {
310 change_to_root_user();
311 DEBUG(1,("Reloading services after SIGHUP\n"));
312 reload_services(False);
313 reload_after_sighup = 0;
319 /* check if we need to reload services */
320 check_reload(time(NULL));
322 /* Find the sockets that are read-ready -
324 for( ; num > 0; num--) {
325 struct sockaddr addr;
326 socklen_t in_addrlen = sizeof(addr);
329 for(i = 0; i < num_sockets; i++) {
330 if(FD_ISSET(fd_listenset[i],&lfds)) {
332 /* Clear this so we don't look
334 FD_CLR(fd_listenset[i],&lfds);
339 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
341 if (smbd_server_fd() == -1 && errno == EINTR)
344 if (smbd_server_fd() == -1) {
345 DEBUG(0,("open_sockets_smbd: accept: %s\n",
350 if (smbd_server_fd() != -1 && sys_fork()==0) {
353 /* close the listening socket(s) */
354 for(i = 0; i < num_sockets; i++)
355 close(fd_listenset[i]);
357 /* close our standard file
359 close_low_fds(False);
362 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
363 set_socket_options(smbd_server_fd(),user_socket_options);
365 /* this is needed so that we get decent entries
366 in smbstatus for port 445 connects */
367 set_remote_machine_name(get_socket_addr(smbd_server_fd()));
369 /* Reset global variables in util.c so
370 that client substitutions will be
371 done correctly in the process. */
372 reset_globals_after_fork();
374 /* tdb needs special fork handling */
379 /* The parent doesn't need this socket */
380 close(smbd_server_fd());
382 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
383 Clear the closed fd info out of server_fd --
384 and more importantly, out of client_fd in
385 util_sock.c, to avoid a possible
386 getpeername failure if we reopen the logs
387 and use %I in the filename.
390 smbd_set_server_fd(-1);
392 /* Force parent to check log size after
393 * spawning child. Fix from
394 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
395 * parent smbd will log to logserver.smb. It
396 * writes only two messages for each child
397 * started/finished. But each child writes,
398 * say, 50 messages also in logserver.smb,
399 * begining with the debug_count of the
400 * parent, before the child opens its own log
401 * file logserver.client. In a worst case
402 * scenario the size of logserver.smb would be
403 * checked after about 50*50=2500 messages
406 force_check_log_size();
411 /* NOTREACHED return True; */
414 /****************************************************************************
415 Reload the services file.
416 **************************************************************************/
418 BOOL reload_services(BOOL test)
424 pstrcpy(fname,lp_configfile());
425 if (file_exist(fname, NULL) &&
426 !strcsequal(fname, dyn_CONFIGFILE)) {
427 pstrcpy(dyn_CONFIGFILE, fname);
434 if (test && !lp_file_list_changed())
437 lp_killunused(conn_snum_used);
439 ret = lp_load(dyn_CONFIGFILE, False, False, True);
443 /* perhaps the config filename is now set */
445 reload_services(True);
452 if (smbd_server_fd() != -1) {
453 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
454 set_socket_options(smbd_server_fd(), user_socket_options);
458 mangle_reset_cache();
461 /* this forces service parameters to be flushed */
462 set_current_service(NULL,True);
468 /*******************************************************************
469 prepare to dump a core file - carefully!
470 ********************************************************************/
471 static BOOL dump_core(void)
476 pstrcpy(dname,lp_logfile());
477 if ((p=strrchr_m(dname,'/'))) *p=0;
478 pstrcat(dname,"/corefiles");
480 sys_chown(dname,getuid(),getgid());
482 if (chdir(dname)) return(False);
485 #ifdef HAVE_GETRLIMIT
489 getrlimit(RLIMIT_CORE, &rlp);
490 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
491 setrlimit(RLIMIT_CORE, &rlp);
492 getrlimit(RLIMIT_CORE, &rlp);
493 DEBUG(3,("Core limits now %d %d\n",
494 (int)rlp.rlim_cur,(int)rlp.rlim_max));
500 DEBUG(0,("Dumping core in %s\n", dname));
506 /****************************************************************************
507 update the current smbd process count
508 ****************************************************************************/
510 static void decrement_smbd_process_count(void)
514 if (lp_max_smbd_processes()) {
516 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
520 /****************************************************************************
522 ****************************************************************************/
524 void exit_server(char *reason)
526 static int firsttime=1;
527 extern char *last_inbuf;
528 extern struct auth_context *negprot_global_auth_context;
534 change_to_root_user();
535 DEBUG(2,("Closing connections\n"));
537 if (negprot_global_auth_context) {
538 (negprot_global_auth_context->free)(&negprot_global_auth_context);
543 invalidate_all_vuids();
545 /* delete our entry in the connections database. */
546 yield_connection(NULL,"");
548 respond_to_all_remaining_local_messages();
549 decrement_smbd_process_count();
552 if (dcelogin_atmost_once) {
558 int oldlevel = DEBUGLEVEL;
560 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
562 show_msg(last_inbuf);
563 DEBUGLEVEL = oldlevel;
564 DEBUG(0,("===============================================================\n"));
566 if (dump_core()) return;
573 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
577 /****************************************************************************
578 Initialise connect, service and file structs.
579 ****************************************************************************/
581 static void init_structs(void )
584 * Set the machine NETBIOS name if not already
585 * set from the config file.
588 if (!*global_myname) {
590 pstrcpy( global_myname, myhostname() );
591 p = strchr_m(global_myname, '.' );
596 strupper(global_myname);
611 /****************************************************************************
612 Usage on the program.
613 ****************************************************************************/
615 static void usage(char *pname)
618 d_printf("Usage: %s [-DaioPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
619 d_printf(" [-O socket options] [-s services file]\n");
620 d_printf("\t-D Become a daemon (default)\n");
621 d_printf("\t-a Append to log file (default)\n");
622 d_printf("\t-i Run interactive (not a daemon)\n" );
623 d_printf("\t-o Overwrite log file, don't append\n");
624 d_printf("\t-h Print usage\n");
625 d_printf("\t-? Print usage\n");
626 d_printf("\t-V Print version\n");
627 d_printf("\t-b Print build options\n");
628 d_printf("\t-d debuglevel Set the debuglevel\n");
629 d_printf("\t-l log basename. Basename for log/debug files\n");
630 d_printf("\t-p port Listen on the specified port\n");
631 d_printf("\t-O socket options Socket options\n");
632 d_printf("\t-s services file. Filename of services file\n");
636 /****************************************************************************
638 ****************************************************************************/
640 int main(int argc,char *argv[])
642 extern BOOL append_log;
643 extern BOOL AllowDebugChange;
645 /* shall I run as a daemon */
646 BOOL is_daemon = False;
647 BOOL interactive = False;
648 BOOL specified_logfile = False;
653 #ifdef HAVE_SET_AUTH_PARAMETERS
654 set_auth_parameters(argc,argv);
657 /* this is for people who can't start the program correctly */
658 while (argc > 1 && (*argv[1] != '-')) {
663 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaiof:")) )
666 pstrcpy(user_socket_options,optarg);
670 pstrcpy(dyn_CONFIGFILE,optarg);
674 specified_logfile = True;
675 pstr_sprintf(logfile, "%s/log.smbd", optarg);
676 lp_set_logfile(logfile);
699 DEBUGLEVEL = atoi(optarg);
700 AllowDebugChange = False;
714 d_printf("Version %s\n",VERSION);
718 build_options(True); /* Display output to screen as well as debug */
722 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
728 /* needed for SecureWare on SCO */
738 if(!specified_logfile) {
739 pstr_sprintf(logfile, "%s/log.smbd", dyn_LOGFILEBASE);
740 lp_set_logfile(logfile);
743 set_remote_machine_name("smbd");
745 setup_logging(argv[0],interactive);
747 /* we want to re-seed early to prevent time delays causing
748 client problems at a later date. (tridge) */
749 generate_random_buffer(NULL, 0, False);
751 /* make absolutely sure we run as root - to handle cases where people
752 are crazy enough to have it setuid */
754 gain_root_privilege();
755 gain_root_group_privilege();
757 fault_setup((void (*)(void *))exit_server);
758 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
759 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
761 /* we are never interested in SIGPIPE */
762 BlockSignals(True,SIGPIPE);
765 /* we are never interested in SIGFPE */
766 BlockSignals(True,SIGFPE);
770 /* We are no longer interested in USR2 */
771 BlockSignals(True,SIGUSR2);
774 /* POSIX demands that signals are inherited. If the invoking process has
775 * these signals masked, we will have problems, as we won't recieve them. */
776 BlockSignals(False, SIGHUP);
777 BlockSignals(False, SIGUSR1);
778 BlockSignals(False, SIGTERM);
780 /* we want total control over the permissions on created files,
781 so set our umask to 0 */
788 DEBUG(0,( "smbd version %s started.\n", VERSION));
789 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
791 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
792 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
794 /* Output the build options to the debug log */
795 build_options(False);
797 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
798 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
803 * Do this before reload_services.
806 if (!reload_services(False))
812 if (!profile_setup(False)) {
813 DEBUG(0,("ERROR: failed to setup profiling\n"));
818 fstrcpy(global_myworkgroup, lp_workgroup());
820 DEBUG(3,( "loaded services\n"));
822 if (!is_daemon && !is_a_socket(0)) {
824 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
827 * Setting is_daemon here prevents us from eventually calling
828 * the open_sockets_inetd()
834 if (is_daemon && !interactive) {
835 DEBUG( 3, ( "Becoming a daemon.\n" ) );
841 * If we're interactive we want to set our own process group for
845 setpgid( (pid_t)0, (pid_t)0);
848 if (!directory_exist(lp_lockdir(), NULL)) {
849 mkdir(lp_lockdir(), 0755);
853 pidfile_create("smbd");
856 if (!message_init()) {
859 register_msg_pool_usage();
860 register_dmalloc_msgs();
862 /* Setup the main smbd so that we can get messages. */
863 claim_connection(NULL,"",0,True);
866 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
867 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
868 smbd PROCESSES THAT NEVER DIE
869 start_background_queue();
872 if (!open_sockets_smbd(is_daemon,ports))
876 * everything after this point is run after the fork()
881 if (!locking_init(0))
884 if (!print_backend_init())
887 if (!share_info_db_init())
890 if (!init_registry())
893 if(!initialize_password_db(False))
896 uni_group_cache_init(); /* Non-critical */
898 /* possibly reload the services file. */
899 reload_services(True);
901 if(!get_global_sam_sid()) {
902 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
906 if (!init_account_policy()) {
907 DEBUG(0,("Could not open account policy tdb.\n"));
912 if (sys_chroot(lp_rootdir()) == 0)
913 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
920 /* Setup change notify */
921 if (!init_change_notify())
924 /* re-initialise the timezone */
927 /* register our message handlers */
928 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
929 talloc_init_named("dummy!");
933 uni_group_cache_shutdown();
934 exit_server("normal exit");