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
;
36 extern SIG_ATOMIC_T got_sig_term
;
37 extern SIG_ATOMIC_T reload_after_sighup
;
40 extern int dcelogin_atmost_once
;
43 /* really we should have a top level context structure that has the
44 client file descriptor as an element. That would require a major rewrite :(
46 the following 2 functions are an alternative - they make the file
47 descriptor private to smbd
49 static int server_fd
= -1;
51 int smbd_server_fd(void)
56 static void smbd_set_server_fd(int fd
)
62 /****************************************************************************
64 ****************************************************************************/
66 static void sig_term(void)
72 /****************************************************************************
74 ****************************************************************************/
76 static void sig_hup(int sig
)
78 reload_after_sighup
= 1;
82 /****************************************************************************
83 Send a SIGTERM to our process group.
84 *****************************************************************************/
86 static void killkids(void)
88 if(am_parent
) kill(0,SIGTERM
);
91 /****************************************************************************
92 Process a sam sync message - not sure whether to do this here or
94 ****************************************************************************/
96 static void msg_sam_sync(int UNUSED(msg_type
), pid_t
UNUSED(pid
),
97 void *UNUSED(buf
), size_t UNUSED(len
))
99 DEBUG(10, ("** sam sync message received, ignoring\n"));
102 /****************************************************************************
103 Process a sam sync replicate message - not sure whether to do this here or
105 ****************************************************************************/
107 static void msg_sam_repl(int msg_type
, pid_t pid
, void *buf
, size_t len
)
111 if (len
!= sizeof(uint32
))
114 low_serial
= *((uint32
*)buf
);
116 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
120 /****************************************************************************
121 Open the socket communication - inetd.
122 ****************************************************************************/
124 static BOOL
open_sockets_inetd(void)
126 /* Started from inetd. fd 0 is the socket. */
127 /* We will abort gracefully when the client or remote system
129 smbd_set_server_fd(dup(0));
131 /* close our standard file descriptors */
132 close_low_fds(False
); /* Don't close stderr */
134 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
135 set_socket_options(smbd_server_fd(), user_socket_options
);
140 static void msg_exit_server(int msg_type
, pid_t src
, void *buf
, size_t len
)
142 exit_server("Got a SHUTDOWN message");
146 /****************************************************************************
147 Open the socket communication.
148 ****************************************************************************/
150 static BOOL
open_sockets_smbd(BOOL is_daemon
,const char *smb_ports
)
152 int num_interfaces
= iface_count();
154 int fd_listenset
[FD_SETSIZE
];
161 return open_sockets_inetd();
167 static int atexit_set
;
168 if(atexit_set
== 0) {
178 FD_ZERO(&listen_set
);
180 /* use a reasonable default set of ports - listing on 445 and 139 */
182 ports
= lp_smb_ports();
183 if (!ports
|| !*ports
) {
186 ports
= strdup(ports
);
188 ports
= strdup(smb_ports
);
191 if (lp_interfaces() && lp_bind_interfaces_only()) {
192 /* We have been given an interfaces line, and been
193 told to only bind to those interfaces. Create a
194 socket per interface and bind to only these.
197 /* Now open a listen socket for each of the
199 for(i
= 0; i
< num_interfaces
; i
++) {
200 struct in_addr
*ifip
= iface_n_ip(i
);
205 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i
));
209 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
210 unsigned port
= atoi(tok
);
211 if (port
== 0) continue;
212 s
= fd_listenset
[num_sockets
] = open_socket_in(SOCK_STREAM
, port
, 0, ifip
->s_addr
, True
);
216 /* ready to listen */
217 set_socket_options(s
,"SO_KEEPALIVE");
218 set_socket_options(s
,user_socket_options
);
220 if (listen(s
, 5) == -1) {
221 DEBUG(0,("listen: %s\n",strerror(errno
)));
225 FD_SET(s
,&listen_set
);
228 if (num_sockets
>= FD_SETSIZE
) {
229 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
235 /* Just bind to 0.0.0.0 - accept connections
243 for (ptr
=ports
; next_token(&ptr
, tok
, NULL
, sizeof(tok
)); ) {
244 unsigned port
= atoi(tok
);
245 if (port
== 0) continue;
246 /* open an incoming socket */
247 s
= open_socket_in(SOCK_STREAM
, port
, 0,
248 interpret_addr(lp_socket_address()),True
);
252 /* ready to listen */
253 set_socket_options(s
,"SO_KEEPALIVE");
254 set_socket_options(s
,user_socket_options
);
256 if (listen(s
, 5) == -1) {
257 DEBUG(0,("open_sockets_smbd: listen: %s\n",
263 fd_listenset
[num_sockets
] = s
;
264 FD_SET(s
,&listen_set
);
268 if (num_sockets
>= FD_SETSIZE
) {
269 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
277 /* Listen to messages */
279 message_register(MSG_SMB_SAM_SYNC
, msg_sam_sync
);
280 message_register(MSG_SMB_SAM_REPL
, msg_sam_repl
);
281 message_register(MSG_SHUTDOWN
, msg_exit_server
);
283 /* now accept incoming connections - forking a new process
284 for each incoming connection */
285 DEBUG(2,("waiting for a connection\n"));
290 /* Free up temporary memory from the main smbd. */
293 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
296 memcpy((char *)&lfds
, (char *)&listen_set
,
299 num
= sys_select(FD_SETSIZE
,&lfds
,NULL
,NULL
,NULL
);
301 if (num
== -1 && errno
== EINTR
) {
303 exit_server("Caught TERM signal");
306 /* check for sighup processing */
307 if (reload_after_sighup
) {
308 change_to_root_user();
309 DEBUG(1,("Reloading services after SIGHUP\n"));
310 reload_services(False
);
311 reload_after_sighup
= 0;
317 /* check if we need to reload services */
318 check_reload(time(NULL
));
320 /* Find the sockets that are read-ready -
322 for( ; num
> 0; num
--) {
323 struct sockaddr addr
;
324 socklen_t in_addrlen
= sizeof(addr
);
327 for(i
= 0; i
< num_sockets
; i
++) {
328 if(FD_ISSET(fd_listenset
[i
],&lfds
)) {
330 /* Clear this so we don't look
332 FD_CLR(fd_listenset
[i
],&lfds
);
337 smbd_set_server_fd(accept(s
,&addr
,&in_addrlen
));
339 if (smbd_server_fd() == -1 && errno
== EINTR
)
342 if (smbd_server_fd() == -1) {
343 DEBUG(0,("open_sockets_smbd: accept: %s\n",
348 if (smbd_server_fd() != -1 && sys_fork()==0) {
351 /* close the listening socket(s) */
352 for(i
= 0; i
< num_sockets
; i
++)
353 close(fd_listenset
[i
]);
355 /* close our standard file
357 close_low_fds(False
);
360 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
361 set_socket_options(smbd_server_fd(),user_socket_options
);
363 /* this is needed so that we get decent entries
364 in smbstatus for port 445 connects */
365 set_remote_machine_name(get_socket_addr(smbd_server_fd()));
367 /* Reset global variables in util.c so
368 that client substitutions will be
369 done correctly in the process. */
370 reset_globals_after_fork();
372 /* tdb needs special fork handling */
377 /* The parent doesn't need this socket */
378 close(smbd_server_fd());
380 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
381 Clear the closed fd info out of server_fd --
382 and more importantly, out of client_fd in
383 util_sock.c, to avoid a possible
384 getpeername failure if we reopen the logs
385 and use %I in the filename.
388 smbd_set_server_fd(-1);
390 /* Force parent to check log size after
391 * spawning child. Fix from
392 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
393 * parent smbd will log to logserver.smb. It
394 * writes only two messages for each child
395 * started/finished. But each child writes,
396 * say, 50 messages also in logserver.smb,
397 * begining with the debug_count of the
398 * parent, before the child opens its own log
399 * file logserver.client. In a worst case
400 * scenario the size of logserver.smb would be
401 * checked after about 50*50=2500 messages
404 force_check_log_size();
409 /* NOTREACHED return True; */
412 /****************************************************************************
413 Reload the services file.
414 **************************************************************************/
416 BOOL
reload_services(BOOL test
)
422 pstrcpy(fname
,lp_configfile());
423 if (file_exist(fname
, NULL
) &&
424 !strcsequal(fname
, dyn_CONFIGFILE
)) {
425 pstrcpy(dyn_CONFIGFILE
, fname
);
432 if (test
&& !lp_file_list_changed())
435 lp_killunused(conn_snum_used
);
437 ret
= lp_load(dyn_CONFIGFILE
, False
, False
, True
);
441 /* perhaps the config filename is now set */
443 reload_services(True
);
450 if (smbd_server_fd() != -1) {
451 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
452 set_socket_options(smbd_server_fd(), user_socket_options
);
456 mangle_reset_cache();
459 /* this forces service parameters to be flushed */
460 set_current_service(NULL
,True
);
466 /*******************************************************************
467 prepare to dump a core file - carefully!
468 ********************************************************************/
469 static BOOL
dump_core(void)
474 pstrcpy(dname
,lp_logfile());
475 if ((p
=strrchr_m(dname
,'/'))) *p
=0;
476 pstrcat(dname
,"/corefiles");
478 sys_chown(dname
,getuid(),getgid());
480 if (chdir(dname
)) return(False
);
483 #ifdef HAVE_GETRLIMIT
487 getrlimit(RLIMIT_CORE
, &rlp
);
488 rlp
.rlim_cur
= MAX(4*1024*1024,rlp
.rlim_cur
);
489 setrlimit(RLIMIT_CORE
, &rlp
);
490 getrlimit(RLIMIT_CORE
, &rlp
);
491 DEBUG(3,("Core limits now %d %d\n",
492 (int)rlp
.rlim_cur
,(int)rlp
.rlim_max
));
498 DEBUG(0,("Dumping core in %s\n", dname
));
504 /****************************************************************************
505 update the current smbd process count
506 ****************************************************************************/
508 static void decrement_smbd_process_count(void)
512 if (lp_max_smbd_processes()) {
514 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds
, -1);
518 /****************************************************************************
520 ****************************************************************************/
522 void exit_server(char *reason
)
524 static int firsttime
=1;
525 extern char *last_inbuf
;
526 extern struct auth_context
*negprot_global_auth_context
;
532 change_to_root_user();
533 DEBUG(2,("Closing connections\n"));
535 if (negprot_global_auth_context
) {
536 (negprot_global_auth_context
->free
)(&negprot_global_auth_context
);
541 invalidate_all_vuids();
543 print_notify_send_messages();
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
,FLAG_MSG_GENERAL
|FLAG_MSG_SMBD
);
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");