2 Unix SMB/Netbios implementation.
4 Main SMB server routines
5 Copyright (C) Andrew Tridgell 1992-1998
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 pstring servicesf
= CONFIGFILE
;
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
;
39 extern int dcelogin_atmost_once
;
42 extern fstring remote_machine
;
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 void smbd_set_server_fd(int fd
)
63 /****************************************************************************
65 ****************************************************************************/
67 SIG_ATOMIC_T got_sig_term
;
69 static void sig_term(void)
75 /****************************************************************************
77 ****************************************************************************/
79 SIG_ATOMIC_T reload_after_sighup
;
81 static void sig_hup(int sig
)
83 reload_after_sighup
= 1;
87 /****************************************************************************
88 Send a SIGTERM to our process group.
89 *****************************************************************************/
91 static void killkids(void)
97 /****************************************************************************
98 Open the socket communication - inetd.
99 ****************************************************************************/
101 static BOOL
open_sockets_inetd(void)
103 /* Started from inetd. fd 0 is the socket. */
104 /* We will abort gracefully when the client or remote system
106 smbd_set_server_fd(dup(0));
108 /* close our standard file descriptors */
111 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
112 set_socket_options(smbd_server_fd(),user_socket_options
);
117 /****************************************************************************
118 Have we reached the process limit ?
119 ****************************************************************************/
121 BOOL
allowable_number_of_smbd_processes(void)
123 int max_processes
= lp_max_smbd_processes();
129 TDB_CONTEXT
*tdb
= conn_tdb_ctx();
132 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
136 val
= tdb_fetch_int32(tdb
, "INFO/total_smbds");
137 if (val
== -1 && (tdb_error(tdb
) != TDB_ERR_NOEXIST
)) {
138 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
139 tdb_errorstr(tdb
) ));
142 if (val
> max_processes
) {
143 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
144 val
, max_processes
));
151 /****************************************************************************
152 Open the socket communication.
153 ****************************************************************************/
155 static BOOL
open_sockets(BOOL is_daemon
,BOOL interactive
, int port
)
157 int num_interfaces
= iface_count();
158 int fd_listenset
[FD_SETSIZE
];
164 return open_sockets_inetd();
170 static int atexit_set
;
171 if(atexit_set
== 0) {
182 FD_ZERO(&listen_set
);
184 if(lp_interfaces() && lp_bind_interfaces_only()) {
185 /* We have been given an interfaces line, and been
186 told to only bind to those interfaces. Create a
187 socket per interface and bind to only these.
190 if(num_interfaces
> FD_SETSIZE
) {
191 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
193 num_interfaces
, FD_SETSIZE
));
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
);
203 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i
));
206 s
= fd_listenset
[i
] = open_socket_in(SOCK_STREAM
, port
, 0, ifip
->s_addr
, True
);
210 /* ready to listen */
211 set_socket_options(s
,"SO_KEEPALIVE");
212 set_socket_options(s
,user_socket_options
);
214 if (listen(s
, 5) == -1) {
215 DEBUG(0,("listen: %s\n",strerror(errno
)));
219 FD_SET(s
,&listen_set
);
222 /* Just bind to 0.0.0.0 - accept connections
226 /* open an incoming socket */
227 s
= open_socket_in(SOCK_STREAM
, port
, 0,
228 interpret_addr(lp_socket_address()),True
);
232 /* ready to listen */
233 set_socket_options(s
,"SO_KEEPALIVE");
234 set_socket_options(s
,user_socket_options
);
236 if (listen(s
, 5) == -1) {
237 DEBUG(0,("open_sockets: listen: %s\n",
244 FD_SET(s
,&listen_set
);
247 /* now accept incoming connections - forking a new process
248 for each incoming connection */
249 DEBUG(2,("waiting for a connection\n"));
254 /* Free up temporary memory from the main smbd. */
257 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
260 memcpy((char *)&lfds
, (char *)&listen_set
,
263 num
= sys_select(FD_SETSIZE
,&lfds
,NULL
,NULL
,NULL
);
265 if (num
== -1 && errno
== EINTR
) {
267 exit_server("Caught TERM signal");
270 /* check for sighup processing */
271 if (reload_after_sighup
) {
272 DEBUG(0,("Got SIGHUP\n"));
273 change_to_root_user();
274 DEBUG(1,("Reloading services after SIGHUP\n"));
275 reload_services(False
);
276 reload_after_sighup
= False
;
282 /* check if we need to reload services */
283 check_reload(time(NULL
));
285 /* Find the sockets that are read-ready -
287 for( ; num
> 0; num
--) {
288 struct sockaddr addr
;
289 socklen_t in_addrlen
= sizeof(addr
);
292 for(i
= 0; i
< num_interfaces
; i
++) {
293 if(FD_ISSET(fd_listenset
[i
],&lfds
)) {
295 /* Clear this so we don't look
297 FD_CLR(fd_listenset
[i
],&lfds
);
302 smbd_set_server_fd(accept(s
,&addr
,&in_addrlen
));
304 if (smbd_server_fd() == -1 && errno
== EINTR
)
307 if (smbd_server_fd() == -1) {
308 DEBUG(0,("open_sockets: accept: %s\n",
313 if (smbd_server_fd() != -1 && interactive
)
316 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
319 /* close the listening socket(s) */
320 for(i
= 0; i
< num_interfaces
; i
++)
321 close(fd_listenset
[i
]);
323 /* close our standard file
328 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
329 set_socket_options(smbd_server_fd(),user_socket_options
);
331 /* Reset global variables in util.c so
332 that client substitutions will be
333 done correctly in the process. */
334 reset_globals_after_fork();
336 /* tdb needs special fork handling */
341 /* The parent doesn't need this socket */
342 close(smbd_server_fd());
344 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
345 Clear the closed fd info out of server_fd --
346 and more importantly, out of client_fd in
347 util_sock.c, to avoid a possible
348 getpeername failure if we reopen the logs
349 and use %I in the filename.
352 smbd_set_server_fd(-1);
354 /* Force parent to check log size after
355 * spawning child. Fix from
356 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
357 * parent smbd will log to logserver.smb. It
358 * writes only two messages for each child
359 * started/finished. But each child writes,
360 * say, 50 messages also in logserver.smb,
361 * begining with the debug_count of the
362 * parent, before the child opens its own log
363 * file logserver.client. In a worst case
364 * scenario the size of logserver.smb would be
365 * checked after about 50*50=2500 messages
368 force_check_log_size();
373 /* NOTREACHED return True; */
376 /****************************************************************************
377 Reload the services file.
378 **************************************************************************/
380 BOOL
reload_services(BOOL test
)
386 pstrcpy(fname
,lp_configfile());
387 if (file_exist(fname
,NULL
) && !strcsequal(fname
,servicesf
)) {
388 pstrcpy(servicesf
,fname
);
395 if (test
&& !lp_file_list_changed())
398 lp_killunused(conn_snum_used
);
400 ret
= lp_load(servicesf
,False
,False
,True
);
404 /* perhaps the config filename is now set */
406 reload_services(True
);
413 if (smbd_server_fd() != -1) {
414 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
415 set_socket_options(smbd_server_fd(),user_socket_options
);
419 mangle_reset_cache();
422 /* this forces service parameters to be flushed */
423 set_current_service(NULL
,True
);
429 /*******************************************************************
430 Prepare to dump a core file - carefully !
431 ********************************************************************/
433 static BOOL
dump_core(void)
437 pstrcpy(dname
,lp_logfile());
438 if ((p
=strrchr(dname
,'/'))) *p
=0;
439 pstrcat(dname
,"/corefiles");
441 sys_chown(dname
,getuid(),getgid());
443 if (chdir(dname
)) return(False
);
446 #ifdef HAVE_GETRLIMIT
450 getrlimit(RLIMIT_CORE
, &rlp
);
451 rlp
.rlim_cur
= MAX(4*1024*1024,rlp
.rlim_cur
);
452 setrlimit(RLIMIT_CORE
, &rlp
);
453 getrlimit(RLIMIT_CORE
, &rlp
);
454 DEBUG(3,("Core limits now %d %d\n",
455 (int)rlp
.rlim_cur
,(int)rlp
.rlim_max
));
461 DEBUG(0,("Dumping core in %s\n",dname
));
467 /****************************************************************************
468 update the current smbd process count
469 ****************************************************************************/
471 static BOOL process_count_update_successful
= False
;
473 int32
increment_smbd_process_count(void)
477 if (lp_max_smbd_processes()) {
479 if (tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds
, 1) == -1)
481 process_count_update_successful
= True
;
482 return total_smbds
+ 1;
487 static void decrement_smbd_process_count(void)
491 if (lp_max_smbd_processes() && process_count_update_successful
) {
493 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds
, -1);
497 /****************************************************************************
499 ****************************************************************************/
501 void exit_server(const char *reason
)
503 static int firsttime
=1;
504 extern char *last_inbuf
;
507 if (!firsttime
) exit(0);
510 change_to_root_user();
511 DEBUG(2,("Closing connections\n"));
515 invalidate_all_vuids();
517 /* delete our entry in the connections database. */
519 yield_connection(NULL
,"");
521 respond_to_all_remaining_local_messages();
522 decrement_smbd_process_count();
525 if (dcelogin_atmost_once
) {
531 int oldlevel
= DEBUGLEVEL
;
533 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message
)));
535 show_msg(last_inbuf
);
536 DEBUGLEVEL
= oldlevel
;
537 DEBUG(0,("===============================================================\n"));
539 if (dump_core()) return;
545 DEBUG(3,("Server exit (%s)\n", (reason
? reason
: "")));
549 /****************************************************************************
550 Initialise connect, service and file structs.
551 ****************************************************************************/
553 static void init_structs(void )
556 * Set the machine NETBIOS name if not already
557 * set from the config file.
560 if (!*global_myname
) {
562 fstrcpy( global_myname
, myhostname() );
563 p
= strchr( global_myname
, '.' );
568 strupper( global_myname
);
582 /****************************************************************************
583 Keep track of the number of running smbd's. This functionality is used to
584 'hard' limit Samba overhead on resource constrained systems.
585 This function is only called once per smbd.
586 ****************************************************************************/
588 static BOOL
smbd_process_limit(void)
592 if (lp_max_smbd_processes()) {
594 /* Always add one to the smbd process count, as exit_server() always
598 if (!conn_tdb_ctx()) {
599 DEBUG(0,("smbd_process_limit: max smbd processes parameter set with status parameter not \
600 set. Ignoring max smbd restriction.\n"));
604 total_smbds
= increment_smbd_process_count();
605 return total_smbds
> lp_max_smbd_processes();
612 /****************************************************************************
613 Usage on the program.
614 ****************************************************************************/
616 static void usage(char *pname
)
619 printf("Usage: %s [-DaioPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname
);
620 printf(" [-O socket options] [-s services file]\n");
621 printf("\t-D Become a daemon (default)\n");
622 printf("\t-a Append to log file (default)\n");
623 printf("\t-i Run interactive (not a daemon)\n");
624 printf("\t-o Overwrite log file, don't append\n");
625 printf("\t-h Print usage\n");
626 printf("\t-? Print usage\n");
627 printf("\t-V Print version\n");
628 printf("\t-d debuglevel Set the debuglevel\n");
629 printf("\t-l log basename. Basename for log/debug files\n");
630 printf("\t-p port Listen on the specified port\n");
631 printf("\t-O socket options Socket options\n");
632 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
;
644 /* shall I run as a daemon */
645 BOOL is_daemon
= False
;
646 BOOL interactive
= False
;
647 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:Dip:h?Vaof:")) )
666 pstrcpy(user_socket_options
,optarg
);
670 pstrcpy(servicesf
,optarg
);
674 specified_logfile
= True
;
675 slprintf(logfile
, sizeof(logfile
)-1, "%s/log.smbd", optarg
);
676 lp_set_logfile(logfile
);
699 DEBUGLEVEL
= atoi(optarg
);
700 AllowDebugChange
= False
;
714 printf("Version %s\n",VERSION
);
718 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
724 /* needed for SecureWare on SCO */
734 if(!specified_logfile
) {
735 slprintf(logfile
, sizeof(logfile
)-1, "%s/log.smbd", LOGFILEBASE
);
736 lp_set_logfile(logfile
);
739 pstrcpy(remote_machine
, "smbd");
742 * Only want interactive behaviour if the user has not also
743 * specified a logfile dir etc.
745 setup_logging(argv
[0],interactive
& !specified_logfile
);
747 charset_initialise();
749 /* we want to re-seed early to prevent time delays causing
750 client problems at a later date. (tridge) */
751 generate_random_buffer(NULL
, 0, False
);
753 /* make absolutely sure we run as root - to handle cases where people
754 are crazy enough to have it setuid */
756 gain_root_privilege();
757 gain_root_group_privilege();
759 fault_setup((void (*)(void *))exit_server
);
760 CatchSignal(SIGTERM
, SIGNAL_CAST sig_term
);
761 CatchSignal(SIGHUP
,SIGNAL_CAST sig_hup
);
763 /* we are never interested in SIGPIPE */
764 BlockSignals(True
,SIGPIPE
);
767 /* we are never interested in SIGFPE */
768 BlockSignals(True
,SIGFPE
);
772 /* We are no longer interested in USR2 */
773 BlockSignals(True
,SIGUSR2
);
776 /* POSIX demands that signals are inherited. If the invoking process has
777 * these signals masked, we will have problems, as we won't recieve them. */
778 BlockSignals(False
, SIGHUP
);
779 BlockSignals(False
, SIGUSR1
);
780 BlockSignals(False
, SIGTERM
);
782 /* we want total control over the permissions on created files,
783 so set our umask to 0 */
791 DEBUG(0,( "smbd version %s started.\n", VERSION
));
792 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
794 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
795 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
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 shared memory\n"));
816 #endif /* WITH_PROFILE */
820 extern BOOL sslEnabled
;
821 sslEnabled
= lp_ssl_enabled();
825 #endif /* WITH_SSL */
827 codepage_initialise(lp_client_code_page());
829 fstrcpy(global_myworkgroup
, lp_workgroup());
831 DEBUG(3,( "loaded services\n"));
833 if (!is_daemon
&& !is_a_socket(0)) {
835 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
838 * Setting is_daemon here prevents us from eventually calling
839 * the open_sockets_inetd()
845 if (is_daemon
&& !interactive
) {
846 DEBUG( 3, ( "Becoming a daemon.\n" ) );
852 * If we're interactive we want to set our own process group for
856 setpgid( (pid_t
)0, (pid_t
)0);
859 if (!directory_exist(lp_lockdir(), NULL
))
860 mkdir(lp_lockdir(), 0755);
863 pidfile_create("smbd");
868 /* Setup the main smbd so that we can get messages. */
870 claim_connection(NULL
,"",0,True
);
872 /* Attempt to migrate from an old 2.0.x machine account file. */
873 if (!migrate_from_old_password_file(global_myworkgroup
))
874 DEBUG(0,("Failed to migrate from old MAC file.\n"));
876 if(!pdb_generate_sam_sid()) {
877 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
881 if (!open_sockets(is_daemon
,interactive
,port
))
885 * Everything after this point is run after the fork().
888 if (!locking_init(0))
891 if (!print_backend_init())
894 if (!share_info_db_init())
897 if(!initialize_password_db(False
))
900 /* possibly reload the services file. */
901 reload_services(True
);
904 if (sys_chroot(lp_rootdir()) == 0)
905 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
912 /* Setup change notify */
913 if (!init_change_notify())
916 if ( smbd_process_limit() ) {
917 DEBUG( 1, ( "Connection denied from %s\n",
919 exit_server("connection denied");
924 exit_server("normal exit");