preparing for release of 3.0-alpha18
[Samba.git] / source / smbd / server.c
blob6f0d0238b0d907c73d2ae7410dcdb40aa4aca0f4
1 /*
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.
22 #include "includes.h"
24 extern fstring global_myworkgroup;
25 extern pstring global_myname;
27 int am_parent = 1;
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;
37 #ifdef WITH_DFS
38 extern int dcelogin_atmost_once;
39 #endif /* WITH_DFS */
41 extern fstring remote_machine;
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)
53 return server_fd;
56 static void smbd_set_server_fd(int fd)
58 server_fd = fd;
59 client_setfd(fd);
62 /****************************************************************************
63 Terminate signal.
64 ****************************************************************************/
66 SIG_ATOMIC_T got_sig_term = 0;
68 static void sig_term(void)
70 got_sig_term = 1;
71 sys_select_signal();
74 /****************************************************************************
75 Catch a sighup.
76 ****************************************************************************/
78 SIG_ATOMIC_T reload_after_sighup = 0;
80 static void sig_hup(int sig)
82 reload_after_sighup = 1;
83 sys_select_signal();
86 /****************************************************************************
87 Send a SIGTERM to our process group.
88 *****************************************************************************/
90 static void killkids(void)
92 if(am_parent) kill(0,SIGTERM);
95 /****************************************************************************
96 Process a sam sync message - not sure whether to do this here or
97 somewhere else.
98 ****************************************************************************/
100 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
101 void *UNUSED(buf), size_t UNUSED(len))
103 DEBUG(10, ("** sam sync message received, ignoring\n"));
106 /****************************************************************************
107 Process a sam sync replicate message - not sure whether to do this here or
108 somewhere else.
109 ****************************************************************************/
111 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
113 uint32 low_serial;
115 if (len != sizeof(uint32))
116 return;
118 low_serial = *((uint32 *)buf);
120 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
121 low_serial));
124 /****************************************************************************
125 Open the socket communication - inetd.
126 ****************************************************************************/
128 static BOOL open_sockets_inetd(void)
130 /* Started from inetd. fd 0 is the socket. */
131 /* We will abort gracefully when the client or remote system
132 goes away */
133 smbd_set_server_fd(dup(0));
135 /* close our standard file descriptors */
136 close_low_fds();
138 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
139 set_socket_options(smbd_server_fd(), user_socket_options);
141 return True;
144 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
146 exit_server("Got a SHUTDOWN message");
150 /****************************************************************************
151 Open the socket communication.
152 ****************************************************************************/
154 static BOOL open_sockets(BOOL is_daemon,int port)
156 int num_interfaces = iface_count();
157 int fd_listenset[FD_SETSIZE];
158 fd_set listen_set;
159 int s;
160 int i;
162 if (!is_daemon) {
163 return open_sockets_inetd();
167 #ifdef HAVE_ATEXIT
169 static int atexit_set;
170 if(atexit_set == 0) {
171 atexit_set=1;
172 atexit(killkids);
175 #endif
177 /* Stop zombies */
178 CatchChild();
181 FD_ZERO(&listen_set);
183 if(lp_interfaces() && lp_bind_interfaces_only()) {
184 /* We have been given an interfaces line, and been
185 told to only bind to those interfaces. Create a
186 socket per interface and bind to only these.
189 if(num_interfaces > FD_SETSIZE) {
190 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
191 max can be %d\n",
192 num_interfaces, FD_SETSIZE));
193 return False;
196 /* Now open a listen socket for each of the
197 interfaces. */
198 for(i = 0; i < num_interfaces; i++) {
199 struct in_addr *ifip = iface_n_ip(i);
201 if(ifip == NULL) {
202 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
203 continue;
205 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
206 if(s == -1)
207 return False;
209 /* ready to listen */
210 set_socket_options(s,"SO_KEEPALIVE");
211 set_socket_options(s,user_socket_options);
213 if (listen(s, 5) == -1) {
214 DEBUG(0,("listen: %s\n",strerror(errno)));
215 close(s);
216 return False;
218 FD_SET(s,&listen_set);
220 } else {
221 /* Just bind to 0.0.0.0 - accept connections
222 from anywhere. */
223 num_interfaces = 1;
225 /* open an incoming socket */
226 s = open_socket_in(SOCK_STREAM, port, 0,
227 interpret_addr(lp_socket_address()),True);
228 if (s == -1)
229 return(False);
231 /* ready to listen */
232 set_socket_options(s,"SO_KEEPALIVE");
233 set_socket_options(s,user_socket_options);
235 if (listen(s, 5) == -1) {
236 DEBUG(0,("open_sockets: listen: %s\n",
237 strerror(errno)));
238 close(s);
239 return False;
242 fd_listenset[0] = s;
243 FD_SET(s,&listen_set);
246 /* Listen to messages */
248 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
249 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
250 message_register(MSG_SHUTDOWN, msg_exit_server);
252 /* now accept incoming connections - forking a new process
253 for each incoming connection */
254 DEBUG(2,("waiting for a connection\n"));
255 while (1) {
256 fd_set lfds;
257 int num;
259 /* Free up temporary memory from the main smbd. */
260 lp_talloc_free();
262 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
263 message_dispatch();
265 memcpy((char *)&lfds, (char *)&listen_set,
266 sizeof(listen_set));
268 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
270 if (num == -1 && errno == EINTR) {
271 if (got_sig_term) {
272 exit_server("Caught TERM signal");
275 /* check for sighup processing */
276 if (reload_after_sighup) {
277 change_to_root_user();
278 DEBUG(1,("Reloading services after SIGHUP\n"));
279 reload_services(False);
280 reload_after_sighup = 0;
283 continue;
286 /* check if we need to reload services */
287 check_reload(time(NULL));
289 /* Find the sockets that are read-ready -
290 accept on these. */
291 for( ; num > 0; num--) {
292 struct sockaddr addr;
293 socklen_t in_addrlen = sizeof(addr);
295 s = -1;
296 for(i = 0; i < num_interfaces; i++) {
297 if(FD_ISSET(fd_listenset[i],&lfds)) {
298 s = fd_listenset[i];
299 /* Clear this so we don't look
300 at it again. */
301 FD_CLR(fd_listenset[i],&lfds);
302 break;
306 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
308 if (smbd_server_fd() == -1 && errno == EINTR)
309 continue;
311 if (smbd_server_fd() == -1) {
312 DEBUG(0,("open_sockets: accept: %s\n",
313 strerror(errno)));
314 continue;
317 if (smbd_server_fd() != -1 && sys_fork()==0) {
318 /* Child code ... */
320 /* close the listening socket(s) */
321 for(i = 0; i < num_interfaces; i++)
322 close(fd_listenset[i]);
324 /* close our standard file
325 descriptors */
326 close_low_fds();
327 am_parent = 0;
329 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
330 set_socket_options(smbd_server_fd(),user_socket_options);
332 /* Reset global variables in util.c so
333 that client substitutions will be
334 done correctly in the process. */
335 reset_globals_after_fork();
337 /* tdb needs special fork handling */
338 tdb_reopen_all();
340 return True;
342 /* The parent doesn't need this socket */
343 close(smbd_server_fd());
345 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
346 Clear the closed fd info out of server_fd --
347 and more importantly, out of client_fd in
348 util_sock.c, to avoid a possible
349 getpeername failure if we reopen the logs
350 and use %I in the filename.
353 smbd_set_server_fd(-1);
355 /* Force parent to check log size after
356 * spawning child. Fix from
357 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
358 * parent smbd will log to logserver.smb. It
359 * writes only two messages for each child
360 * started/finished. But each child writes,
361 * say, 50 messages also in logserver.smb,
362 * begining with the debug_count of the
363 * parent, before the child opens its own log
364 * file logserver.client. In a worst case
365 * scenario the size of logserver.smb would be
366 * checked after about 50*50=2500 messages
367 * (ca. 100kb).
368 * */
369 force_check_log_size();
371 } /* end for num */
372 } /* end while 1 */
374 /* NOTREACHED return True; */
377 /****************************************************************************
378 Reload the services file.
379 **************************************************************************/
381 BOOL reload_services(BOOL test)
383 BOOL ret;
385 set_register_printer_fn();
387 if (lp_loaded()) {
388 pstring fname;
389 pstrcpy(fname,lp_configfile());
390 if (file_exist(fname, NULL) &&
391 !strcsequal(fname, dyn_CONFIGFILE)) {
392 pstrcpy(dyn_CONFIGFILE, fname);
393 test = False;
397 reopen_logs();
399 if (test && !lp_file_list_changed())
400 return(True);
402 lp_killunused(conn_snum_used);
404 ret = lp_load(dyn_CONFIGFILE, False, False, True);
406 load_printers();
408 /* perhaps the config filename is now set */
409 if (!test)
410 reload_services(True);
412 reopen_logs();
414 load_interfaces();
417 if (smbd_server_fd() != -1) {
418 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
419 set_socket_options(smbd_server_fd(), user_socket_options);
423 mangle_reset_cache();
424 reset_stat_cache();
426 /* this forces service parameters to be flushed */
427 set_current_service(NULL,True);
429 return(ret);
432 #if DUMP_CORE
433 /*******************************************************************
434 prepare to dump a core file - carefully!
435 ********************************************************************/
436 static BOOL dump_core(void)
438 char *p;
439 pstring dname;
441 pstrcpy(dname,lp_logfile());
442 if ((p=strrchr_m(dname,'/'))) *p=0;
443 pstrcat(dname,"/corefiles");
444 mkdir(dname,0700);
445 sys_chown(dname,getuid(),getgid());
446 chmod(dname,0700);
447 if (chdir(dname)) return(False);
448 umask(~(0700));
450 #ifdef HAVE_GETRLIMIT
451 #ifdef RLIMIT_CORE
453 struct rlimit rlp;
454 getrlimit(RLIMIT_CORE, &rlp);
455 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
456 setrlimit(RLIMIT_CORE, &rlp);
457 getrlimit(RLIMIT_CORE, &rlp);
458 DEBUG(3,("Core limits now %d %d\n",
459 (int)rlp.rlim_cur,(int)rlp.rlim_max));
461 #endif
462 #endif
465 DEBUG(0,("Dumping core in %s\n", dname));
466 abort();
467 return(True);
469 #endif
471 /****************************************************************************
472 update the current smbd process count
473 ****************************************************************************/
475 static void decrement_smbd_process_count(void)
477 int32 total_smbds;
479 if (lp_max_smbd_processes()) {
480 total_smbds = 0;
481 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
485 /****************************************************************************
486 Exit the server.
487 ****************************************************************************/
489 void exit_server(char *reason)
491 static int firsttime=1;
492 extern char *last_inbuf;
493 extern struct auth_context *negprot_global_auth_context;
495 if (!firsttime)
496 exit(0);
497 firsttime = 0;
499 change_to_root_user();
500 DEBUG(2,("Closing connections\n"));
502 if (negprot_global_auth_context) {
503 (negprot_global_auth_context->free)(&negprot_global_auth_context);
506 conn_close_all();
508 invalidate_all_vuids();
510 /* delete our entry in the connections database. */
511 yield_connection(NULL,"");
513 respond_to_all_remaining_local_messages();
514 decrement_smbd_process_count();
516 #ifdef WITH_DFS
517 if (dcelogin_atmost_once) {
518 dfs_unlogin();
520 #endif
522 if (!reason) {
523 int oldlevel = DEBUGLEVEL;
524 DEBUGLEVEL = 10;
525 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
526 if (last_inbuf)
527 show_msg(last_inbuf);
528 DEBUGLEVEL = oldlevel;
529 DEBUG(0,("===============================================================\n"));
530 #if DUMP_CORE
531 if (dump_core()) return;
532 #endif
535 locking_end();
536 printing_end();
538 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
539 exit(0);
542 /****************************************************************************
543 Initialise connect, service and file structs.
544 ****************************************************************************/
546 static void init_structs(void )
549 * Set the machine NETBIOS name if not already
550 * set from the config file.
553 if (!*global_myname) {
554 char *p;
555 pstrcpy( global_myname, myhostname() );
556 p = strchr_m(global_myname, '.' );
557 if (p)
558 *p = 0;
561 strupper(global_myname);
563 conn_init();
565 file_init();
567 /* for RPC pipes */
568 init_rpc_pipe_hnd();
570 init_dptrs();
572 secrets_init();
576 /****************************************************************************
577 Usage on the program.
578 ****************************************************************************/
580 static void usage(char *pname)
583 d_printf("Usage: %s [-DaioPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
584 d_printf(" [-O socket options] [-s services file]\n");
585 d_printf("\t-D Become a daemon (default)\n");
586 d_printf("\t-a Append to log file (default)\n");
587 d_printf("\t-i Run interactive (not a daemon)\n" );
588 d_printf("\t-o Overwrite log file, don't append\n");
589 d_printf("\t-h Print usage\n");
590 d_printf("\t-? Print usage\n");
591 d_printf("\t-V Print version\n");
592 d_printf("\t-b Print build options\n");
593 d_printf("\t-d debuglevel Set the debuglevel\n");
594 d_printf("\t-l log basename. Basename for log/debug files\n");
595 d_printf("\t-p port Listen on the specified port\n");
596 d_printf("\t-O socket options Socket options\n");
597 d_printf("\t-s services file. Filename of services file\n");
598 d_printf("\n");
601 /****************************************************************************
602 main program.
603 ****************************************************************************/
605 int main(int argc,char *argv[])
607 extern BOOL append_log;
608 extern BOOL AllowDebugChange;
609 extern char *optarg;
610 /* shall I run as a daemon */
611 BOOL is_daemon = False;
612 BOOL interactive = False;
613 BOOL specified_logfile = False;
614 int port = SMB_PORT;
615 int opt;
616 pstring logfile;
618 #ifdef HAVE_SET_AUTH_PARAMETERS
619 set_auth_parameters(argc,argv);
620 #endif
622 /* this is for people who can't start the program correctly */
623 while (argc > 1 && (*argv[1] != '-')) {
624 argv++;
625 argc--;
628 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaiof:")) )
629 switch (opt) {
630 case 'O':
631 pstrcpy(user_socket_options,optarg);
632 break;
634 case 's':
635 pstrcpy(dyn_CONFIGFILE,optarg);
636 break;
638 case 'l':
639 specified_logfile = True;
640 pstr_sprintf(logfile, "%s/log.smbd", optarg);
641 lp_set_logfile(logfile);
642 break;
644 case 'a':
645 append_log = True;
646 break;
648 case 'i':
649 interactive = True;
650 break;
652 case 'o':
653 append_log = False;
654 break;
656 case 'D':
657 is_daemon = True;
658 break;
660 case 'd':
661 if (*optarg == 'A')
662 DEBUGLEVEL = 10000;
663 else
664 DEBUGLEVEL = atoi(optarg);
665 AllowDebugChange = False;
666 break;
668 case 'p':
669 port = atoi(optarg);
670 break;
672 case 'h':
673 case '?':
674 usage(argv[0]);
675 exit(0);
676 break;
678 case 'V':
679 d_printf("Version %s\n",VERSION);
680 exit(0);
681 break;
682 case 'b':
683 build_options(True); /* Display output to screen as well as debug */
684 exit(0);
685 break;
686 default:
687 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
688 usage(argv[0]);
689 exit(1);
692 #ifdef HAVE_SETLUID
693 /* needed for SecureWare on SCO */
694 setluid(0);
695 #endif
697 sec_init();
699 load_case_tables();
701 append_log = True;
703 if(!specified_logfile) {
704 pstr_sprintf(logfile, "%s/log.smbd", dyn_LOGFILEBASE);
705 lp_set_logfile(logfile);
708 fstrcpy(remote_machine, "smbd");
710 setup_logging(argv[0],interactive);
712 /* we want to re-seed early to prevent time delays causing
713 client problems at a later date. (tridge) */
714 generate_random_buffer(NULL, 0, False);
716 /* make absolutely sure we run as root - to handle cases where people
717 are crazy enough to have it setuid */
719 gain_root_privilege();
720 gain_root_group_privilege();
722 fault_setup((void (*)(void *))exit_server);
723 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
724 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
726 /* we are never interested in SIGPIPE */
727 BlockSignals(True,SIGPIPE);
729 #if defined(SIGFPE)
730 /* we are never interested in SIGFPE */
731 BlockSignals(True,SIGFPE);
732 #endif
734 #if defined(SIGUSR2)
735 /* We are no longer interested in USR2 */
736 BlockSignals(True,SIGUSR2);
737 #endif
739 /* POSIX demands that signals are inherited. If the invoking process has
740 * these signals masked, we will have problems, as we won't recieve them. */
741 BlockSignals(False, SIGHUP);
742 BlockSignals(False, SIGUSR1);
743 BlockSignals(False, SIGTERM);
745 /* we want total control over the permissions on created files,
746 so set our umask to 0 */
747 umask(0);
749 init_sec_ctx();
751 reopen_logs();
753 DEBUG(0,( "smbd version %s started.\n", VERSION));
754 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
756 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
757 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
759 /* Output the build options to the debug log */
760 build_options(False);
762 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
763 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
764 exit(1);
768 * Do this before reload_services.
771 if (!reload_services(False))
772 return(-1);
774 init_structs();
776 /* don't call winbind for our domain if we are the DC */
777 if (lp_domain_logons()) {
778 winbind_exclude_domain(lp_workgroup());
781 #ifdef WITH_PROFILE
782 if (!profile_setup(False)) {
783 DEBUG(0,("ERROR: failed to setup profiling\n"));
784 return -1;
786 #endif
788 fstrcpy(global_myworkgroup, lp_workgroup());
790 DEBUG(3,( "loaded services\n"));
792 if (!is_daemon && !is_a_socket(0)) {
793 if (!interactive)
794 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
797 * Setting is_daemon here prevents us from eventually calling
798 * the open_sockets_inetd()
801 is_daemon = True;
804 if (is_daemon && !interactive) {
805 DEBUG( 3, ( "Becoming a daemon.\n" ) );
806 become_daemon();
809 #if HAVE_SETPGID
811 * If we're interactive we want to set our own process group for
812 * signal management.
814 if (interactive)
815 setpgid( (pid_t)0, (pid_t)0);
816 #endif
818 if (!directory_exist(lp_lockdir(), NULL)) {
819 mkdir(lp_lockdir(), 0755);
822 if (is_daemon) {
823 pidfile_create("smbd");
826 if (!message_init()) {
827 exit(1);
829 register_msg_pool_usage();
830 register_dmalloc_msgs();
832 /* Setup the main smbd so that we can get messages. */
833 claim_connection(NULL,"",0,True);
836 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
837 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
838 smbd PROCESSES THAT NEVER DIE
839 start_background_queue();
842 if (!open_sockets(is_daemon,port))
843 exit(1);
846 * everything after this point is run after the fork()
849 if (!locking_init(0))
850 exit(1);
852 if (!print_backend_init())
853 exit(1);
855 if (!share_info_db_init())
856 exit(1);
858 if (!init_registry())
859 exit(1);
861 if(!initialize_password_db(False))
862 exit(1);
864 uni_group_cache_init(); /* Non-critical */
866 /* possibly reload the services file. */
867 reload_services(True);
869 if(!get_global_sam_sid()) {
870 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
871 exit(1);
874 if (!init_account_policy()) {
875 DEBUG(0,("Could not open account policy tdb.\n"));
876 exit(1);
879 if (*lp_rootdir()) {
880 if (sys_chroot(lp_rootdir()) == 0)
881 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
884 /* Setup oplocks */
885 if (!init_oplocks())
886 exit(1);
888 /* Setup change notify */
889 if (!init_change_notify())
890 exit(1);
892 smbd_process();
894 uni_group_cache_shutdown();
895 exit_server("normal exit");
896 return(0);