* backport of "WinXP" and "Win2K3" values for %a
[Samba.git] / source / smbd / server.c
blobd7e958981b8cd80809017bfc10f0dff8562d1473
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
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.
22 #include "includes.h"
24 pstring servicesf = CONFIGFILE;
25 extern fstring global_myworkgroup;
26 extern pstring global_myname;
28 int am_parent = 1;
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;
38 #ifdef WITH_DFS
39 extern int dcelogin_atmost_once;
40 #endif /* WITH_DFS */
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)
54 return server_fd;
57 void smbd_set_server_fd(int fd)
59 server_fd = fd;
60 client_setfd(fd);
63 /****************************************************************************
64 Terminate signal.
65 ****************************************************************************/
67 SIG_ATOMIC_T got_sig_term;
69 static void sig_term(void)
71 got_sig_term = 1;
72 sys_select_signal();
75 /****************************************************************************
76 Catch a sighup.
77 ****************************************************************************/
79 SIG_ATOMIC_T reload_after_sighup;
81 static void sig_hup(int sig)
83 reload_after_sighup = 1;
84 sys_select_signal();
87 /****************************************************************************
88 Send a SIGTERM to our process group.
89 *****************************************************************************/
91 static void killkids(void)
93 if(am_parent)
94 kill(0,SIGTERM);
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
105 goes away */
106 smbd_set_server_fd(dup(0));
108 /* close our standard file descriptors */
109 close_low_fds();
111 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
112 set_socket_options(smbd_server_fd(),user_socket_options);
114 return True;
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();
125 if (!max_processes)
126 return True;
129 TDB_CONTEXT *tdb = conn_tdb_ctx();
130 int32 val;
131 if (!tdb) {
132 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
133 return False;
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) ));
140 return False;
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 ));
145 return False;
148 return True;
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];
159 fd_set listen_set;
160 int s;
161 int i;
163 if (!is_daemon) {
164 return open_sockets_inetd();
168 #ifdef HAVE_ATEXIT
170 static int atexit_set;
171 if(atexit_set == 0) {
172 atexit_set=1;
173 atexit(killkids);
176 #endif
178 /* Stop zombies */
179 CatchChild();
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 \
192 max can be %d\n",
193 num_interfaces, FD_SETSIZE));
194 return False;
197 /* Now open a listen socket for each of the
198 interfaces. */
199 for(i = 0; i < num_interfaces; i++) {
200 struct in_addr *ifip = iface_n_ip(i);
202 if(ifip == NULL) {
203 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
204 continue;
206 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
207 if(s == -1)
208 return False;
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)));
216 close(s);
217 return False;
219 FD_SET(s,&listen_set);
221 } else {
222 /* Just bind to 0.0.0.0 - accept connections
223 from anywhere. */
224 num_interfaces = 1;
226 /* open an incoming socket */
227 s = open_socket_in(SOCK_STREAM, port, 0,
228 interpret_addr(lp_socket_address()),True);
229 if (s == -1)
230 return(False);
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",
238 strerror(errno)));
239 close(s);
240 return False;
243 fd_listenset[0] = s;
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"));
250 while (1) {
251 fd_set lfds;
252 int num;
254 /* Free up temporary memory from the main smbd. */
255 lp_talloc_free();
257 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
258 message_dispatch();
260 memcpy((char *)&lfds, (char *)&listen_set,
261 sizeof(listen_set));
263 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
265 if (num == -1 && errno == EINTR) {
266 if (got_sig_term) {
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;
279 continue;
282 /* check if we need to reload services */
283 check_reload(time(NULL));
285 /* Find the sockets that are read-ready -
286 accept on these. */
287 for( ; num > 0; num--) {
288 struct sockaddr addr;
289 socklen_t in_addrlen = sizeof(addr);
291 s = -1;
292 for(i = 0; i < num_interfaces; i++) {
293 if(FD_ISSET(fd_listenset[i],&lfds)) {
294 s = fd_listenset[i];
295 /* Clear this so we don't look
296 at it again. */
297 FD_CLR(fd_listenset[i],&lfds);
298 break;
302 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
304 if (smbd_server_fd() == -1 && errno == EINTR)
305 continue;
307 if (smbd_server_fd() == -1) {
308 DEBUG(0,("open_sockets: accept: %s\n",
309 strerror(errno)));
310 continue;
313 if (smbd_server_fd() != -1 && interactive)
314 return True;
316 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
317 /* Child code ... */
319 /* close the listening socket(s) */
320 for(i = 0; i < num_interfaces; i++)
321 close(fd_listenset[i]);
323 /* close our standard file
324 descriptors */
325 close_low_fds();
326 am_parent = 0;
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 */
337 tdb_reopen_all();
339 return True;
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
366 * (ca. 100kb).
367 * */
368 force_check_log_size();
370 } /* end for num */
371 } /* end while 1 */
373 /* NOTREACHED return True; */
376 /****************************************************************************
377 Reload the services file.
378 **************************************************************************/
380 BOOL reload_services(BOOL test)
382 BOOL ret;
384 if (lp_loaded()) {
385 pstring fname;
386 pstrcpy(fname,lp_configfile());
387 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
388 pstrcpy(servicesf,fname);
389 test = False;
393 reopen_logs();
395 if (test && !lp_file_list_changed())
396 return(True);
398 lp_killunused(conn_snum_used);
400 ret = lp_load(servicesf,False,False,True);
402 load_printers();
404 /* perhaps the config filename is now set */
405 if (!test)
406 reload_services(True);
408 reopen_logs();
410 load_interfaces();
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();
420 reset_stat_cache();
422 /* this forces service parameters to be flushed */
423 set_current_service(NULL,True);
425 return(ret);
428 #if DUMP_CORE
429 /*******************************************************************
430 Prepare to dump a core file - carefully !
431 ********************************************************************/
433 static BOOL dump_core(void)
435 char *p;
436 pstring dname;
437 pstrcpy(dname,lp_logfile());
438 if ((p=strrchr(dname,'/'))) *p=0;
439 pstrcat(dname,"/corefiles");
440 mkdir(dname,0700);
441 sys_chown(dname,getuid(),getgid());
442 chmod(dname,0700);
443 if (chdir(dname)) return(False);
444 umask(~(0700));
446 #ifdef HAVE_GETRLIMIT
447 #ifdef RLIMIT_CORE
449 struct rlimit rlp;
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));
457 #endif
458 #endif
461 DEBUG(0,("Dumping core in %s\n",dname));
462 abort();
463 return(True);
465 #endif
467 /****************************************************************************
468 update the current smbd process count
469 ****************************************************************************/
471 static BOOL process_count_update_successful = False;
473 int32 increment_smbd_process_count(void)
475 int32 total_smbds;
477 if (lp_max_smbd_processes()) {
478 total_smbds = 0;
479 if (tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, 1) == -1)
480 return 1;
481 process_count_update_successful = True;
482 return total_smbds + 1;
484 return 1;
487 static void decrement_smbd_process_count(void)
489 int32 total_smbds;
491 if (lp_max_smbd_processes() && process_count_update_successful) {
492 total_smbds = 1;
493 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
497 /****************************************************************************
498 Exit the server.
499 ****************************************************************************/
501 void exit_server(const char *reason)
503 static int firsttime=1;
504 extern char *last_inbuf;
507 if (!firsttime) exit(0);
508 firsttime = 0;
510 change_to_root_user();
511 DEBUG(2,("Closing connections\n"));
513 conn_close_all();
515 invalidate_all_vuids();
517 /* delete our entry in the connections database. */
518 if (lp_status(-1))
519 yield_connection(NULL,"");
521 respond_to_all_remaining_local_messages();
522 decrement_smbd_process_count();
524 #ifdef WITH_DFS
525 if (dcelogin_atmost_once) {
526 dfs_unlogin();
528 #endif
530 if (!reason) {
531 int oldlevel = DEBUGLEVEL;
532 DEBUGLEVEL = 10;
533 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
534 if (last_inbuf)
535 show_msg(last_inbuf);
536 DEBUGLEVEL = oldlevel;
537 DEBUG(0,("===============================================================\n"));
538 #if DUMP_CORE
539 if (dump_core()) return;
540 #endif
543 locking_end();
545 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
546 exit(0);
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) {
561 char *p;
562 fstrcpy( global_myname, myhostname() );
563 p = strchr( global_myname, '.' );
564 if (p)
565 *p = 0;
568 strupper( global_myname );
570 conn_init();
572 file_init();
574 /* for RPC pipes */
575 init_rpc_pipe_hnd();
577 init_dptrs();
579 secrets_init();
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)
590 int32 total_smbds;
592 if (lp_max_smbd_processes()) {
594 /* Always add one to the smbd process count, as exit_server() always
595 * subtracts one.
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"));
601 return False;
604 total_smbds = increment_smbd_process_count();
605 return total_smbds > lp_max_smbd_processes();
607 else
608 return False;
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");
633 printf("\n");
636 /****************************************************************************
637 main program.
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;
648 int port = SMB_PORT;
649 int opt;
650 extern char *optarg;
651 pstring logfile;
653 #ifdef HAVE_SET_AUTH_PARAMETERS
654 set_auth_parameters(argc,argv);
655 #endif
657 /* this is for people who can't start the program correctly */
658 while (argc > 1 && (*argv[1] != '-')) {
659 argv++;
660 argc--;
663 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dip:h?Vaof:")) )
664 switch (opt) {
665 case 'O':
666 pstrcpy(user_socket_options,optarg);
667 break;
669 case 's':
670 pstrcpy(servicesf,optarg);
671 break;
673 case 'l':
674 specified_logfile = True;
675 slprintf(logfile, sizeof(logfile)-1, "%s/log.smbd", optarg);
676 lp_set_logfile(logfile);
677 break;
679 case 'a':
680 append_log = True;
681 break;
683 case 'o':
684 append_log = False;
685 break;
687 case 'D':
688 is_daemon = True;
689 break;
691 case 'i':
692 interactive = True;
693 break;
695 case 'd':
696 if (*optarg == 'A')
697 DEBUGLEVEL = 10000;
698 else
699 DEBUGLEVEL = atoi(optarg);
700 AllowDebugChange = False;
701 break;
703 case 'p':
704 port = atoi(optarg);
705 break;
707 case 'h':
708 case '?':
709 usage(argv[0]);
710 exit(0);
711 break;
713 case 'V':
714 printf("Version %s\n",VERSION);
715 exit(0);
716 break;
717 default:
718 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
719 usage(argv[0]);
720 exit(1);
723 #ifdef HAVE_SETLUID
724 /* needed for SecureWare on SCO */
725 setluid(0);
726 #endif
728 sec_init();
730 append_log = True;
732 TimeInit();
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);
766 #if defined(SIGFPE)
767 /* we are never interested in SIGFPE */
768 BlockSignals(True,SIGFPE);
769 #endif
771 #if defined(SIGUSR2)
772 /* We are no longer interested in USR2 */
773 BlockSignals(True,SIGUSR2);
774 #endif
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 */
784 umask(0);
786 init_sec_ctx();
787 init_conn_ctx();
789 reopen_logs();
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"));
799 exit(1);
803 * Do this before reload_services.
806 if (!reload_services(False))
807 return(-1);
809 init_structs();
811 #ifdef WITH_PROFILE
812 if (!profile_setup(False)) {
813 DEBUG(0,("ERROR: failed to setup profiling shared memory\n"));
814 return -1;
816 #endif /* WITH_PROFILE */
818 #ifdef WITH_SSL
820 extern BOOL sslEnabled;
821 sslEnabled = lp_ssl_enabled();
822 if(sslEnabled)
823 sslutil_init(True);
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)) {
834 if (!interactive)
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()
842 is_daemon = True;
845 if (is_daemon && !interactive) {
846 DEBUG( 3, ( "Becoming a daemon.\n" ) );
847 become_daemon();
850 #if HAVE_SETPGID
852 * If we're interactive we want to set our own process group for
853 * signal management.
855 if (interactive)
856 setpgid( (pid_t)0, (pid_t)0);
857 #endif
859 if (!directory_exist(lp_lockdir(), NULL))
860 mkdir(lp_lockdir(), 0755);
862 if (is_daemon)
863 pidfile_create("smbd");
865 if (!message_init())
866 exit(1);
868 /* Setup the main smbd so that we can get messages. */
869 if (lp_status(-1))
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"));
878 exit(1);
881 if (!open_sockets(is_daemon,interactive,port))
882 exit(1);
885 * Everything after this point is run after the fork().
888 if (!locking_init(0))
889 exit(1);
891 if (!print_backend_init())
892 exit(1);
894 if (!share_info_db_init())
895 exit(1);
897 if(!initialize_password_db(False))
898 exit(1);
900 /* possibly reload the services file. */
901 reload_services(True);
903 if (*lp_rootdir()) {
904 if (sys_chroot(lp_rootdir()) == 0)
905 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
908 /* Setup oplocks */
909 if (!init_oplocks())
910 exit(1);
912 /* Setup change notify */
913 if (!init_change_notify())
914 exit(1);
916 if ( smbd_process_limit() ) {
917 DEBUG( 1, ( "Connection denied from %s\n",
918 client_addr() ) );
919 exit_server("connection denied");
922 smbd_process();
924 exit_server("normal exit");
925 return(0);