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.
27 /* the last message the was processed */
28 int last_message
= -1;
30 /* a useful macro to debug the last message processed */
31 #define LAST_MESSAGE() smb_fn_name(last_message)
33 extern pstring user_socket_options
;
34 extern SIG_ATOMIC_T got_sig_term
;
35 extern SIG_ATOMIC_T reload_after_sighup
;
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 static void sig_term(void)
70 /****************************************************************************
72 ****************************************************************************/
74 static void sig_hup(int sig
)
76 reload_after_sighup
= 1;
80 /****************************************************************************
81 Send a SIGTERM to our process group.
82 *****************************************************************************/
84 static void killkids(void)
86 if(am_parent
) kill(0,SIGTERM
);
89 /****************************************************************************
90 Process a sam sync message - not sure whether to do this here or
92 ****************************************************************************/
94 static void msg_sam_sync(int UNUSED(msg_type
), pid_t
UNUSED(pid
),
95 void *UNUSED(buf
), size_t UNUSED(len
))
97 DEBUG(10, ("** sam sync message received, ignoring\n"));
100 /****************************************************************************
101 Process a sam sync replicate message - not sure whether to do this here or
103 ****************************************************************************/
105 static void msg_sam_repl(int msg_type
, pid_t pid
, void *buf
, size_t len
)
109 if (len
!= sizeof(uint32
))
112 low_serial
= *((uint32
*)buf
);
114 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
118 /****************************************************************************
119 Open the socket communication - inetd.
120 ****************************************************************************/
122 static BOOL
open_sockets_inetd(void)
124 /* Started from inetd. fd 0 is the socket. */
125 /* We will abort gracefully when the client or remote system
127 smbd_set_server_fd(dup(0));
129 /* close our standard file descriptors */
130 close_low_fds(False
); /* Don't close stderr */
132 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
133 set_socket_options(smbd_server_fd(), user_socket_options
);
138 static void msg_exit_server(int msg_type
, pid_t src
, void *buf
, size_t len
)
140 exit_server("Got a SHUTDOWN message");
144 /****************************************************************************
145 Open the socket communication.
146 ****************************************************************************/
148 static BOOL
open_sockets_smbd(BOOL is_daemon
, BOOL interactive
, const char *smb_ports
)
150 int num_interfaces
= iface_count();
152 int fd_listenset
[FD_SETSIZE
];
159 return open_sockets_inetd();
165 static int atexit_set
;
166 if(atexit_set
== 0) {
176 FD_ZERO(&listen_set
);
178 /* use a reasonable default set of ports - listing on 445 and 139 */
180 ports
= lp_smb_ports();
181 if (!ports
|| !*ports
) {
182 ports
= smb_xstrdup(SMB_PORTS
);
184 ports
= smb_xstrdup(ports
);
187 ports
= smb_xstrdup(smb_ports
);
190 if (lp_interfaces() && lp_bind_interfaces_only()) {
191 /* We have been given an interfaces line, and been
192 told to only bind to those interfaces. Create a
193 socket per interface and bind to only these.
196 /* Now open a listen socket for each of the
198 for(i
= 0; i
< num_interfaces
; i
++) {
199 struct in_addr
*ifip
= iface_n_ip(i
);
204 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i
));
208 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
209 unsigned port
= atoi(tok
);
210 if (port
== 0) continue;
211 s
= fd_listenset
[num_sockets
] = open_socket_in(SOCK_STREAM
, port
, 0, ifip
->s_addr
, True
);
215 /* ready to listen */
216 set_socket_options(s
,"SO_KEEPALIVE");
217 set_socket_options(s
,user_socket_options
);
219 if (listen(s
, 5) == -1) {
220 DEBUG(0,("listen: %s\n",strerror(errno
)));
224 FD_SET(s
,&listen_set
);
227 if (num_sockets
>= FD_SETSIZE
) {
228 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
234 /* Just bind to 0.0.0.0 - accept connections
242 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
243 unsigned port
= atoi(tok
);
244 if (port
== 0) continue;
245 /* open an incoming socket */
246 s
= open_socket_in(SOCK_STREAM
, port
, 0,
247 interpret_addr(lp_socket_address()),True
);
251 /* ready to listen */
252 set_socket_options(s
,"SO_KEEPALIVE");
253 set_socket_options(s
,user_socket_options
);
255 if (listen(s
, 5) == -1) {
256 DEBUG(0,("open_sockets_smbd: listen: %s\n",
262 fd_listenset
[num_sockets
] = s
;
263 FD_SET(s
,&listen_set
);
267 if (num_sockets
>= FD_SETSIZE
) {
268 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
276 /* Listen to messages */
278 message_register(MSG_SMB_SAM_SYNC
, msg_sam_sync
);
279 message_register(MSG_SMB_SAM_REPL
, msg_sam_repl
);
280 message_register(MSG_SHUTDOWN
, msg_exit_server
);
282 /* now accept incoming connections - forking a new process
283 for each incoming connection */
284 DEBUG(2,("waiting for a connection\n"));
289 /* Free up temporary memory from the main smbd. */
292 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
295 memcpy((char *)&lfds
, (char *)&listen_set
,
298 num
= sys_select(FD_SETSIZE
,&lfds
,NULL
,NULL
,NULL
);
300 if (num
== -1 && errno
== EINTR
) {
302 exit_server("Caught TERM signal");
305 /* check for sighup processing */
306 if (reload_after_sighup
) {
307 change_to_root_user();
308 DEBUG(1,("Reloading services after SIGHUP\n"));
309 reload_services(False
);
310 reload_after_sighup
= 0;
316 /* check if we need to reload services */
317 check_reload(time(NULL
));
319 /* Find the sockets that are read-ready -
321 for( ; num
> 0; num
--) {
322 struct sockaddr addr
;
323 socklen_t in_addrlen
= sizeof(addr
);
326 for(i
= 0; i
< num_sockets
; i
++) {
327 if(FD_ISSET(fd_listenset
[i
],&lfds
)) {
329 /* Clear this so we don't look
331 FD_CLR(fd_listenset
[i
],&lfds
);
336 smbd_set_server_fd(accept(s
,&addr
,&in_addrlen
));
338 if (smbd_server_fd() == -1 && errno
== EINTR
)
341 if (smbd_server_fd() == -1) {
342 DEBUG(0,("open_sockets_smbd: accept: %s\n",
347 if (smbd_server_fd() != -1 && interactive
)
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 */
375 if (tdb_reopen_all() == -1) {
376 DEBUG(0,("tdb_reopen_all failed.\n"));
382 smb_load_modules(lp_modules());
386 /* The parent doesn't need this socket */
387 close(smbd_server_fd());
389 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
390 Clear the closed fd info out of server_fd --
391 and more importantly, out of client_fd in
392 util_sock.c, to avoid a possible
393 getpeername failure if we reopen the logs
394 and use %I in the filename.
397 smbd_set_server_fd(-1);
399 /* Force parent to check log size after
400 * spawning child. Fix from
401 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
402 * parent smbd will log to logserver.smb. It
403 * writes only two messages for each child
404 * started/finished. But each child writes,
405 * say, 50 messages also in logserver.smb,
406 * begining with the debug_count of the
407 * parent, before the child opens its own log
408 * file logserver.client. In a worst case
409 * scenario the size of logserver.smb would be
410 * checked after about 50*50=2500 messages
413 force_check_log_size();
418 /* NOTREACHED return True; */
421 /****************************************************************************
422 Reload the services file.
423 **************************************************************************/
425 BOOL
reload_services(BOOL test
)
431 pstrcpy(fname
,lp_configfile());
432 if (file_exist(fname
, NULL
) &&
433 !strcsequal(fname
, dyn_CONFIGFILE
)) {
434 pstrcpy(dyn_CONFIGFILE
, fname
);
441 if (test
&& !lp_file_list_changed())
444 lp_killunused(conn_snum_used
);
446 ret
= lp_load(dyn_CONFIGFILE
, False
, False
, True
);
450 /* perhaps the config filename is now set */
452 reload_services(True
);
459 if (smbd_server_fd() != -1) {
460 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
461 set_socket_options(smbd_server_fd(), user_socket_options
);
465 mangle_reset_cache();
468 /* this forces service parameters to be flushed */
469 set_current_service(NULL
,True
);
474 /*******************************************************************
475 Print out all talloc memory info.
476 ********************************************************************/
478 void return_all_talloc_info(int msg_type
, pid_t src_pid
, void *buf
, size_t len
)
480 TALLOC_CTX
*ctx
= talloc_init("info context");
486 info
= talloc_describe_all(ctx
);
489 message_send_pid(src_pid
, MSG_TALLOC_USAGE
, info
, info
? strlen(info
) + 1 : 0, True
);
494 /*******************************************************************
495 prepare to dump a core file - carefully!
496 ********************************************************************/
497 static BOOL
dump_core(void)
502 pstrcpy(dname
,lp_logfile());
503 if ((p
=strrchr_m(dname
,'/'))) *p
=0;
504 pstrcat(dname
,"/corefiles");
506 sys_chown(dname
,getuid(),getgid());
508 if (chdir(dname
)) return(False
);
511 #ifdef HAVE_GETRLIMIT
515 getrlimit(RLIMIT_CORE
, &rlp
);
516 rlp
.rlim_cur
= MAX(4*1024*1024,rlp
.rlim_cur
);
517 setrlimit(RLIMIT_CORE
, &rlp
);
518 getrlimit(RLIMIT_CORE
, &rlp
);
519 DEBUG(3,("Core limits now %d %d\n",
520 (int)rlp
.rlim_cur
,(int)rlp
.rlim_max
));
526 DEBUG(0,("Dumping core in %s\n", dname
));
532 /****************************************************************************
534 ****************************************************************************/
536 void exit_server(const char *reason
)
538 static int firsttime
=1;
539 extern char *last_inbuf
;
540 extern struct auth_context
*negprot_global_auth_context
;
546 change_to_root_user();
547 DEBUG(2,("Closing connections\n"));
549 if (negprot_global_auth_context
) {
550 (negprot_global_auth_context
->free
)(&negprot_global_auth_context
);
555 invalidate_all_vuids();
557 print_notify_send_messages();
559 /* delete our entry in the connections database. */
560 yield_connection(NULL
,"");
562 respond_to_all_remaining_local_messages();
563 decrement_smbd_process_count();
566 if (dcelogin_atmost_once
) {
572 int oldlevel
= DEBUGLEVEL
;
574 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message
)));
576 show_msg(last_inbuf
);
577 DEBUGLEVEL
= oldlevel
;
578 DEBUG(0,("===============================================================\n"));
580 if (dump_core()) return;
587 DEBUG(3,("Server exit (%s)\n", (reason
? reason
: "")));
591 /****************************************************************************
592 Initialise connect, service and file structs.
593 ****************************************************************************/
595 static BOOL
init_structs(void )
598 * Set the machine NETBIOS name if not already
599 * set from the config file.
619 /****************************************************************************
621 ****************************************************************************/
623 int main(int argc
,const char *argv
[])
625 /* shall I run as a daemon */
626 static BOOL is_daemon
= False
;
627 static BOOL interactive
= False
;
628 static BOOL Fork
= True
;
629 static BOOL log_stdout
= False
;
630 static char *ports
= NULL
;
634 struct poptOption long_options
[] = {
636 {"daemon", 'D', POPT_ARG_VAL
, &is_daemon
, True
, "Become a daemon (default)" },
637 {"interactive", 'i', POPT_ARG_VAL
, &interactive
, True
, "Run interactive (not a daemon)"},
638 {"foreground", 'F', POPT_ARG_VAL
, &Fork
, False
, "Run daemon in foreground (for daemontools & etc)" },
639 {"log-stdout", 'S', POPT_ARG_VAL
, &log_stdout
, True
, "Log to stdout" },
640 {"build-options", 'b', POPT_ARG_NONE
, NULL
, 'b', "Print build options" },
641 {"port", 'p', POPT_ARG_STRING
, &ports
, 0, "Listen on the specified ports"},
642 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_debug
},
643 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_configfile
},
644 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_socket_options
},
645 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_log_base
},
646 {NULL
, 0, POPT_ARG_INCLUDE_TABLE
, popt_common_version
},
650 #ifdef HAVE_SET_AUTH_PARAMETERS
651 set_auth_parameters(argc
,argv
);
654 pc
= poptGetContext("smbd", argc
, argv
, long_options
, 0);
656 while((opt
= poptGetNextOpt(pc
)) != -1) {
659 build_options(True
); /* Display output to screen as well as debug */
668 /* needed for SecureWare on SCO */
676 set_remote_machine_name("smbd");
683 if (log_stdout
&& Fork
) {
684 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
688 setup_logging(argv
[0],log_stdout
);
690 /* we want to re-seed early to prevent time delays causing
691 client problems at a later date. (tridge) */
692 generate_random_buffer(NULL
, 0, False
);
694 /* make absolutely sure we run as root - to handle cases where people
695 are crazy enough to have it setuid */
697 gain_root_privilege();
698 gain_root_group_privilege();
700 fault_setup((void (*)(void *))exit_server
);
701 CatchSignal(SIGTERM
, SIGNAL_CAST sig_term
);
702 CatchSignal(SIGHUP
,SIGNAL_CAST sig_hup
);
704 /* we are never interested in SIGPIPE */
705 BlockSignals(True
,SIGPIPE
);
708 /* we are never interested in SIGFPE */
709 BlockSignals(True
,SIGFPE
);
713 /* We are no longer interested in USR2 */
714 BlockSignals(True
,SIGUSR2
);
717 /* POSIX demands that signals are inherited. If the invoking process has
718 * these signals masked, we will have problems, as we won't recieve them. */
719 BlockSignals(False
, SIGHUP
);
720 BlockSignals(False
, SIGUSR1
);
721 BlockSignals(False
, SIGTERM
);
723 /* we want total control over the permissions on created files,
724 so set our umask to 0 */
731 DEBUG(0,( "smbd version %s started.\n", VERSION
));
732 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
734 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
735 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
737 /* Output the build options to the debug log */
738 build_options(False
);
740 if (sizeof(uint16
) < 2 || sizeof(uint32
) < 4) {
741 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
746 * Do this before reload_services.
749 if (!reload_services(False
))
755 if (!profile_setup(False
)) {
756 DEBUG(0,("ERROR: failed to setup profiling\n"));
761 DEBUG(3,( "loaded services\n"));
763 if (!is_daemon
&& !is_a_socket(0)) {
765 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
768 * Setting is_daemon here prevents us from eventually calling
769 * the open_sockets_inetd()
775 if (is_daemon
&& !interactive
) {
776 DEBUG( 3, ( "Becoming a daemon.\n" ) );
782 * If we're interactive we want to set our own process group for
786 setpgid( (pid_t
)0, (pid_t
)0);
789 if (!directory_exist(lp_lockdir(), NULL
))
790 mkdir(lp_lockdir(), 0755);
793 pidfile_create("smbd");
798 register_msg_pool_usage();
799 register_dmalloc_msgs();
800 message_register(MSG_REQ_TALLOC_USAGE
, return_all_talloc_info
);
802 if (!print_backend_init())
805 /* Setup the main smbd so that we can get messages. */
806 claim_connection(NULL
,"",0,True
,FLAG_MSG_GENERAL
|FLAG_MSG_SMBD
);
809 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
810 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
811 smbd PROCESSES THAT NEVER DIE
812 start_background_queue();
815 if (!open_sockets_smbd(is_daemon
, interactive
, ports
))
819 * everything after this point is run after the fork()
824 if (!locking_init(0))
827 if (!share_info_db_init())
830 if (!init_registry())
833 if(!initialize_password_db(False
))
836 uni_group_cache_init(); /* Non-critical */
838 /* possibly reload the services file. */
839 reload_services(True
);
841 if(!get_global_sam_sid()) {
842 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
846 if (!init_account_policy()) {
847 DEBUG(0,("Could not open account policy tdb.\n"));
852 if (sys_chroot(lp_rootdir()) == 0)
853 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
860 /* Setup change notify */
861 if (!init_change_notify())
864 /* re-initialise the timezone */
867 /* register our message handlers */
868 message_register(MSG_SMB_FORCE_TDIS
, msg_force_tdis
);
872 uni_group_cache_shutdown();
873 namecache_shutdown();
874 exit_server("normal exit");