add WITH_SENDFILE profiling data (from Pierre Belanger)
[Samba.git] / source / smbd / server.c
blob141053427552163e75d3fea8a94b3d662f0645f7
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 Open the socket communication.
119 ****************************************************************************/
121 static BOOL open_sockets(BOOL is_daemon,BOOL interactive, int port)
123 int num_interfaces = iface_count();
124 int fd_listenset[FD_SETSIZE];
125 fd_set listen_set;
126 int s;
127 int i;
129 if (!is_daemon) {
130 return open_sockets_inetd();
134 #ifdef HAVE_ATEXIT
136 static int atexit_set;
137 if(atexit_set == 0) {
138 atexit_set=1;
139 atexit(killkids);
142 #endif
144 /* Stop zombies */
145 CatchChild();
148 FD_ZERO(&listen_set);
150 if(lp_interfaces() && lp_bind_interfaces_only()) {
151 /* We have been given an interfaces line, and been
152 told to only bind to those interfaces. Create a
153 socket per interface and bind to only these.
156 if(num_interfaces > FD_SETSIZE) {
157 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
158 max can be %d\n",
159 num_interfaces, FD_SETSIZE));
160 return False;
163 /* Now open a listen socket for each of the
164 interfaces. */
165 for(i = 0; i < num_interfaces; i++) {
166 struct in_addr *ifip = iface_n_ip(i);
168 if(ifip == NULL) {
169 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
170 continue;
172 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
173 if(s == -1)
174 return False;
176 /* ready to listen */
177 set_socket_options(s,"SO_KEEPALIVE");
178 set_socket_options(s,user_socket_options);
180 if (listen(s, 5) == -1) {
181 DEBUG(0,("listen: %s\n",strerror(errno)));
182 close(s);
183 return False;
185 FD_SET(s,&listen_set);
187 } else {
188 /* Just bind to 0.0.0.0 - accept connections
189 from anywhere. */
190 num_interfaces = 1;
192 /* open an incoming socket */
193 s = open_socket_in(SOCK_STREAM, port, 0,
194 interpret_addr(lp_socket_address()),True);
195 if (s == -1)
196 return(False);
198 /* ready to listen */
199 set_socket_options(s,"SO_KEEPALIVE");
200 set_socket_options(s,user_socket_options);
202 if (listen(s, 5) == -1) {
203 DEBUG(0,("open_sockets: listen: %s\n",
204 strerror(errno)));
205 close(s);
206 return False;
209 fd_listenset[0] = s;
210 FD_SET(s,&listen_set);
213 /* now accept incoming connections - forking a new process
214 for each incoming connection */
215 DEBUG(2,("waiting for a connection\n"));
216 while (1) {
217 fd_set lfds;
218 int num;
220 /* Free up temporary memory from the main smbd. */
221 lp_talloc_free();
223 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
224 message_dispatch();
226 memcpy((char *)&lfds, (char *)&listen_set,
227 sizeof(listen_set));
229 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
231 if (num == -1 && errno == EINTR) {
232 if (got_sig_term) {
233 exit_server("Caught TERM signal");
236 /* check for sighup processing */
237 if (reload_after_sighup) {
238 DEBUG(0,("Got SIGHUP\n"));
239 change_to_root_user();
240 DEBUG(1,("Reloading services after SIGHUP\n"));
241 reload_services(False);
242 reload_after_sighup = False;
245 continue;
248 /* check if we need to reload services */
249 check_reload(time(NULL));
251 /* Find the sockets that are read-ready -
252 accept on these. */
253 for( ; num > 0; num--) {
254 struct sockaddr addr;
255 socklen_t in_addrlen = sizeof(addr);
257 s = -1;
258 for(i = 0; i < num_interfaces; i++) {
259 if(FD_ISSET(fd_listenset[i],&lfds)) {
260 s = fd_listenset[i];
261 /* Clear this so we don't look
262 at it again. */
263 FD_CLR(fd_listenset[i],&lfds);
264 break;
268 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
270 if (smbd_server_fd() == -1 && errno == EINTR)
271 continue;
273 if (smbd_server_fd() == -1) {
274 DEBUG(0,("open_sockets: accept: %s\n",
275 strerror(errno)));
276 continue;
279 if (smbd_server_fd() != -1 && interactive)
280 return True;
282 if (smbd_server_fd() != -1 && sys_fork()==0) {
283 /* Child code ... */
285 /* close the listening socket(s) */
286 for(i = 0; i < num_interfaces; i++)
287 close(fd_listenset[i]);
289 /* close our standard file
290 descriptors */
291 close_low_fds();
292 am_parent = 0;
294 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
295 set_socket_options(smbd_server_fd(),user_socket_options);
297 /* Reset global variables in util.c so
298 that client substitutions will be
299 done correctly in the process. */
300 reset_globals_after_fork();
302 /* tdb needs special fork handling */
303 tdb_reopen_all();
305 return True;
307 /* The parent doesn't need this socket */
308 close(smbd_server_fd());
310 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
311 Clear the closed fd info out of server_fd --
312 and more importantly, out of client_fd in
313 util_sock.c, to avoid a possible
314 getpeername failure if we reopen the logs
315 and use %I in the filename.
318 smbd_set_server_fd(-1);
320 /* Force parent to check log size after
321 * spawning child. Fix from
322 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
323 * parent smbd will log to logserver.smb. It
324 * writes only two messages for each child
325 * started/finished. But each child writes,
326 * say, 50 messages also in logserver.smb,
327 * begining with the debug_count of the
328 * parent, before the child opens its own log
329 * file logserver.client. In a worst case
330 * scenario the size of logserver.smb would be
331 * checked after about 50*50=2500 messages
332 * (ca. 100kb).
333 * */
334 force_check_log_size();
336 } /* end for num */
337 } /* end while 1 */
339 /* NOTREACHED return True; */
342 /****************************************************************************
343 Reload the services file.
344 **************************************************************************/
346 BOOL reload_services(BOOL test)
348 BOOL ret;
350 if (lp_loaded()) {
351 pstring fname;
352 pstrcpy(fname,lp_configfile());
353 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
354 pstrcpy(servicesf,fname);
355 test = False;
359 reopen_logs();
361 if (test && !lp_file_list_changed())
362 return(True);
364 lp_killunused(conn_snum_used);
366 ret = lp_load(servicesf,False,False,True);
368 load_printers();
370 /* perhaps the config filename is now set */
371 if (!test)
372 reload_services(True);
374 reopen_logs();
376 load_interfaces();
379 if (smbd_server_fd() != -1) {
380 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
381 set_socket_options(smbd_server_fd(),user_socket_options);
385 mangle_reset_cache();
386 reset_stat_cache();
388 /* this forces service parameters to be flushed */
389 set_current_service(NULL,True);
391 return(ret);
394 #if DUMP_CORE
395 /*******************************************************************
396 Prepare to dump a core file - carefully !
397 ********************************************************************/
399 static BOOL dump_core(void)
401 char *p;
402 pstring dname;
403 pstrcpy(dname,lp_logfile());
404 if ((p=strrchr(dname,'/'))) *p=0;
405 pstrcat(dname,"/corefiles");
406 mkdir(dname,0700);
407 sys_chown(dname,getuid(),getgid());
408 chmod(dname,0700);
409 if (chdir(dname)) return(False);
410 umask(~(0700));
412 #ifdef HAVE_GETRLIMIT
413 #ifdef RLIMIT_CORE
415 struct rlimit rlp;
416 getrlimit(RLIMIT_CORE, &rlp);
417 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
418 setrlimit(RLIMIT_CORE, &rlp);
419 getrlimit(RLIMIT_CORE, &rlp);
420 DEBUG(3,("Core limits now %d %d\n",
421 (int)rlp.rlim_cur,(int)rlp.rlim_max));
423 #endif
424 #endif
427 DEBUG(0,("Dumping core in %s\n",dname));
428 abort();
429 return(True);
431 #endif
433 /****************************************************************************
434 update the current smbd process count
435 ****************************************************************************/
437 static void decrement_smbd_process_count(void)
439 int32 total_smbds;
441 if (lp_max_smbd_processes()) {
442 total_smbds = 0;
443 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
447 /****************************************************************************
448 Exit the server.
449 ****************************************************************************/
451 void exit_server(char *reason)
453 static int firsttime=1;
454 extern char *last_inbuf;
457 if (!firsttime) exit(0);
458 firsttime = 0;
460 change_to_root_user();
461 DEBUG(2,("Closing connections\n"));
463 conn_close_all();
465 invalidate_all_vuids();
467 /* delete our entry in the connections database. */
468 if (lp_status(-1))
469 yield_connection(NULL,"");
471 respond_to_all_remaining_local_messages();
472 decrement_smbd_process_count();
474 #ifdef WITH_DFS
475 if (dcelogin_atmost_once) {
476 dfs_unlogin();
478 #endif
480 if (!reason) {
481 int oldlevel = DEBUGLEVEL;
482 DEBUGLEVEL = 10;
483 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
484 if (last_inbuf)
485 show_msg(last_inbuf);
486 DEBUGLEVEL = oldlevel;
487 DEBUG(0,("===============================================================\n"));
488 #if DUMP_CORE
489 if (dump_core()) return;
490 #endif
493 locking_end();
495 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
496 exit(0);
499 /****************************************************************************
500 Initialise connect, service and file structs.
501 ****************************************************************************/
503 static void init_structs(void )
506 * Set the machine NETBIOS name if not already
507 * set from the config file.
510 if (!*global_myname) {
511 char *p;
512 fstrcpy( global_myname, myhostname() );
513 p = strchr( global_myname, '.' );
514 if (p)
515 *p = 0;
518 strupper( global_myname );
520 conn_init();
522 file_init();
524 /* for RPC pipes */
525 init_rpc_pipe_hnd();
527 init_dptrs();
529 secrets_init();
532 /****************************************************************************
533 Usage on the program.
534 ****************************************************************************/
536 static void usage(char *pname)
539 printf("Usage: %s [-DaioPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
540 printf(" [-O socket options] [-s services file]\n");
541 printf("\t-D Become a daemon (default)\n");
542 printf("\t-a Append to log file (default)\n");
543 printf("\t-i Run interactive (not a daemon)\n");
544 printf("\t-o Overwrite log file, don't append\n");
545 printf("\t-h Print usage\n");
546 printf("\t-? Print usage\n");
547 printf("\t-V Print version\n");
548 printf("\t-d debuglevel Set the debuglevel\n");
549 printf("\t-l log basename. Basename for log/debug files\n");
550 printf("\t-p port Listen on the specified port\n");
551 printf("\t-O socket options Socket options\n");
552 printf("\t-s services file. Filename of services file\n");
553 printf("\n");
556 /****************************************************************************
557 main program.
558 ****************************************************************************/
560 int main(int argc,char *argv[])
562 extern BOOL append_log;
563 extern BOOL AllowDebugChange;
564 /* shall I run as a daemon */
565 BOOL is_daemon = False;
566 BOOL interactive = False;
567 BOOL specified_logfile = False;
568 int port = SMB_PORT;
569 int opt;
570 extern char *optarg;
571 pstring logfile;
573 #ifdef HAVE_SET_AUTH_PARAMETERS
574 set_auth_parameters(argc,argv);
575 #endif
577 /* this is for people who can't start the program correctly */
578 while (argc > 1 && (*argv[1] != '-')) {
579 argv++;
580 argc--;
583 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dip:h?Vaof:")) )
584 switch (opt) {
585 case 'O':
586 pstrcpy(user_socket_options,optarg);
587 break;
589 case 's':
590 pstrcpy(servicesf,optarg);
591 break;
593 case 'l':
594 specified_logfile = True;
595 slprintf(logfile, sizeof(logfile)-1, "%s/log.smbd", optarg);
596 lp_set_logfile(logfile);
597 break;
599 case 'a':
600 append_log = True;
601 break;
603 case 'o':
604 append_log = False;
605 break;
607 case 'D':
608 is_daemon = True;
609 break;
611 case 'i':
612 interactive = True;
613 break;
615 case 'd':
616 if (*optarg == 'A')
617 DEBUGLEVEL = 10000;
618 else
619 DEBUGLEVEL = atoi(optarg);
620 AllowDebugChange = False;
621 break;
623 case 'p':
624 port = atoi(optarg);
625 break;
627 case 'h':
628 case '?':
629 usage(argv[0]);
630 exit(0);
631 break;
633 case 'V':
634 printf("Version %s\n",VERSION);
635 exit(0);
636 break;
637 default:
638 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
639 usage(argv[0]);
640 exit(1);
643 #ifdef HAVE_SETLUID
644 /* needed for SecureWare on SCO */
645 setluid(0);
646 #endif
648 sec_init();
650 append_log = True;
652 TimeInit();
654 if(!specified_logfile) {
655 slprintf(logfile, sizeof(logfile)-1, "%s/log.smbd", LOGFILEBASE);
656 lp_set_logfile(logfile);
659 pstrcpy(remote_machine, "smbd");
661 setup_logging(argv[0],interactive);
663 charset_initialise();
665 /* we want to re-seed early to prevent time delays causing
666 client problems at a later date. (tridge) */
667 generate_random_buffer(NULL, 0, False);
669 /* make absolutely sure we run as root - to handle cases where people
670 are crazy enough to have it setuid */
672 gain_root_privilege();
673 gain_root_group_privilege();
675 fault_setup((void (*)(void *))exit_server);
676 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
677 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
679 /* we are never interested in SIGPIPE */
680 BlockSignals(True,SIGPIPE);
682 #if defined(SIGFPE)
683 /* we are never interested in SIGFPE */
684 BlockSignals(True,SIGFPE);
685 #endif
687 #if defined(SIGUSR2)
688 /* We are no longer interested in USR2 */
689 BlockSignals(True,SIGUSR2);
690 #endif
692 /* POSIX demands that signals are inherited. If the invoking process has
693 * these signals masked, we will have problems, as we won't recieve them. */
694 BlockSignals(False, SIGHUP);
695 BlockSignals(False, SIGUSR1);
696 BlockSignals(False, SIGTERM);
698 /* we want total control over the permissions on created files,
699 so set our umask to 0 */
700 umask(0);
702 init_sec_ctx();
703 init_conn_ctx();
705 reopen_logs();
707 DEBUG(0,( "smbd version %s started.\n", VERSION));
708 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
710 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
711 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
713 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
714 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
715 exit(1);
719 * Do this before reload_services.
722 if (!reload_services(False))
723 return(-1);
725 init_structs();
727 #ifdef WITH_PROFILE
728 if (!profile_setup(False)) {
729 DEBUG(0,("ERROR: failed to setup profiling shared memory\n"));
730 return -1;
732 #endif /* WITH_PROFILE */
734 #ifdef WITH_SSL
736 extern BOOL sslEnabled;
737 sslEnabled = lp_ssl_enabled();
738 if(sslEnabled)
739 sslutil_init(True);
741 #endif /* WITH_SSL */
743 codepage_initialise(lp_client_code_page());
745 fstrcpy(global_myworkgroup, lp_workgroup());
747 DEBUG(3,( "loaded services\n"));
749 if (!is_daemon && !is_a_socket(0)) {
750 if (!interactive)
751 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
754 * Setting is_daemon here prevents us from eventually calling
755 * the open_sockets_inetd()
758 is_daemon = True;
761 if (is_daemon && !interactive) {
762 DEBUG( 3, ( "Becoming a daemon.\n" ) );
763 become_daemon();
766 #if HAVE_SETPGID
768 * If we're interactive we want to set our own process group for
769 * signal management.
771 if (interactive)
772 setpgid( (pid_t)0, (pid_t)0);
773 #endif
775 if (!directory_exist(lp_lockdir(), NULL))
776 mkdir(lp_lockdir(), 0755);
778 if (is_daemon)
779 pidfile_create("smbd");
781 if (!message_init())
782 exit(1);
784 /* Setup the main smbd so that we can get messages. */
785 if (lp_status(-1))
786 claim_connection(NULL,"",0,True);
788 /* Attempt to migrate from an old 2.0.x machine account file. */
789 if (!migrate_from_old_password_file(global_myworkgroup))
790 DEBUG(0,("Failed to migrate from old MAC file.\n"));
792 if(!pdb_generate_sam_sid()) {
793 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
794 exit(1);
797 if (!open_sockets(is_daemon,interactive,port))
798 exit(1);
801 * Everything after this point is run after the fork().
804 if (!locking_init(0))
805 exit(1);
807 if (!print_backend_init())
808 exit(1);
810 if (!share_info_db_init())
811 exit(1);
813 if(!initialize_password_db(False))
814 exit(1);
816 /* possibly reload the services file. */
817 reload_services(True);
819 if (*lp_rootdir()) {
820 if (sys_chroot(lp_rootdir()) == 0)
821 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
824 /* Setup oplocks */
825 if (!init_oplocks())
826 exit(1);
828 /* Setup change notify */
829 if (!init_change_notify())
830 exit(1);
832 smbd_process();
834 exit_server("normal exit");
835 return(0);