make sure we give an error for unknown lockingX locktype bits
[Samba/gebeck_regimport.git] / source / smbd / server.c
blob02f52e2392344228c3c5f6f7505212c9399bd385
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 void smbd_set_server_fd(int fd)
58 server_fd = fd;
59 client_setfd(fd);
62 /****************************************************************************
63 when exiting, take the whole family
64 ****************************************************************************/
65 static void *dflt_sig(void)
67 exit_server("caught signal");
68 return NULL;
71 /****************************************************************************
72 Send a SIGTERM to our process group.
73 *****************************************************************************/
74 static void killkids(void)
76 if(am_parent) kill(0,SIGTERM);
79 /****************************************************************************
80 process a sam sync message - not sure whether to do this here or
81 somewhere else
82 ****************************************************************************/
83 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
84 void *UNUSED(buf), size_t UNUSED(len))
86 DEBUG(10, ("** sam sync message received, ignoring\n"));
89 /****************************************************************************
90 process a sam sync replicate message - not sure whether to do this here or
91 somewhere else
92 ****************************************************************************/
93 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
95 uint32 low_serial;
97 if (len != sizeof(uint32))
98 return;
100 low_serial = *((uint32 *)buf);
102 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
103 low_serial));
106 /****************************************************************************
107 open the socket communication
108 ****************************************************************************/
109 static BOOL open_sockets_inetd(void)
111 /* Started from inetd. fd 0 is the socket. */
112 /* We will abort gracefully when the client or remote system
113 goes away */
114 smbd_set_server_fd(dup(0));
116 /* close our standard file descriptors */
117 close_low_fds();
119 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
120 set_socket_options(smbd_server_fd(), user_socket_options);
122 return True;
126 /****************************************************************************
127 open the socket communication
128 ****************************************************************************/
129 static BOOL open_sockets(BOOL is_daemon,int port)
131 int num_interfaces = iface_count();
132 int fd_listenset[FD_SETSIZE];
133 fd_set listen_set;
134 int s;
135 int i;
137 if (!is_daemon) {
138 return open_sockets_inetd();
142 #ifdef HAVE_ATEXIT
144 static int atexit_set;
145 if(atexit_set == 0) {
146 atexit_set=1;
147 atexit(killkids);
150 #endif
152 /* Stop zombies */
153 CatchChild();
156 FD_ZERO(&listen_set);
158 if(lp_interfaces() && lp_bind_interfaces_only()) {
159 /* We have been given an interfaces line, and been
160 told to only bind to those interfaces. Create a
161 socket per interface and bind to only these.
164 if(num_interfaces > FD_SETSIZE) {
165 DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
166 max can be %d\n",
167 num_interfaces, FD_SETSIZE));
168 return False;
171 /* Now open a listen socket for each of the
172 interfaces. */
173 for(i = 0; i < num_interfaces; i++) {
174 struct in_addr *ifip = iface_n_ip(i);
176 if(ifip == NULL) {
177 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
178 continue;
180 s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
181 if(s == -1)
182 return False;
184 /* ready to listen */
185 set_socket_options(s,"SO_KEEPALIVE");
186 set_socket_options(s,user_socket_options);
188 if (listen(s, 5) == -1) {
189 DEBUG(0,("listen: %s\n",strerror(errno)));
190 close(s);
191 return False;
193 FD_SET(s,&listen_set);
195 } else {
196 /* Just bind to 0.0.0.0 - accept connections
197 from anywhere. */
198 num_interfaces = 1;
200 /* open an incoming socket */
201 s = open_socket_in(SOCK_STREAM, port, 0,
202 interpret_addr(lp_socket_address()),True);
203 if (s == -1)
204 return(False);
206 /* ready to listen */
207 set_socket_options(s,"SO_KEEPALIVE");
208 set_socket_options(s,user_socket_options);
210 if (listen(s, 5) == -1) {
211 DEBUG(0,("open_sockets: listen: %s\n",
212 strerror(errno)));
213 close(s);
214 return False;
217 fd_listenset[0] = s;
218 FD_SET(s,&listen_set);
221 /* Listen to messages */
223 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
224 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
226 /* now accept incoming connections - forking a new process
227 for each incoming connection */
228 DEBUG(2,("waiting for a connection\n"));
229 while (1) {
230 fd_set lfds;
231 int num;
233 /* Free up temporary memory from the main smbd. */
234 lp_talloc_free();
236 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
237 message_dispatch();
239 memcpy((char *)&lfds, (char *)&listen_set,
240 sizeof(listen_set));
242 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
244 if (num == -1 && errno == EINTR) {
245 extern VOLATILE sig_atomic_t reload_after_sighup;
247 /* check for sighup processing */
248 if (reload_after_sighup) {
249 change_to_root_user();
250 DEBUG(1,("Reloading services after SIGHUP\n"));
251 reload_services(False);
252 reload_after_sighup = False;
255 continue;
258 /* check if we need to reload services */
259 check_reload(time(NULL));
261 /* Find the sockets that are read-ready -
262 accept on these. */
263 for( ; num > 0; num--) {
264 struct sockaddr addr;
265 socklen_t in_addrlen = sizeof(addr);
267 s = -1;
268 for(i = 0; i < num_interfaces; i++) {
269 if(FD_ISSET(fd_listenset[i],&lfds)) {
270 s = fd_listenset[i];
271 /* Clear this so we don't look
272 at it again. */
273 FD_CLR(fd_listenset[i],&lfds);
274 break;
278 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
280 if (smbd_server_fd() == -1 && errno == EINTR)
281 continue;
283 if (smbd_server_fd() == -1) {
284 DEBUG(0,("open_sockets: accept: %s\n",
285 strerror(errno)));
286 continue;
289 if (smbd_server_fd() != -1 && sys_fork()==0) {
290 /* Child code ... */
292 /* close the listening socket(s) */
293 for(i = 0; i < num_interfaces; i++)
294 close(fd_listenset[i]);
296 /* close our standard file
297 descriptors */
298 close_low_fds();
299 am_parent = 0;
301 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
302 set_socket_options(smbd_server_fd(),user_socket_options);
304 /* Reset global variables in util.c so
305 that client substitutions will be
306 done correctly in the process. */
307 reset_globals_after_fork();
309 /* tdb needs special fork handling */
310 tdb_reopen_all();
312 return True;
314 /* The parent doesn't need this socket */
315 close(smbd_server_fd());
317 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
318 Clear the closed fd info out of server_fd --
319 and more importantly, out of client_fd in
320 util_sock.c, to avoid a possible
321 getpeername failure if we reopen the logs
322 and use %I in the filename.
325 smbd_set_server_fd(-1);
327 /* Force parent to check log size after
328 * spawning child. Fix from
329 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
330 * parent smbd will log to logserver.smb. It
331 * writes only two messages for each child
332 * started/finished. But each child writes,
333 * say, 50 messages also in logserver.smb,
334 * begining with the debug_count of the
335 * parent, before the child opens its own log
336 * file logserver.client. In a worst case
337 * scenario the size of logserver.smb would be
338 * checked after about 50*50=2500 messages
339 * (ca. 100kb).
340 * */
341 force_check_log_size();
343 } /* end for num */
344 } /* end while 1 */
346 /* NOTREACHED return True; */
349 /****************************************************************************
350 reload the services file
351 **************************************************************************/
352 BOOL reload_services(BOOL test)
354 BOOL ret;
356 if (lp_loaded()) {
357 pstring fname;
358 pstrcpy(fname,lp_configfile());
359 if (file_exist(fname, NULL) &&
360 !strcsequal(fname, dyn_CONFIGFILE)) {
361 pstrcpy(dyn_CONFIGFILE, fname);
362 test = False;
366 reopen_logs();
368 if (test && !lp_file_list_changed())
369 return(True);
371 lp_killunused(conn_snum_used);
373 ret = lp_load(dyn_CONFIGFILE, False, False, True);
375 load_printers();
377 /* perhaps the config filename is now set */
378 if (!test)
379 reload_services(True);
381 reopen_logs();
383 load_interfaces();
386 if (smbd_server_fd() != -1) {
387 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
388 set_socket_options(smbd_server_fd(), user_socket_options);
392 reset_mangled_cache();
393 reset_stat_cache();
395 /* this forces service parameters to be flushed */
396 set_current_service(NULL,True);
398 return(ret);
403 /****************************************************************************
404 Catch a sighup.
405 ****************************************************************************/
407 VOLATILE sig_atomic_t reload_after_sighup = False;
409 static void sig_hup(int sig)
411 BlockSignals(True,SIGHUP);
412 DEBUG(0,("Got SIGHUP\n"));
414 sys_select_signal();
415 reload_after_sighup = True;
416 BlockSignals(False,SIGHUP);
421 #if DUMP_CORE
422 /*******************************************************************
423 prepare to dump a core file - carefully!
424 ********************************************************************/
425 static BOOL dump_core(void)
427 char *p;
428 pstring dname;
430 pstrcpy(dname,lp_logfile());
431 if ((p=strrchr_m(dname,'/'))) *p=0;
432 pstrcat(dname,"/corefiles");
433 mkdir(dname,0700);
434 sys_chown(dname,getuid(),getgid());
435 chmod(dname,0700);
436 if (chdir(dname)) return(False);
437 umask(~(0700));
439 #ifdef HAVE_GETRLIMIT
440 #ifdef RLIMIT_CORE
442 struct rlimit rlp;
443 getrlimit(RLIMIT_CORE, &rlp);
444 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
445 setrlimit(RLIMIT_CORE, &rlp);
446 getrlimit(RLIMIT_CORE, &rlp);
447 DEBUG(3,("Core limits now %d %d\n",
448 (int)rlp.rlim_cur,(int)rlp.rlim_max));
450 #endif
451 #endif
454 DEBUG(0,("Dumping core in %s\n", dname));
455 abort();
456 return(True);
458 #endif
460 /****************************************************************************
461 update the current smbd process count
462 ****************************************************************************/
464 static void decrement_smbd_process_count(void)
466 int32 total_smbds;
468 if (lp_max_smbd_processes()) {
469 total_smbds = 0;
470 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
474 /****************************************************************************
475 exit the server
476 ****************************************************************************/
477 void exit_server(char *reason)
479 static int firsttime=1;
480 extern char *last_inbuf;
481 extern struct auth_context *negprot_global_auth_context;
483 if (!firsttime)
484 exit(0);
485 firsttime = 0;
487 change_to_root_user();
488 DEBUG(2,("Closing connections\n"));
490 if (negprot_global_auth_context) {
491 (negprot_global_auth_context->free)(&negprot_global_auth_context);
494 conn_close_all();
496 invalidate_all_vuids();
498 /* delete our entry in the connections database. */
499 yield_connection(NULL,"");
501 respond_to_all_remaining_local_messages();
502 decrement_smbd_process_count();
504 #ifdef WITH_DFS
505 if (dcelogin_atmost_once) {
506 dfs_unlogin();
508 #endif
510 if (!reason) {
511 int oldlevel = DEBUGLEVEL;
512 DEBUGLEVEL = 10;
513 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
514 if (last_inbuf)
515 show_msg(last_inbuf);
516 DEBUGLEVEL = oldlevel;
517 DEBUG(0,("===============================================================\n"));
518 #if DUMP_CORE
519 if (dump_core()) return;
520 #endif
523 locking_end();
525 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
526 exit(0);
529 /****************************************************************************
530 initialise connect, service and file structs
531 ****************************************************************************/
532 static void init_structs(void )
535 * Set the machine NETBIOS name if not already
536 * set from the config file.
539 if (!*global_myname) {
540 char *p;
541 pstrcpy( global_myname, myhostname() );
542 p = strchr_m(global_myname, '.' );
543 if (p)
544 *p = 0;
547 strupper(global_myname);
549 conn_init();
551 file_init();
553 /* for RPC pipes */
554 init_rpc_pipe_hnd();
556 init_dptrs();
558 secrets_init();
562 /****************************************************************************
563 usage on the program
564 ****************************************************************************/
565 static void usage(char *pname)
568 d_printf("Usage: %s [-DaioPh?Vb] [-d debuglevel] [-l log basename] [-p port]\n", pname);
569 d_printf(" [-O socket options] [-s services file]\n");
570 d_printf("\t-D Become a daemon (default)\n");
571 d_printf("\t-a Append to log file (default)\n");
572 d_printf("\t-i Run interactive (not a daemon)\n" );
573 d_printf("\t-o Overwrite log file, don't append\n");
574 d_printf("\t-h Print usage\n");
575 d_printf("\t-? Print usage\n");
576 d_printf("\t-V Print version\n");
577 d_printf("\t-b Print build options\n");
578 d_printf("\t-d debuglevel Set the debuglevel\n");
579 d_printf("\t-l log basename. Basename for log/debug files\n");
580 d_printf("\t-p port Listen on the specified port\n");
581 d_printf("\t-O socket options Socket options\n");
582 d_printf("\t-s services file. Filename of services file\n");
583 d_printf("\n");
586 /****************************************************************************
587 main program
588 ****************************************************************************/
589 int main(int argc,char *argv[])
591 extern BOOL append_log;
592 extern BOOL AllowDebugChange;
593 extern char *optarg;
594 /* shall I run as a daemon */
595 BOOL is_daemon = False;
596 BOOL interactive = False;
597 BOOL specified_logfile = False;
598 int port = SMB_PORT;
599 int opt;
600 pstring logfile;
602 #ifdef HAVE_SET_AUTH_PARAMETERS
603 set_auth_parameters(argc,argv);
604 #endif
606 /* this is for people who can't start the program correctly */
607 while (argc > 1 && (*argv[1] != '-')) {
608 argv++;
609 argc--;
612 while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?bVaiof:")) )
613 switch (opt) {
614 case 'O':
615 pstrcpy(user_socket_options,optarg);
616 break;
618 case 's':
619 pstrcpy(dyn_CONFIGFILE,optarg);
620 break;
622 case 'l':
623 specified_logfile = True;
624 pstr_sprintf(logfile, "%s/log.smbd", optarg);
625 lp_set_logfile(logfile);
626 break;
628 case 'a':
629 append_log = True;
630 break;
632 case 'i':
633 interactive = True;
634 break;
636 case 'o':
637 append_log = False;
638 break;
640 case 'D':
641 is_daemon = True;
642 break;
644 case 'd':
645 if (*optarg == 'A')
646 DEBUGLEVEL = 10000;
647 else
648 DEBUGLEVEL = atoi(optarg);
649 AllowDebugChange = False;
650 break;
652 case 'p':
653 port = atoi(optarg);
654 break;
656 case 'h':
657 case '?':
658 usage(argv[0]);
659 exit(0);
660 break;
662 case 'V':
663 d_printf("Version %s\n",VERSION);
664 exit(0);
665 break;
666 case 'b':
667 build_options(True); /* Display output to screen as well as debug */
668 exit(0);
669 break;
670 default:
671 DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
672 usage(argv[0]);
673 exit(1);
676 #ifdef HAVE_SETLUID
677 /* needed for SecureWare on SCO */
678 setluid(0);
679 #endif
681 sec_init();
683 load_case_tables();
685 append_log = True;
687 if(!specified_logfile) {
688 pstr_sprintf(logfile, "%s/log.smbd", dyn_LOGFILEBASE);
689 lp_set_logfile(logfile);
692 fstrcpy(remote_machine, "smbd");
694 setup_logging(argv[0],interactive);
696 /* we want to re-seed early to prevent time delays causing
697 client problems at a later date. (tridge) */
698 generate_random_buffer(NULL, 0, False);
700 /* make absolutely sure we run as root - to handle cases where people
701 are crazy enough to have it setuid */
703 gain_root_privilege();
704 gain_root_group_privilege();
706 fault_setup((void (*)(void *))exit_server);
707 CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
709 /* we are never interested in SIGPIPE */
710 BlockSignals(True,SIGPIPE);
712 #if defined(SIGFPE)
713 /* we are never interested in SIGFPE */
714 BlockSignals(True,SIGFPE);
715 #endif
717 #if defined(SIGUSR2)
718 /* We are no longer interested in USR2 */
719 BlockSignals(True,SIGUSR2);
720 #endif
722 /* POSIX demands that signals are inherited. If the invoking process has
723 * these signals masked, we will have problems, as we won't recieve them. */
724 BlockSignals(False, SIGHUP);
725 BlockSignals(False, SIGUSR1);
727 /* we want total control over the permissions on created files,
728 so set our umask to 0 */
729 umask(0);
731 init_sec_ctx();
733 reopen_logs();
735 DEBUG(0,( "smbd version %s started.\n", VERSION));
736 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
738 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
739 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
741 /* Output the build options to the debug log */
742 build_options(False);
744 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
745 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
746 exit(1);
750 * Do this before reload_services.
753 if (!reload_services(False))
754 return(-1);
756 init_structs();
758 /* don't call winbind for our domain if we are the DC */
759 if (lp_domain_logons()) {
760 winbind_exclude_domain(lp_workgroup());
763 #ifdef WITH_PROFILE
764 if (!profile_setup(False)) {
765 DEBUG(0,("ERROR: failed to setup profiling\n"));
766 return -1;
768 #endif
770 #ifdef WITH_SSL
772 extern BOOL sslEnabled;
773 sslEnabled = lp_ssl_enabled();
774 if(sslEnabled)
775 sslutil_init(True);
777 #endif /* WITH_SSL */
779 fstrcpy(global_myworkgroup, lp_workgroup());
781 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
783 DEBUG(3,( "loaded services\n"));
785 if (!is_daemon && !is_a_socket(0)) {
786 if (!interactive)
787 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
790 * Setting is_daemon here prevents us from eventually calling
791 * the open_sockets_inetd()
794 is_daemon = True;
797 if (is_daemon && !interactive) {
798 DEBUG( 3, ( "Becoming a daemon.\n" ) );
799 become_daemon();
802 #if HAVE_SETPGID
804 * If we're interactive we want to set our own process group for
805 * signal management.
807 if (interactive)
808 setpgid( (pid_t)0, (pid_t)0);
809 #endif
811 if (!directory_exist(lp_lockdir(), NULL)) {
812 mkdir(lp_lockdir(), 0755);
815 if (is_daemon) {
816 pidfile_create("smbd");
819 if (!message_init()) {
820 exit(1);
822 register_msg_pool_usage();
823 register_dmalloc_msgs();
825 /* Setup the main smbd so that we can get messages. */
826 claim_connection(NULL,"",0,True);
829 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
830 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
831 smbd PROCESSES THAT NEVER DIE
832 start_background_queue();
835 if (!open_sockets(is_daemon,port))
836 exit(1);
839 * everything after this point is run after the fork()
842 if (!locking_init(0))
843 exit(1);
845 if (!print_backend_init())
846 exit(1);
848 if (!share_info_db_init())
849 exit(1);
851 if(!initialize_password_db(False))
852 exit(1);
854 uni_group_cache_init(); /* Non-critical */
856 /* possibly reload the services file. */
857 reload_services(True);
859 if(!pdb_generate_sam_sid()) {
860 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
861 exit(1);
864 if (!init_account_policy()) {
865 DEBUG(0,("Could not open account policy tdb.\n"));
866 exit(1);
869 if (*lp_rootdir()) {
870 if (sys_chroot(lp_rootdir()) == 0)
871 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
874 /* Setup oplocks */
875 if (!init_oplocks())
876 exit(1);
878 /* Setup mangle */
879 if (!init_mangle_tdb())
880 exit(1);
882 /* Setup change notify */
883 if (!init_change_notify())
884 exit(1);
886 smbd_process();
888 uni_group_cache_shutdown();
889 exit_server("normal exit");
890 return(0);