Add testacl.c ... from Derrell Lipman.
[Samba.git] / source3 / smbd / server.c
blob89d6f92e9831b3d051581baed0a789ad3887fef8
1 /*
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-2003
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.
23 #include "includes.h"
25 int am_parent = 1;
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;
37 #ifdef WITH_DFS
38 extern int dcelogin_atmost_once;
39 #endif /* WITH_DFS */
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)
51 return server_fd;
54 static void smbd_set_server_fd(int fd)
56 server_fd = fd;
57 client_setfd(fd);
60 /****************************************************************************
61 Terminate signal.
62 ****************************************************************************/
64 static void sig_term(void)
66 got_sig_term = 1;
67 sys_select_signal();
70 /****************************************************************************
71 Catch a sighup.
72 ****************************************************************************/
74 static void sig_hup(int sig)
76 reload_after_sighup = 1;
77 sys_select_signal();
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
91 somewhere else.
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
102 somewhere else.
103 ****************************************************************************/
105 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
107 uint32 low_serial;
109 if (len != sizeof(uint32))
110 return;
112 low_serial = *((uint32 *)buf);
114 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
115 low_serial));
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
126 goes away */
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);
135 return True;
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 Have we reached the process limit ?
146 ****************************************************************************/
148 BOOL allowable_number_of_smbd_processes(void)
150 int max_processes = lp_max_smbd_processes();
152 if (!max_processes)
153 return True;
156 TDB_CONTEXT *tdb = conn_tdb_ctx();
157 int32 val;
158 if (!tdb) {
159 DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
160 return False;
163 val = tdb_fetch_int32(tdb, "INFO/total_smbds");
164 if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
165 DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
166 tdb_errorstr(tdb) ));
167 return False;
169 if (val > max_processes) {
170 DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
171 val, max_processes ));
172 return False;
175 return True;
178 /****************************************************************************
179 Open the socket communication.
180 ****************************************************************************/
182 static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
184 int num_interfaces = iface_count();
185 int num_sockets = 0;
186 int fd_listenset[FD_SETSIZE];
187 fd_set listen_set;
188 int s;
189 int i;
190 char *ports;
192 if (!is_daemon) {
193 return open_sockets_inetd();
197 #ifdef HAVE_ATEXIT
199 static int atexit_set;
200 if(atexit_set == 0) {
201 atexit_set=1;
202 atexit(killkids);
205 #endif
207 /* Stop zombies */
208 CatchChild();
210 FD_ZERO(&listen_set);
212 /* use a reasonable default set of ports - listing on 445 and 139 */
213 if (!smb_ports) {
214 ports = lp_smb_ports();
215 if (!ports || !*ports) {
216 ports = smb_xstrdup(SMB_PORTS);
217 } else {
218 ports = smb_xstrdup(ports);
220 } else {
221 ports = smb_xstrdup(smb_ports);
224 if (lp_interfaces() && lp_bind_interfaces_only()) {
225 /* We have been given an interfaces line, and been
226 told to only bind to those interfaces. Create a
227 socket per interface and bind to only these.
230 /* Now open a listen socket for each of the
231 interfaces. */
232 for(i = 0; i < num_interfaces; i++) {
233 struct in_addr *ifip = iface_n_ip(i);
234 fstring tok;
235 const char *ptr;
237 if(ifip == NULL) {
238 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
239 continue;
242 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
243 unsigned port = atoi(tok);
244 if (port == 0) continue;
245 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
246 if(s == -1)
247 return False;
249 /* ready to listen */
250 set_socket_options(s,"SO_KEEPALIVE");
251 set_socket_options(s,user_socket_options);
253 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
254 DEBUG(0,("listen: %s\n",strerror(errno)));
255 close(s);
256 return False;
258 FD_SET(s,&listen_set);
260 num_sockets++;
261 if (num_sockets >= FD_SETSIZE) {
262 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
263 return False;
267 } else {
268 /* Just bind to 0.0.0.0 - accept connections
269 from anywhere. */
271 fstring tok;
272 const char *ptr;
274 num_interfaces = 1;
276 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
277 unsigned port = atoi(tok);
278 if (port == 0) continue;
279 /* open an incoming socket */
280 s = open_socket_in(SOCK_STREAM, port, 0,
281 interpret_addr(lp_socket_address()),True);
282 if (s == -1)
283 return(False);
285 /* ready to listen */
286 set_socket_options(s,"SO_KEEPALIVE");
287 set_socket_options(s,user_socket_options);
289 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
290 DEBUG(0,("open_sockets_smbd: listen: %s\n",
291 strerror(errno)));
292 close(s);
293 return False;
296 fd_listenset[num_sockets] = s;
297 FD_SET(s,&listen_set);
299 num_sockets++;
301 if (num_sockets >= FD_SETSIZE) {
302 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
303 return False;
308 SAFE_FREE(ports);
310 /* Listen to messages */
312 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
313 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
314 message_register(MSG_SHUTDOWN, msg_exit_server);
316 /* now accept incoming connections - forking a new process
317 for each incoming connection */
318 DEBUG(2,("waiting for a connection\n"));
319 while (1) {
320 fd_set lfds;
321 int num;
323 /* Free up temporary memory from the main smbd. */
324 lp_talloc_free();
326 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
327 message_dispatch();
329 memcpy((char *)&lfds, (char *)&listen_set,
330 sizeof(listen_set));
332 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
334 if (num == -1 && errno == EINTR) {
335 if (got_sig_term) {
336 exit_server("Caught TERM signal");
339 /* check for sighup processing */
340 if (reload_after_sighup) {
341 change_to_root_user();
342 DEBUG(1,("Reloading services after SIGHUP\n"));
343 reload_services(False);
344 reload_after_sighup = 0;
347 continue;
350 /* check if we need to reload services */
351 check_reload(time(NULL));
353 /* Find the sockets that are read-ready -
354 accept on these. */
355 for( ; num > 0; num--) {
356 struct sockaddr addr;
357 socklen_t in_addrlen = sizeof(addr);
359 s = -1;
360 for(i = 0; i < num_sockets; i++) {
361 if(FD_ISSET(fd_listenset[i],&lfds)) {
362 s = fd_listenset[i];
363 /* Clear this so we don't look
364 at it again. */
365 FD_CLR(fd_listenset[i],&lfds);
366 break;
370 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
372 if (smbd_server_fd() == -1 && errno == EINTR)
373 continue;
375 if (smbd_server_fd() == -1) {
376 DEBUG(0,("open_sockets_smbd: accept: %s\n",
377 strerror(errno)));
378 continue;
381 if (smbd_server_fd() != -1 && interactive)
382 return True;
384 if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
385 /* Child code ... */
387 /* close the listening socket(s) */
388 for(i = 0; i < num_sockets; i++)
389 close(fd_listenset[i]);
391 /* close our standard file
392 descriptors */
393 close_low_fds(False);
394 am_parent = 0;
396 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
397 set_socket_options(smbd_server_fd(),user_socket_options);
399 /* this is needed so that we get decent entries
400 in smbstatus for port 445 connects */
401 set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
403 /* Reset global variables in util.c so
404 that client substitutions will be
405 done correctly in the process. */
406 reset_globals_after_fork();
408 /* tdb needs special fork handling */
409 if (tdb_reopen_all() == -1) {
410 DEBUG(0,("tdb_reopen_all failed.\n"));
411 return False;
414 return True;
416 /* The parent doesn't need this socket */
417 close(smbd_server_fd());
419 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
420 Clear the closed fd info out of server_fd --
421 and more importantly, out of client_fd in
422 util_sock.c, to avoid a possible
423 getpeername failure if we reopen the logs
424 and use %I in the filename.
427 smbd_set_server_fd(-1);
429 /* Force parent to check log size after
430 * spawning child. Fix from
431 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
432 * parent smbd will log to logserver.smb. It
433 * writes only two messages for each child
434 * started/finished. But each child writes,
435 * say, 50 messages also in logserver.smb,
436 * begining with the debug_count of the
437 * parent, before the child opens its own log
438 * file logserver.client. In a worst case
439 * scenario the size of logserver.smb would be
440 * checked after about 50*50=2500 messages
441 * (ca. 100kb).
442 * */
443 force_check_log_size();
445 } /* end for num */
446 } /* end while 1 */
448 /* NOTREACHED return True; */
451 /****************************************************************************
452 Reload the services file.
453 **************************************************************************/
455 BOOL reload_services(BOOL test)
457 BOOL ret;
459 if (lp_loaded()) {
460 pstring fname;
461 pstrcpy(fname,lp_configfile());
462 if (file_exist(fname, NULL) &&
463 !strcsequal(fname, dyn_CONFIGFILE)) {
464 pstrcpy(dyn_CONFIGFILE, fname);
465 test = False;
469 reopen_logs();
471 if (test && !lp_file_list_changed())
472 return(True);
474 lp_killunused(conn_snum_used);
476 ret = lp_load(dyn_CONFIGFILE, False, False, True);
478 load_printers();
480 /* perhaps the config filename is now set */
481 if (!test)
482 reload_services(True);
484 reopen_logs();
486 load_interfaces();
489 if (smbd_server_fd() != -1) {
490 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
491 set_socket_options(smbd_server_fd(), user_socket_options);
495 mangle_reset_cache();
496 reset_stat_cache();
498 /* this forces service parameters to be flushed */
499 set_current_service(NULL,True);
501 return(ret);
504 #if DUMP_CORE
505 /*******************************************************************
506 prepare to dump a core file - carefully!
507 ********************************************************************/
508 static BOOL dump_core(void)
510 char *p;
511 pstring dname;
513 pstrcpy(dname,lp_logfile());
514 if ((p=strrchr_m(dname,'/'))) *p=0;
515 pstrcat(dname,"/corefiles");
516 mkdir(dname,0700);
517 sys_chown(dname,getuid(),getgid());
518 chmod(dname,0700);
519 if (chdir(dname)) return(False);
520 umask(~(0700));
522 #ifdef HAVE_GETRLIMIT
523 #ifdef RLIMIT_CORE
525 struct rlimit rlp;
526 getrlimit(RLIMIT_CORE, &rlp);
527 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
528 setrlimit(RLIMIT_CORE, &rlp);
529 getrlimit(RLIMIT_CORE, &rlp);
530 DEBUG(3,("Core limits now %d %d\n",
531 (int)rlp.rlim_cur,(int)rlp.rlim_max));
533 #endif
534 #endif
537 DEBUG(0,("Dumping core in %s\n", dname));
538 abort();
539 return(True);
541 #endif
543 /****************************************************************************
544 Exit the server.
545 ****************************************************************************/
547 void exit_server(const char *reason)
549 static int firsttime=1;
550 extern char *last_inbuf;
551 extern struct auth_context *negprot_global_auth_context;
553 if (!firsttime)
554 exit(0);
555 firsttime = 0;
557 change_to_root_user();
558 DEBUG(2,("Closing connections\n"));
560 if (negprot_global_auth_context) {
561 (negprot_global_auth_context->free)(&negprot_global_auth_context);
564 conn_close_all();
566 invalidate_all_vuids();
568 print_notify_send_messages(3); /* 3 second timeout. */
570 /* run all registered exit events */
571 smb_run_exit_events();
573 /* delete our entry in the connections database. */
574 yield_connection(NULL,"");
576 respond_to_all_remaining_local_messages();
577 decrement_smbd_process_count();
579 #ifdef WITH_DFS
580 if (dcelogin_atmost_once) {
581 dfs_unlogin();
583 #endif
585 if (!reason) {
586 int oldlevel = DEBUGLEVEL;
587 DEBUGLEVEL = 10;
588 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
589 if (last_inbuf)
590 show_msg(last_inbuf);
591 DEBUGLEVEL = oldlevel;
592 DEBUG(0,("===============================================================\n"));
593 #if DUMP_CORE
594 if (dump_core()) return;
595 #endif
598 locking_end();
599 printing_end();
601 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
602 exit(0);
605 /****************************************************************************
606 Initialise connect, service and file structs.
607 ****************************************************************************/
609 static BOOL init_structs(void )
612 * Set the machine NETBIOS name if not already
613 * set from the config file.
616 if (!init_names())
617 return False;
619 conn_init();
621 file_init();
623 /* for RPC pipes */
624 init_rpc_pipe_hnd();
626 init_dptrs();
628 secrets_init();
630 return True;
633 /****************************************************************************
634 main program.
635 ****************************************************************************/
637 /* Declare prototype for build_options() to avoid having to run it through
638 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
639 prototype generation system is too complicated. */
641 void build_options(BOOL screen);
643 int main(int argc,const char *argv[])
645 /* shall I run as a daemon */
646 static BOOL is_daemon = False;
647 static BOOL interactive = False;
648 static BOOL Fork = True;
649 static BOOL log_stdout = False;
650 static char *ports = NULL;
651 int opt;
652 poptContext pc;
654 struct poptOption long_options[] = {
655 POPT_AUTOHELP
656 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
657 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
658 {"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
659 {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
660 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
661 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
662 POPT_COMMON_SAMBA
663 { NULL }
666 #ifdef HAVE_SET_AUTH_PARAMETERS
667 set_auth_parameters(argc,argv);
668 #endif
670 pc = poptGetContext("smbd", argc, argv, long_options, 0);
672 while((opt = poptGetNextOpt(pc)) != -1) {
673 switch (opt) {
674 case 'b':
675 build_options(True); /* Display output to screen as well as debug */
676 exit(0);
677 break;
681 poptFreeContext(pc);
683 #ifdef HAVE_SETLUID
684 /* needed for SecureWare on SCO */
685 setluid(0);
686 #endif
688 sec_init();
690 load_case_tables();
692 set_remote_machine_name("smbd", False);
694 if (interactive) {
695 Fork = False;
696 log_stdout = True;
699 if (log_stdout && Fork) {
700 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
701 exit(1);
704 setup_logging(argv[0],log_stdout);
706 /* we want to re-seed early to prevent time delays causing
707 client problems at a later date. (tridge) */
708 generate_random_buffer(NULL, 0, False);
710 /* make absolutely sure we run as root - to handle cases where people
711 are crazy enough to have it setuid */
713 gain_root_privilege();
714 gain_root_group_privilege();
716 fault_setup((void (*)(void *))exit_server);
717 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
718 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
720 /* we are never interested in SIGPIPE */
721 BlockSignals(True,SIGPIPE);
723 #if defined(SIGFPE)
724 /* we are never interested in SIGFPE */
725 BlockSignals(True,SIGFPE);
726 #endif
728 #if defined(SIGUSR2)
729 /* We are no longer interested in USR2 */
730 BlockSignals(True,SIGUSR2);
731 #endif
733 /* POSIX demands that signals are inherited. If the invoking process has
734 * these signals masked, we will have problems, as we won't recieve them. */
735 BlockSignals(False, SIGHUP);
736 BlockSignals(False, SIGUSR1);
737 BlockSignals(False, SIGTERM);
739 /* we want total control over the permissions on created files,
740 so set our umask to 0 */
741 umask(0);
743 init_sec_ctx();
745 reopen_logs();
747 DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
748 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2003\n"));
750 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
751 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
753 /* Output the build options to the debug log */
754 build_options(False);
756 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
757 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
758 exit(1);
762 * Do this before reload_services.
765 if (!reload_services(False))
766 return(-1);
768 init_structs();
770 #ifdef WITH_PROFILE
771 if (!profile_setup(False)) {
772 DEBUG(0,("ERROR: failed to setup profiling\n"));
773 return -1;
775 #endif
777 DEBUG(3,( "loaded services\n"));
779 if (!is_daemon && !is_a_socket(0)) {
780 if (!interactive)
781 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
784 * Setting is_daemon here prevents us from eventually calling
785 * the open_sockets_inetd()
788 is_daemon = True;
791 if (is_daemon && !interactive) {
792 DEBUG( 3, ( "Becoming a daemon.\n" ) );
793 become_daemon(Fork);
796 #if HAVE_SETPGID
798 * If we're interactive we want to set our own process group for
799 * signal management.
801 if (interactive)
802 setpgid( (pid_t)0, (pid_t)0);
803 #endif
805 if (!directory_exist(lp_lockdir(), NULL))
806 mkdir(lp_lockdir(), 0755);
808 if (is_daemon)
809 pidfile_create("smbd");
811 if (!message_init())
812 exit(1);
814 if (!print_backend_init())
815 exit(1);
817 /* Setup the main smbd so that we can get messages. */
818 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
821 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
822 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
823 smbd PROCESSES THAT NEVER DIE
824 start_background_queue();
827 if (!open_sockets_smbd(is_daemon, interactive, ports))
828 exit(1);
831 * everything after this point is run after the fork()
834 namecache_enable();
836 if (!locking_init(0))
837 exit(1);
839 if (!share_info_db_init())
840 exit(1);
842 if (!init_registry())
843 exit(1);
845 /* Initialise the password backed before the global_sam_sid
846 to ensure that we fetch from ldap before we make a domain sid up */
848 if(!initialize_password_db(False))
849 exit(1);
851 if(!get_global_sam_sid()) {
852 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
853 exit(1);
856 static_init_rpc;
858 init_modules();
860 /* possibly reload the services file. */
861 reload_services(True);
863 if (!init_account_policy()) {
864 DEBUG(0,("Could not open account policy tdb.\n"));
865 exit(1);
868 if (*lp_rootdir()) {
869 if (sys_chroot(lp_rootdir()) == 0)
870 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
873 /* Setup oplocks */
874 if (!init_oplocks())
875 exit(1);
877 /* Setup change notify */
878 if (!init_change_notify())
879 exit(1);
881 /* re-initialise the timezone */
882 TimeInit();
884 /* register our message handlers */
885 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
887 smbd_process();
889 namecache_shutdown();
890 exit_server("normal exit");
891 return(0);