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
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.
25 extern fstring global_myworkgroup
;
26 extern pstring global_myname
;
30 /* the last message the was processed */
31 int last_message
= -1;
33 /* a useful macro to debug the last message processed */
34 #define LAST_MESSAGE() smb_fn_name(last_message)
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 /****************************************************************************
65 ****************************************************************************/
67 static void sig_term(void)
73 /****************************************************************************
75 ****************************************************************************/
77 static void sig_hup(int sig
)
79 reload_after_sighup
= 1;
83 /****************************************************************************
84 Send a SIGTERM to our process group.
85 *****************************************************************************/
87 static void killkids(void)
89 if(am_parent
) kill(0,SIGTERM
);
92 /****************************************************************************
93 Process a sam sync message - not sure whether to do this here or
95 ****************************************************************************/
97 static void msg_sam_sync(int UNUSED(msg_type
), pid_t
UNUSED(pid
),
98 void *UNUSED(buf
), size_t UNUSED(len
))
100 DEBUG(10, ("** sam sync message received, ignoring\n"));
103 /****************************************************************************
104 Process a sam sync replicate message - not sure whether to do this here or
106 ****************************************************************************/
108 static void msg_sam_repl(int msg_type
, pid_t pid
, void *buf
, size_t len
)
112 if (len
!= sizeof(uint32
))
115 low_serial
= *((uint32
*)buf
);
117 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
121 /****************************************************************************
122 Open the socket communication - inetd.
123 ****************************************************************************/
125 static BOOL
open_sockets_inetd(void)
127 /* Started from inetd. fd 0 is the socket. */
128 /* We will abort gracefully when the client or remote system
130 smbd_set_server_fd(dup(0));
132 /* close our standard file descriptors */
133 close_low_fds(False
); /* Don't close stderr */
135 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
136 set_socket_options(smbd_server_fd(), user_socket_options
);
141 static void msg_exit_server(int msg_type
, pid_t src
, void *buf
, size_t len
)
143 exit_server("Got a SHUTDOWN message");
147 /****************************************************************************
148 Open the socket communication.
149 ****************************************************************************/
151 static BOOL
open_sockets_smbd(BOOL is_daemon
,const char *smb_ports
)
153 int num_interfaces
= iface_count();
155 int fd_listenset
[FD_SETSIZE
];
162 return open_sockets_inetd();
168 static int atexit_set
;
169 if(atexit_set
== 0) {
179 FD_ZERO(&listen_set
);
181 /* use a reasonable default set of ports - listing on 445 and 139 */
183 ports
= lp_smb_ports();
184 if (!ports
|| !*ports
) {
187 ports
= strdup(ports
);
189 ports
= strdup(smb_ports
);
192 if (lp_interfaces() && lp_bind_interfaces_only()) {
193 /* We have been given an interfaces line, and been
194 told to only bind to those interfaces. Create a
195 socket per interface and bind to only these.
198 /* Now open a listen socket for each of the
200 for(i
= 0; i
< num_interfaces
; i
++) {
201 struct in_addr
*ifip
= iface_n_ip(i
);
206 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i
));
210 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
211 unsigned port
= atoi(tok
);
212 if (port
== 0) continue;
213 s
= fd_listenset
[num_sockets
] = open_socket_in(SOCK_STREAM
, port
, 0, ifip
->s_addr
, True
);
217 /* ready to listen */
218 set_socket_options(s
,"SO_KEEPALIVE");
219 set_socket_options(s
,user_socket_options
);
221 if (listen(s
, 5) == -1) {
222 DEBUG(0,("listen: %s\n",strerror(errno
)));
226 FD_SET(s
,&listen_set
);
229 if (num_sockets
>= FD_SETSIZE
) {
230 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
236 /* Just bind to 0.0.0.0 - accept connections
244 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
245 unsigned port
= atoi(tok
);
246 if (port
== 0) continue;
247 /* open an incoming socket */
248 s
= open_socket_in(SOCK_STREAM
, port
, 0,
249 interpret_addr(lp_socket_address()),True
);
253 /* ready to listen */
254 set_socket_options(s
,"SO_KEEPALIVE");
255 set_socket_options(s
,user_socket_options
);
257 if (listen(s
, 5) == -1) {
258 DEBUG(0,("open_sockets_smbd: listen: %s\n",
264 fd_listenset
[num_sockets
] = s
;
265 FD_SET(s
,&listen_set
);
269 if (num_sockets
>= FD_SETSIZE
) {
270 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
278 /* Listen to messages */
280 message_register(MSG_SMB_SAM_SYNC
, msg_sam_sync
);
281 message_register(MSG_SMB_SAM_REPL
, msg_sam_repl
);
282 message_register(MSG_SHUTDOWN
, msg_exit_server
);
284 /* now accept incoming connections - forking a new process
285 for each incoming connection */
286 DEBUG(2,("waiting for a connection\n"));
291 /* Free up temporary memory from the main smbd. */
294 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
297 memcpy((char *)&lfds
, (char *)&listen_set
,
300 num
= sys_select(FD_SETSIZE
,&lfds
,NULL
,NULL
,NULL
);
302 if (num
== -1 && errno
== EINTR
) {
304 exit_server("Caught TERM signal");
307 /* check for sighup processing */
308 if (reload_after_sighup
) {
309 change_to_root_user();
310 DEBUG(1,("Reloading services after SIGHUP\n"));
311 reload_services(False
);
312 reload_after_sighup
= 0;
318 /* check if we need to reload services */
319 check_reload(time(NULL
));
321 /* Find the sockets that are read-ready -
323 for( ; num
> 0; num
--) {
324 struct sockaddr addr
;
325 socklen_t in_addrlen
= sizeof(addr
);
328 for(i
= 0; i
< num_sockets
; i
++) {
329 if(FD_ISSET(fd_listenset
[i
],&lfds
)) {
331 /* Clear this so we don't look
333 FD_CLR(fd_listenset
[i
],&lfds
);
338 smbd_set_server_fd(accept(s
,&addr
,&in_addrlen
));
340 if (smbd_server_fd() == -1 && errno
== EINTR
)
343 if (smbd_server_fd() == -1) {
344 DEBUG(0,("open_sockets_smbd: accept: %s\n",
349 if (smbd_server_fd() != -1 && sys_fork()==0) {
352 /* close the listening socket(s) */
353 for(i
= 0; i
< num_sockets
; i
++)
354 close(fd_listenset
[i
]);
356 /* close our standard file
358 close_low_fds(False
);
361 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
362 set_socket_options(smbd_server_fd(),user_socket_options
);
364 /* this is needed so that we get decent entries
365 in smbstatus for port 445 connects */
366 set_remote_machine_name(get_socket_addr(smbd_server_fd()));
368 /* Reset global variables in util.c so
369 that client substitutions will be
370 done correctly in the process. */
371 reset_globals_after_fork();
373 /* tdb needs special fork handling */
374 if (tdb_reopen_all() == -1) {
375 DEBUG(0,("tdb_reopen_all failed.\n"));
381 /* The parent doesn't need this socket */
382 close(smbd_server_fd());
384 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
385 Clear the closed fd info out of server_fd --
386 and more importantly, out of client_fd in
387 util_sock.c, to avoid a possible
388 getpeername failure if we reopen the logs
389 and use %I in the filename.
392 smbd_set_server_fd(-1);
394 /* Force parent to check log size after
395 * spawning child. Fix from
396 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
397 * parent smbd will log to logserver.smb. It
398 * writes only two messages for each child
399 * started/finished. But each child writes,
400 * say, 50 messages also in logserver.smb,
401 * begining with the debug_count of the
402 * parent, before the child opens its own log
403 * file logserver.client. In a worst case
404 * scenario the size of logserver.smb would be
405 * checked after about 50*50=2500 messages
408 force_check_log_size();
413 /* NOTREACHED return True; */
416 /****************************************************************************
417 Reload the services file.
418 **************************************************************************/
420 BOOL
reload_services(BOOL test
)
426 pstrcpy(fname
,lp_configfile());
427 if (file_exist(fname
, NULL
) &&
428 !strcsequal(fname
, dyn_CONFIGFILE
)) {
429 pstrcpy(dyn_CONFIGFILE
, fname
);
436 if (test
&& !lp_file_list_changed())
439 lp_killunused(conn_snum_used
);
441 ret
= lp_load(dyn_CONFIGFILE
, False
, False
, True
);
445 /* perhaps the config filename is now set */
447 reload_services(True
);
454 if (smbd_server_fd() != -1) {
455 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
456 set_socket_options(smbd_server_fd(), user_socket_options
);
460 mangle_reset_cache();
463 /* this forces service parameters to be flushed */
464 set_current_service(NULL
,True
);
470 /*******************************************************************
471 prepare to dump a core file - carefully!
472 ********************************************************************/
473 static BOOL
dump_core(void)
478 pstrcpy(dname
,lp_logfile());
479 if ((p
=strrchr_m(dname
,'/'))) *p
=0;
480 pstrcat(dname
,"/corefiles");
482 sys_chown(dname
,getuid(),getgid());
484 if (chdir(dname
)) return(False
);
487 #ifdef HAVE_GETRLIMIT
491 getrlimit(RLIMIT_CORE
, &rlp
);
492 rlp
.rlim_cur
= MAX(4*1024*1024,rlp
.rlim_cur
);
493 setrlimit(RLIMIT_CORE
, &rlp
);
494 getrlimit(RLIMIT_CORE
, &rlp
);
495 DEBUG(3,("Core limits now %d %d\n",
496 (int)rlp
.rlim_cur
,(int)rlp
.rlim_max
));
502 DEBUG(0,("Dumping core in %s\n", dname
));
508 /****************************************************************************
509 update the current smbd process count
510 ****************************************************************************/
512 static void decrement_smbd_process_count(void)
516 if (lp_max_smbd_processes()) {
518 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds
, -1);
522 /****************************************************************************
524 ****************************************************************************/
526 void exit_server(char *reason
)
528 static int firsttime
=1;
529 extern char *last_inbuf
;
530 extern struct auth_context
*negprot_global_auth_context
;
536 change_to_root_user();
537 DEBUG(2,("Closing connections\n"));
539 if (negprot_global_auth_context
) {
540 (negprot_global_auth_context
->free
)(&negprot_global_auth_context
);
545 invalidate_all_vuids();
547 print_notify_send_messages();
549 /* delete our entry in the connections database. */
550 yield_connection(NULL
,"");
552 respond_to_all_remaining_local_messages();
553 decrement_smbd_process_count();
556 if (dcelogin_atmost_once
) {
562 int oldlevel
= DEBUGLEVEL
;
564 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message
)));
566 show_msg(last_inbuf
);
567 DEBUGLEVEL
= oldlevel
;
568 DEBUG(0,("===============================================================\n"));
570 if (dump_core()) return;
577 DEBUG(3,("Server exit (%s)\n", (reason
? reason
: "")));
581 /****************************************************************************
582 Initialise connect, service and file structs.
583 ****************************************************************************/
585 static void init_structs(void )
588 * Set the machine NETBIOS name if not already
589 * set from the config file.
592 if (!*global_myname
) {
594 pstrcpy( global_myname
, myhostname() );
595 p
= strchr_m(global_myname
, '.' );
600 strupper(global_myname
);
615 /****************************************************************************
617 ****************************************************************************/
619 int main(int argc
,const char *argv
[])
621 /* shall I run as a daemon */
622 static BOOL is_daemon
= False
;
623 static BOOL interactive
= False
;
624 static char *ports
= NULL
;
628 struct poptOption long_options
[] = {
630 {"daemon", 'D', POPT_ARG_VAL
, &is_daemon
, True
, "Become a daemon (default)" },
631 {"interactive", 'i', POPT_ARG_VAL
, &interactive
, True
, "Run interactive (not a daemon)"},
632 {"build-options", 'b', POPT_ARG_NONE
, NULL
, 'b', "Print build options" },
633 {"port", 'p', POPT_ARG_STRING
, &ports
, 0, "Listen on the specified ports"},
634 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_debug
},
635 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_configfile
},
636 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_socket_options
},
637 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_log_base
},
638 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_version
},
642 #ifdef HAVE_SET_AUTH_PARAMETERS
643 set_auth_parameters(argc
,argv
);
646 pc
= poptGetContext("smbd", argc
, argv
, long_options
, 0);
648 while((opt
= poptGetNextOpt(pc
)) != -1) {
651 build_options(True
); /* Display output to screen as well as debug */
660 /* needed for SecureWare on SCO */
668 set_remote_machine_name("smbd");
670 setup_logging(argv
[0],interactive
);
672 /* we want to re-seed early to prevent time delays causing
673 client problems at a later date. (tridge) */
674 generate_random_buffer(NULL
, 0, False
);
676 /* make absolutely sure we run as root - to handle cases where people
677 are crazy enough to have it setuid */
679 gain_root_privilege();
680 gain_root_group_privilege();
682 fault_setup((void (*)(void *))exit_server
);
683 CatchSignal(SIGTERM
, SIGNAL_CAST sig_term
);
684 CatchSignal(SIGHUP
,SIGNAL_CAST sig_hup
);
686 /* we are never interested in SIGPIPE */
687 BlockSignals(True
,SIGPIPE
);
690 /* we are never interested in SIGFPE */
691 BlockSignals(True
,SIGFPE
);
695 /* We are no longer interested in USR2 */
696 BlockSignals(True
,SIGUSR2
);
699 /* POSIX demands that signals are inherited. If the invoking process has
700 * these signals masked, we will have problems, as we won't recieve them. */
701 BlockSignals(False
, SIGHUP
);
702 BlockSignals(False
, SIGUSR1
);
703 BlockSignals(False
, SIGTERM
);
705 /* we want total control over the permissions on created files,
706 so set our umask to 0 */
713 DEBUG(0,( "smbd version %s started.\n", VERSION
));
714 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
716 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
717 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
719 /* Output the build options to the debug log */
720 build_options(False
);
722 if (sizeof(uint16
) < 2 || sizeof(uint32
) < 4) {
723 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
728 * Do this before reload_services.
731 if (!reload_services(False
))
737 if (!profile_setup(False
)) {
738 DEBUG(0,("ERROR: failed to setup profiling\n"));
743 fstrcpy(global_myworkgroup
, lp_workgroup());
745 DEBUG(3,( "loaded services\n"));
747 if (!is_daemon
&& !is_a_socket(0)) {
749 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
752 * Setting is_daemon here prevents us from eventually calling
753 * the open_sockets_inetd()
759 if (is_daemon
&& !interactive
) {
760 DEBUG( 3, ( "Becoming a daemon.\n" ) );
766 * If we're interactive we want to set our own process group for
770 setpgid( (pid_t
)0, (pid_t
)0);
773 if (!directory_exist(lp_lockdir(), NULL
)) {
774 mkdir(lp_lockdir(), 0755);
778 pidfile_create("smbd");
781 if (!message_init()) {
784 register_msg_pool_usage();
785 register_dmalloc_msgs();
787 if (!print_backend_init())
790 /* Setup the main smbd so that we can get messages. */
791 claim_connection(NULL
,"",0,True
,FLAG_MSG_GENERAL
|FLAG_MSG_SMBD
);
794 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
795 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
796 smbd PROCESSES THAT NEVER DIE
797 start_background_queue();
800 if (!open_sockets_smbd(is_daemon
,ports
))
804 * everything after this point is run after the fork()
809 if (!locking_init(0))
812 if (!share_info_db_init())
815 if (!init_registry())
818 if(!initialize_password_db(False
))
821 uni_group_cache_init(); /* Non-critical */
823 /* possibly reload the services file. */
824 reload_services(True
);
826 if(!get_global_sam_sid()) {
827 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
831 if (!init_account_policy()) {
832 DEBUG(0,("Could not open account policy tdb.\n"));
837 if (sys_chroot(lp_rootdir()) == 0)
838 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
845 /* Setup change notify */
846 if (!init_change_notify())
849 /* re-initialise the timezone */
852 /* register our message handlers */
853 message_register(MSG_SMB_FORCE_TDIS
, msg_force_tdis
);
854 talloc_init_named("dummy!");
858 uni_group_cache_shutdown();
859 exit_server("normal exit");