2 Unix SMB/Netbios 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.
22 #define PSTRING_SANCTIFY
26 extern fstring global_myworkgroup;
27 extern pstring global_myname;
31 /* the last message the was processed */
32 int last_message = -1;
34 /* a useful macro to debug the last message processed */
35 #define LAST_MESSAGE() smb_fn_name(last_message)
37 extern pstring user_socket_options;
40 extern int dcelogin_atmost_once;
43 extern fstring remote_machine;
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 void smbd_set_server_fd(int fd)
64 /****************************************************************************
65 when exiting, take the whole family
66 ****************************************************************************/
67 static void *dflt_sig(void)
69 exit_server("caught signal");
73 /****************************************************************************
74 Send a SIGTERM to our process group.
75 *****************************************************************************/
76 static void killkids(void)
78 if(am_parent) kill(0,SIGTERM);
81 /****************************************************************************
82 process a sam sync message - not sure whether to do this here or
84 ****************************************************************************/
85 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
86 void *UNUSED(buf), size_t UNUSED(len))
88 DEBUG(10, ("** sam sync message received, ignoring\n"));
91 /****************************************************************************
92 process a sam sync replicate message - not sure whether to do this here or
94 ****************************************************************************/
95 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
99 if (len != sizeof(uint32))
102 low_serial = *((uint32 *)buf);
104 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
108 /****************************************************************************
109 open the socket communication
110 ****************************************************************************/
111 static BOOL open_sockets_inetd(void)
113 /* Started from inetd. fd 0 is the socket. */
114 /* We will abort gracefully when the client or remote system
116 smbd_set_server_fd(dup(0));
118 /* close our standard file descriptors */
121 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
122 set_socket_options(smbd_server_fd(), PSTR(user_socket_options));
128 /****************************************************************************
129 open the socket communication
130 ****************************************************************************/
131 static BOOL open_sockets(BOOL is_daemon,int port)
133 int num_interfaces = iface_count();
134 int fd_listenset[FD_SETSIZE];
140 return open_sockets_inetd();
146 static int atexit_set;
147 if(atexit_set == 0) {
158 FD_ZERO(&listen_set);
160 if(lp_interfaces() && lp_bind_interfaces_only()) {
161 /* We have been given an interfaces line, and been
162 told to only bind to those interfaces. Create a
163 socket per interface and bind to only these.
166 if(num_interfaces > FD_SETSIZE) {
167 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
169 num_interfaces, FD_SETSIZE));
173 /* Now open a listen socket for each of the
175 for(i = 0; i < num_interfaces; i++) {
176 struct in_addr *ifip = iface_n_ip(i);
179 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
182 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
186 /* ready to listen */
187 set_socket_options(s,"SO_KEEPALIVE");
188 set_socket_options(s,PSTR(user_socket_options));
190 if (listen(s, 5) == -1) {
191 DEBUG(0,("listen: %s\n",strerror(errno)));
195 FD_SET(s,&listen_set);
198 /* Just bind to 0.0.0.0 - accept connections
202 /* open an incoming socket */
203 s = open_socket_in(SOCK_STREAM, port, 0,
204 interpret_addr(lp_socket_address()),True);
208 /* ready to listen */
209 set_socket_options(s,"SO_KEEPALIVE");
210 set_socket_options(s,PSTR(user_socket_options));
212 if (listen(s, 5) == -1) {
213 DEBUG(0,("open_sockets: listen: %s\n",
220 FD_SET(s,&listen_set);
223 /* Listen to messages */
225 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
226 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
228 /* now accept incoming connections - forking a new process
229 for each incoming connection */
230 DEBUG(2,("waiting for a connection\n"));
235 /* Free up temporary memory from the main smbd. */
238 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
241 memcpy((char *)&lfds, (char *)&listen_set,
244 num = sys_select(FD_SETSIZE,&lfds,NULL);
246 if (num == -1 && errno == EINTR) {
247 extern VOLATILE sig_atomic_t reload_after_sighup;
249 /* check for sighup processing */
250 if (reload_after_sighup) {
251 change_to_root_user();
252 DEBUG(1,("Reloading services after SIGHUP\n"));
253 reload_services(False);
254 reload_after_sighup = False;
260 /* check if we need to reload services */
261 check_reload(time(NULL));
263 /* Find the sockets that are read-ready -
265 for( ; num > 0; num--) {
266 struct sockaddr addr;
267 socklen_t in_addrlen = sizeof(addr);
270 for(i = 0; i < num_interfaces; i++) {
271 if(FD_ISSET(fd_listenset[i],&lfds)) {
273 /* Clear this so we don't look
275 FD_CLR(fd_listenset[i],&lfds);
280 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
282 if (smbd_server_fd() == -1 && errno == EINTR)
285 if (smbd_server_fd() == -1) {
286 DEBUG(0,("open_sockets: accept: %s\n",
291 if (smbd_server_fd() != -1 && sys_fork()==0) {
294 /* close the listening socket(s) */
295 for(i = 0; i < num_interfaces; i++)
296 close(fd_listenset[i]);
298 /* close our standard file
303 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
304 set_socket_options(smbd_server_fd(),PSTR(user_socket_options));
306 /* Reset global variables in util.c so
307 that client substitutions will be
308 done correctly in the process. */
309 reset_globals_after_fork();
311 /* tdb needs special fork handling */
316 /* The parent doesn't need this socket */
317 close(smbd_server_fd());
319 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
320 Clear the closed fd info out of server_fd --
321 and more importantly, out of client_fd in
322 util_sock.c, to avoid a possible
323 getpeername failure if we reopen the logs
324 and use %I in the filename.
327 smbd_set_server_fd(-1);
329 /* Force parent to check log size after
330 * spawning child. Fix from
331 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
332 * parent smbd will log to logserver.smb. It
333 * writes only two messages for each child
334 * started/finished. But each child writes,
335 * say, 50 messages also in logserver.smb,
336 * begining with the debug_count of the
337 * parent, before the child opens its own log
338 * file logserver.client. In a worst case
339 * scenario the size of logserver.smb would be
340 * checked after about 50*50=2500 messages
343 force_check_log_size();
348 /* NOTREACHED return True; */
351 /****************************************************************************
352 reload the services file
353 **************************************************************************/
354 BOOL reload_services(BOOL test)
360 pstrcpy(fname,lp_configfile());
361 if (file_exist(PSTR(fname), NULL) &&
362 !strcsequal(PSTR(fname), PSTR(dyn_CONFIGFILE))) {
363 pstrcpy(dyn_CONFIGFILE, PSTR(fname));
370 if (test && !lp_file_list_changed())
373 lp_killunused(conn_snum_used);
375 ret = lp_load(PSTR(dyn_CONFIGFILE), False, False, True);
379 /* perhaps the config filename is now set */
381 reload_services(True);
388 if (smbd_server_fd() != -1) {
389 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
390 set_socket_options(smbd_server_fd(), PSTR(user_socket_options));
394 reset_mangled_cache();
397 /* this forces service parameters to be flushed */
398 set_current_service(NULL,True);
405 /****************************************************************************
407 ****************************************************************************/
409 VOLATILE sig_atomic_t reload_after_sighup = False;
411 static void sig_hup(int sig)
413 BlockSignals(True,SIGHUP);
414 DEBUG(0,("Got SIGHUP\n"));
417 reload_after_sighup = True;
418 BlockSignals(False,SIGHUP);
424 /*******************************************************************
425 prepare to dump a core file - carefully!
426 ********************************************************************/
427 static BOOL dump_core(void)
432 pstrcpy(dname,lp_logfile());
433 if ((p=strrchr_m(PSTR(dname),'/'))) *p=0;
434 pstrcat(dname,"/corefiles");
435 mkdir(PSTR(dname),0700);
436 sys_chown(PSTR(dname),getuid(),getgid());
437 chmod(PSTR(dname),0700);
438 if (chdir(PSTR(dname))) return(False);
441 #ifdef HAVE_GETRLIMIT
445 getrlimit(RLIMIT_CORE, &rlp);
446 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
447 setrlimit(RLIMIT_CORE, &rlp);
448 getrlimit(RLIMIT_CORE, &rlp);
449 DEBUG(3,("Core limits now %d %d\n",
450 (int)rlp.rlim_cur,(int)rlp.rlim_max));
456 DEBUG(0,("Dumping core in %s\n", PSTR(dname)));
462 /****************************************************************************
463 update the current smbd process count
464 ****************************************************************************/
466 static void decrement_smbd_process_count(void)
470 if (lp_max_smbd_processes()) {
472 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
476 /****************************************************************************
478 ****************************************************************************/
479 void exit_server(char *reason)
481 static int firsttime=1;
482 extern char *last_inbuf;
483 extern struct auth_context *negprot_global_auth_context;
489 change_to_root_user();
490 DEBUG(2,("Closing connections\n"));
492 if (negprot_global_auth_context) {
493 (negprot_global_auth_context->free)(&negprot_global_auth_context);
498 invalidate_all_vuids();
500 /* delete our entry in the connections database. */
501 yield_connection(NULL,"");
503 respond_to_all_remaining_local_messages();
504 decrement_smbd_process_count();
507 if (dcelogin_atmost_once) {
513 int oldlevel = DEBUGLEVEL;
515 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
517 show_msg(last_inbuf);
518 DEBUGLEVEL = oldlevel;
519 DEBUG(0,("===============================================================\n"));
521 if (dump_core()) return;
527 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
531 /****************************************************************************
532 initialise connect, service and file structs
533 ****************************************************************************/
534 static void init_structs(void )
537 * Set the machine NETBIOS name if not already
538 * set from the config file.
541 if (!*PSTR(global_myname)) {
543 pstrcpy( global_myname, myhostname() );
544 p = strchr_m(PSTR(global_myname), '.' );
549 strupper(PSTR_MUTABLE(global_myname));
563 /****************************************************************************
565 ****************************************************************************/
566 static void usage(char *pname)
569 d_printf("Usage: %s [-DaioPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
570 d_printf(" [-O socket options] [-s services file]\n");
571 d_printf("\t-D Become a daemon (default)\n");
572 d_printf("\t-a Append to log file (default)\n");
573 d_printf("\t-i Run interactive (not a daemon)\n" );
574 d_printf("\t-o Overwrite log file, don't append\n");
575 d_printf("\t-h Print usage\n");
576 d_printf("\t-? Print usage\n");
577 d_printf("\t-V Print version\n");
578 d_printf("\t-b Print build options\n");
579 d_printf("\t-d debuglevel Set the debuglevel\n");
580 d_printf("\t-l log basename. Basename for log/debug files\n");
581 d_printf("\t-p port Listen on the specified port\n");
582 d_printf("\t-O socket options Socket options\n");
583 d_printf("\t-s services file. Filename of services file\n");
587 /****************************************************************************
589 ****************************************************************************/
590 int main(int argc,char *argv[])
592 extern BOOL append_log;
594 /* shall I run as a daemon */
595 BOOL is_daemon = False;
596 BOOL interactive = False;
597 BOOL specified_logfile = False;
602 #ifdef HAVE_SET_AUTH_PARAMETERS
603 set_auth_parameters(argc,argv);
606 /* this is for people who can't start the program correctly */
607 while (argc > 1 && (*argv[1] != '-')) {
612 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaiof:")) )
615 pstrcpy(user_socket_options,optarg);
619 pstrcpy(dyn_CONFIGFILE,optarg);
623 specified_logfile = True;
624 pstr_sprintf(logfile, "%s/log.smbd", optarg);
625 lp_set_logfile(PSTR(logfile));
648 DEBUGLEVEL = atoi(optarg);
662 d_printf("Version %s\n",VERSION);
666 build_options(True); /* Display output to screen as well as debug */
670 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
676 /* needed for SecureWare on SCO */
686 if(!specified_logfile) {
687 pstr_sprintf(logfile, "%s/log.smbd", PSTR(dyn_LOGFILEBASE));
688 lp_set_logfile(PSTR(logfile));
691 fstrcpy(remote_machine, "smbd");
693 setup_logging(argv[0],interactive);
695 /* we want to re-seed early to prevent time delays causing
696 client problems at a later date. (tridge) */
697 generate_random_buffer(NULL, 0, False);
699 /* make absolutely sure we run as root - to handle cases where people
700 are crazy enough to have it setuid */
702 gain_root_privilege();
703 gain_root_group_privilege();
705 fault_setup((void (*)(void *))exit_server);
706 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
708 /* we are never interested in SIGPIPE */
709 BlockSignals(True,SIGPIPE);
712 /* we are never interested in SIGFPE */
713 BlockSignals(True,SIGFPE);
717 /* We are no longer interested in USR2 */
718 BlockSignals(True,SIGUSR2);
721 /* POSIX demands that signals are inherited. If the invoking process has
722 * these signals masked, we will have problems, as we won't recieve them. */
723 BlockSignals(False, SIGHUP);
724 BlockSignals(False, SIGUSR1);
726 /* we want total control over the permissions on created files,
727 so set our umask to 0 */
734 DEBUG(1,( "smbd version %s started.\n", VERSION));
735 DEBUGADD(1,( "Copyright Andrew Tridgell 1992-2002\n"));
737 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
738 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
740 /* Output the build options to the debug log */
741 build_options(False);
743 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
744 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
749 * Do this before reload_services.
752 if (!reload_services(False))
757 /* don't call winbind for our domain if we are the DC */
758 if (lp_domain_logons()) {
759 winbind_exclude_domain(lp_workgroup());
763 if (!profile_setup(False)) {
764 DEBUG(0,("ERROR: failed to setup profiling\n"));
771 extern BOOL sslEnabled;
772 sslEnabled = lp_ssl_enabled();
776 #endif /* WITH_SSL */
778 fstrcpy(global_myworkgroup, lp_workgroup());
780 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
782 DEBUG(3,( "loaded services\n"));
784 if (!is_daemon && !is_a_socket(0)) {
785 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
789 if (is_daemon && !interactive) {
790 DEBUG( 3, ( "Becoming a daemon.\n" ) );
796 * If we're interactive we want to set our own process group for
800 setpgid( (pid_t)0, (pid_t)0);
803 if (!directory_exist(lp_lockdir(), NULL)) {
804 mkdir(lp_lockdir(), 0755);
808 pidfile_create("smbd");
811 if (!message_init()) {
814 register_msg_pool_usage();
815 register_dmalloc_msgs();
817 /* Setup the main smbd so that we can get messages. */
818 claim_connection(NULL,"",0,True);
821 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
822 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
823 smbd PROCESSES THAT NEVER DIE
824 start_background_queue();
827 if (!open_sockets(is_daemon,port))
831 * everything after this point is run after the fork()
834 if (!locking_init(0))
837 if (!print_backend_init())
840 if (!share_info_db_init())
843 if(!initialize_password_db(False))
846 /* possibly reload the services file. */
847 reload_services(True);
849 if(!pdb_generate_sam_sid()) {
850 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
854 if (!init_group_mapping()) {
855 DEBUG(0,("Could not open tdb mapping file.\n"));
859 if (!init_account_policy()) {
860 DEBUG(0,("Could not open account policy tdb.\n"));
865 if (sys_chroot(lp_rootdir()) == 0)
866 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
874 if (!init_mangle_tdb())
877 /* Setup change notify */
878 if (!init_change_notify())
883 uni_group_cache_shutdown();
884 exit_server("normal exit");