Stop using hardcoded transact commands
[Samba/nascimento.git] / source / smbd / server.c
blob3d9a4675b2b4e8b6b02feb3b20b881fe421f9f2c
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
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 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;
37 extern SIG_ATOMIC_T got_sig_term;
38 extern SIG_ATOMIC_T reload_after_sighup;
40 #ifdef WITH_DFS
41 extern int dcelogin_atmost_once;
42 #endif /* WITH_DFS */
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 static void smbd_set_server_fd(int fd)
59 server_fd = fd;
60 client_setfd(fd);
63 /****************************************************************************
64 Terminate signal.
65 ****************************************************************************/
67 static void sig_term(void)
69 got_sig_term = 1;
70 sys_select_signal();
73 /****************************************************************************
74 Catch a sighup.
75 ****************************************************************************/
77 static void sig_hup(int sig)
79 reload_after_sighup = 1;
80 sys_select_signal();
83 /****************************************************************************
84 Send a SIGTERM to our process group.
85 *****************************************************************************/
87 static void killkids(void)
89 if(am_parent) kill(0,SIGTERM);
92 /****************************************************************************
93 Process a sam sync message - not sure whether to do this here or
94 somewhere else.
95 ****************************************************************************/
97 static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
98 void *UNUSED(buf), size_t UNUSED(len))
100 DEBUG(10, ("** sam sync message received, ignoring\n"));
103 /****************************************************************************
104 Process a sam sync replicate message - not sure whether to do this here or
105 somewhere else.
106 ****************************************************************************/
108 static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
110 uint32 low_serial;
112 if (len != sizeof(uint32))
113 return;
115 low_serial = *((uint32 *)buf);
117 DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
118 low_serial));
121 /****************************************************************************
122 Open the socket communication - inetd.
123 ****************************************************************************/
125 static BOOL open_sockets_inetd(void)
127 /* Started from inetd. fd 0 is the socket. */
128 /* We will abort gracefully when the client or remote system
129 goes away */
130 smbd_set_server_fd(dup(0));
132 /* close our standard file descriptors */
133 close_low_fds(False); /* Don't close stderr */
135 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
136 set_socket_options(smbd_server_fd(), user_socket_options);
138 return True;
141 static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
143 exit_server("Got a SHUTDOWN message");
147 /****************************************************************************
148 Open the socket communication.
149 ****************************************************************************/
151 static BOOL open_sockets_smbd(BOOL is_daemon,const char *smb_ports)
153 int num_interfaces = iface_count();
154 int num_sockets = 0;
155 int fd_listenset[FD_SETSIZE];
156 fd_set listen_set;
157 int s;
158 int i;
159 char *ports;
161 if (!is_daemon) {
162 return open_sockets_inetd();
166 #ifdef HAVE_ATEXIT
168 static int atexit_set;
169 if(atexit_set == 0) {
170 atexit_set=1;
171 atexit(killkids);
174 #endif
176 /* Stop zombies */
177 CatchChild();
179 FD_ZERO(&listen_set);
181 /* use a reasonable default set of ports - listing on 445 and 139 */
182 if (!smb_ports) {
183 ports = lp_smb_ports();
184 if (!ports || !*ports) {
185 ports = SMB_PORTS;
187 ports = strdup(ports);
188 } else {
189 ports = strdup(smb_ports);
192 if (lp_interfaces() && lp_bind_interfaces_only()) {
193 /* We have been given an interfaces line, and been
194 told to only bind to those interfaces. Create a
195 socket per interface and bind to only these.
198 /* Now open a listen socket for each of the
199 interfaces. */
200 for(i = 0; i < num_interfaces; i++) {
201 struct in_addr *ifip = iface_n_ip(i);
202 fstring tok;
203 char *ptr;
205 if(ifip == NULL) {
206 DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
207 continue;
210 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
211 unsigned port = atoi(tok);
212 if (port == 0) continue;
213 s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
214 if(s == -1)
215 return False;
217 /* ready to listen */
218 set_socket_options(s,"SO_KEEPALIVE");
219 set_socket_options(s,user_socket_options);
221 if (listen(s, 5) == -1) {
222 DEBUG(0,("listen: %s\n",strerror(errno)));
223 close(s);
224 return False;
226 FD_SET(s,&listen_set);
228 num_sockets++;
229 if (num_sockets >= FD_SETSIZE) {
230 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
231 return False;
235 } else {
236 /* Just bind to 0.0.0.0 - accept connections
237 from anywhere. */
239 fstring tok;
240 char *ptr;
242 num_interfaces = 1;
244 for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
245 unsigned port = atoi(tok);
246 if (port == 0) continue;
247 /* open an incoming socket */
248 s = open_socket_in(SOCK_STREAM, port, 0,
249 interpret_addr(lp_socket_address()),True);
250 if (s == -1)
251 return(False);
253 /* ready to listen */
254 set_socket_options(s,"SO_KEEPALIVE");
255 set_socket_options(s,user_socket_options);
257 if (listen(s, 5) == -1) {
258 DEBUG(0,("open_sockets_smbd: listen: %s\n",
259 strerror(errno)));
260 close(s);
261 return False;
264 fd_listenset[num_sockets] = s;
265 FD_SET(s,&listen_set);
267 num_sockets++;
269 if (num_sockets >= FD_SETSIZE) {
270 DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
271 return False;
276 SAFE_FREE(ports);
278 /* Listen to messages */
280 message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
281 message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
282 message_register(MSG_SHUTDOWN, msg_exit_server);
284 /* now accept incoming connections - forking a new process
285 for each incoming connection */
286 DEBUG(2,("waiting for a connection\n"));
287 while (1) {
288 fd_set lfds;
289 int num;
291 /* Free up temporary memory from the main smbd. */
292 lp_talloc_free();
294 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
295 message_dispatch();
297 memcpy((char *)&lfds, (char *)&listen_set,
298 sizeof(listen_set));
300 num = sys_select(FD_SETSIZE,&lfds,NULL,NULL,NULL);
302 if (num == -1 && errno == EINTR) {
303 if (got_sig_term) {
304 exit_server("Caught TERM signal");
307 /* check for sighup processing */
308 if (reload_after_sighup) {
309 change_to_root_user();
310 DEBUG(1,("Reloading services after SIGHUP\n"));
311 reload_services(False);
312 reload_after_sighup = 0;
315 continue;
318 /* check if we need to reload services */
319 check_reload(time(NULL));
321 /* Find the sockets that are read-ready -
322 accept on these. */
323 for( ; num > 0; num--) {
324 struct sockaddr addr;
325 socklen_t in_addrlen = sizeof(addr);
327 s = -1;
328 for(i = 0; i < num_sockets; i++) {
329 if(FD_ISSET(fd_listenset[i],&lfds)) {
330 s = fd_listenset[i];
331 /* Clear this so we don't look
332 at it again. */
333 FD_CLR(fd_listenset[i],&lfds);
334 break;
338 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
340 if (smbd_server_fd() == -1 && errno == EINTR)
341 continue;
343 if (smbd_server_fd() == -1) {
344 DEBUG(0,("open_sockets_smbd: accept: %s\n",
345 strerror(errno)));
346 continue;
349 if (smbd_server_fd() != -1 && sys_fork()==0) {
350 /* Child code ... */
352 /* close the listening socket(s) */
353 for(i = 0; i < num_sockets; i++)
354 close(fd_listenset[i]);
356 /* close our standard file
357 descriptors */
358 close_low_fds(False);
359 am_parent = 0;
361 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
362 set_socket_options(smbd_server_fd(),user_socket_options);
364 /* this is needed so that we get decent entries
365 in smbstatus for port 445 connects */
366 set_remote_machine_name(get_socket_addr(smbd_server_fd()));
368 /* Reset global variables in util.c so
369 that client substitutions will be
370 done correctly in the process. */
371 reset_globals_after_fork();
373 /* tdb needs special fork handling */
374 if (tdb_reopen_all() == -1) {
375 DEBUG(0,("tdb_reopen_all failed.\n"));
376 return False;
379 return True;
381 /* The parent doesn't need this socket */
382 close(smbd_server_fd());
384 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
385 Clear the closed fd info out of server_fd --
386 and more importantly, out of client_fd in
387 util_sock.c, to avoid a possible
388 getpeername failure if we reopen the logs
389 and use %I in the filename.
392 smbd_set_server_fd(-1);
394 /* Force parent to check log size after
395 * spawning child. Fix from
396 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
397 * parent smbd will log to logserver.smb. It
398 * writes only two messages for each child
399 * started/finished. But each child writes,
400 * say, 50 messages also in logserver.smb,
401 * begining with the debug_count of the
402 * parent, before the child opens its own log
403 * file logserver.client. In a worst case
404 * scenario the size of logserver.smb would be
405 * checked after about 50*50=2500 messages
406 * (ca. 100kb).
407 * */
408 force_check_log_size();
410 } /* end for num */
411 } /* end while 1 */
413 /* NOTREACHED return True; */
416 /****************************************************************************
417 Reload the services file.
418 **************************************************************************/
420 BOOL reload_services(BOOL test)
422 BOOL ret;
424 if (lp_loaded()) {
425 pstring fname;
426 pstrcpy(fname,lp_configfile());
427 if (file_exist(fname, NULL) &&
428 !strcsequal(fname, dyn_CONFIGFILE)) {
429 pstrcpy(dyn_CONFIGFILE, fname);
430 test = False;
434 reopen_logs();
436 if (test && !lp_file_list_changed())
437 return(True);
439 lp_killunused(conn_snum_used);
441 ret = lp_load(dyn_CONFIGFILE, False, False, True);
443 load_printers();
445 /* perhaps the config filename is now set */
446 if (!test)
447 reload_services(True);
449 reopen_logs();
451 load_interfaces();
454 if (smbd_server_fd() != -1) {
455 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
456 set_socket_options(smbd_server_fd(), user_socket_options);
460 mangle_reset_cache();
461 reset_stat_cache();
463 /* this forces service parameters to be flushed */
464 set_current_service(NULL,True);
466 return(ret);
469 #if DUMP_CORE
470 /*******************************************************************
471 prepare to dump a core file - carefully!
472 ********************************************************************/
473 static BOOL dump_core(void)
475 char *p;
476 pstring dname;
478 pstrcpy(dname,lp_logfile());
479 if ((p=strrchr_m(dname,'/'))) *p=0;
480 pstrcat(dname,"/corefiles");
481 mkdir(dname,0700);
482 sys_chown(dname,getuid(),getgid());
483 chmod(dname,0700);
484 if (chdir(dname)) return(False);
485 umask(~(0700));
487 #ifdef HAVE_GETRLIMIT
488 #ifdef RLIMIT_CORE
490 struct rlimit rlp;
491 getrlimit(RLIMIT_CORE, &rlp);
492 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
493 setrlimit(RLIMIT_CORE, &rlp);
494 getrlimit(RLIMIT_CORE, &rlp);
495 DEBUG(3,("Core limits now %d %d\n",
496 (int)rlp.rlim_cur,(int)rlp.rlim_max));
498 #endif
499 #endif
502 DEBUG(0,("Dumping core in %s\n", dname));
503 abort();
504 return(True);
506 #endif
508 /****************************************************************************
509 update the current smbd process count
510 ****************************************************************************/
512 static void decrement_smbd_process_count(void)
514 int32 total_smbds;
516 if (lp_max_smbd_processes()) {
517 total_smbds = 0;
518 tdb_change_int32_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
522 /****************************************************************************
523 Exit the server.
524 ****************************************************************************/
526 void exit_server(char *reason)
528 static int firsttime=1;
529 extern char *last_inbuf;
530 extern struct auth_context *negprot_global_auth_context;
532 if (!firsttime)
533 exit(0);
534 firsttime = 0;
536 change_to_root_user();
537 DEBUG(2,("Closing connections\n"));
539 if (negprot_global_auth_context) {
540 (negprot_global_auth_context->free)(&negprot_global_auth_context);
543 conn_close_all();
545 invalidate_all_vuids();
547 print_notify_send_messages();
549 /* delete our entry in the connections database. */
550 yield_connection(NULL,"");
552 respond_to_all_remaining_local_messages();
553 decrement_smbd_process_count();
555 #ifdef WITH_DFS
556 if (dcelogin_atmost_once) {
557 dfs_unlogin();
559 #endif
561 if (!reason) {
562 int oldlevel = DEBUGLEVEL;
563 DEBUGLEVEL = 10;
564 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
565 if (last_inbuf)
566 show_msg(last_inbuf);
567 DEBUGLEVEL = oldlevel;
568 DEBUG(0,("===============================================================\n"));
569 #if DUMP_CORE
570 if (dump_core()) return;
571 #endif
574 locking_end();
575 printing_end();
577 DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
578 exit(0);
581 /****************************************************************************
582 Initialise connect, service and file structs.
583 ****************************************************************************/
585 static void init_structs(void )
588 * Set the machine NETBIOS name if not already
589 * set from the config file.
592 if (!*global_myname) {
593 char *p;
594 pstrcpy( global_myname, myhostname() );
595 p = strchr_m(global_myname, '.' );
596 if (p)
597 *p = 0;
600 strupper(global_myname);
602 conn_init();
604 file_init();
606 /* for RPC pipes */
607 init_rpc_pipe_hnd();
609 init_dptrs();
611 secrets_init();
615 /****************************************************************************
616 main program.
617 ****************************************************************************/
619 int main(int argc,const char *argv[])
621 /* shall I run as a daemon */
622 static BOOL is_daemon = False;
623 static BOOL interactive = False;
624 static char *ports = NULL;
625 int opt;
626 poptContext pc;
628 struct poptOption long_options[] = {
629 POPT_AUTOHELP
630 {"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
631 {"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
632 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
633 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
634 {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_debug},
635 {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_configfile},
636 {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_socket_options},
637 {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_log_base},
638 {NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_version},
639 { NULL }
642 #ifdef HAVE_SET_AUTH_PARAMETERS
643 set_auth_parameters(argc,argv);
644 #endif
646 pc = poptGetContext("smbd", argc, argv, long_options, 0);
648 while((opt = poptGetNextOpt(pc)) != -1) {
649 switch (opt) {
650 case 'b':
651 build_options(True); /* Display output to screen as well as debug */
652 exit(0);
653 break;
657 poptFreeContext(pc);
659 #ifdef HAVE_SETLUID
660 /* needed for SecureWare on SCO */
661 setluid(0);
662 #endif
664 sec_init();
666 load_case_tables();
668 set_remote_machine_name("smbd");
670 setup_logging(argv[0],interactive);
672 /* we want to re-seed early to prevent time delays causing
673 client problems at a later date. (tridge) */
674 generate_random_buffer(NULL, 0, False);
676 /* make absolutely sure we run as root - to handle cases where people
677 are crazy enough to have it setuid */
679 gain_root_privilege();
680 gain_root_group_privilege();
682 fault_setup((void (*)(void *))exit_server);
683 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
684 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
686 /* we are never interested in SIGPIPE */
687 BlockSignals(True,SIGPIPE);
689 #if defined(SIGFPE)
690 /* we are never interested in SIGFPE */
691 BlockSignals(True,SIGFPE);
692 #endif
694 #if defined(SIGUSR2)
695 /* We are no longer interested in USR2 */
696 BlockSignals(True,SIGUSR2);
697 #endif
699 /* POSIX demands that signals are inherited. If the invoking process has
700 * these signals masked, we will have problems, as we won't recieve them. */
701 BlockSignals(False, SIGHUP);
702 BlockSignals(False, SIGUSR1);
703 BlockSignals(False, SIGTERM);
705 /* we want total control over the permissions on created files,
706 so set our umask to 0 */
707 umask(0);
709 init_sec_ctx();
711 reopen_logs();
713 DEBUG(0,( "smbd version %s started.\n", VERSION));
714 DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2002\n"));
716 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
717 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
719 /* Output the build options to the debug log */
720 build_options(False);
722 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
723 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
724 exit(1);
728 * Do this before reload_services.
731 if (!reload_services(False))
732 return(-1);
734 init_structs();
736 #ifdef WITH_PROFILE
737 if (!profile_setup(False)) {
738 DEBUG(0,("ERROR: failed to setup profiling\n"));
739 return -1;
741 #endif
743 fstrcpy(global_myworkgroup, lp_workgroup());
745 DEBUG(3,( "loaded services\n"));
747 if (!is_daemon && !is_a_socket(0)) {
748 if (!interactive)
749 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
752 * Setting is_daemon here prevents us from eventually calling
753 * the open_sockets_inetd()
756 is_daemon = True;
759 if (is_daemon && !interactive) {
760 DEBUG( 3, ( "Becoming a daemon.\n" ) );
761 become_daemon();
764 #if HAVE_SETPGID
766 * If we're interactive we want to set our own process group for
767 * signal management.
769 if (interactive)
770 setpgid( (pid_t)0, (pid_t)0);
771 #endif
773 if (!directory_exist(lp_lockdir(), NULL)) {
774 mkdir(lp_lockdir(), 0755);
777 if (is_daemon) {
778 pidfile_create("smbd");
781 if (!message_init()) {
782 exit(1);
784 register_msg_pool_usage();
785 register_dmalloc_msgs();
787 if (!print_backend_init())
788 exit(1);
790 /* Setup the main smbd so that we can get messages. */
791 claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
794 DO NOT ENABLE THIS TILL YOU COPE WITH KILLING THESE TASKS AND INETD
795 THIS *killed* LOTS OF BUILD FARM MACHINES. IT CREATED HUNDREDS OF
796 smbd PROCESSES THAT NEVER DIE
797 start_background_queue();
800 if (!open_sockets_smbd(is_daemon,ports))
801 exit(1);
804 * everything after this point is run after the fork()
807 namecache_enable();
809 if (!locking_init(0))
810 exit(1);
812 if (!share_info_db_init())
813 exit(1);
815 if (!init_registry())
816 exit(1);
818 if(!initialize_password_db(False))
819 exit(1);
821 uni_group_cache_init(); /* Non-critical */
823 /* possibly reload the services file. */
824 reload_services(True);
826 if(!get_global_sam_sid()) {
827 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
828 exit(1);
831 if (!init_account_policy()) {
832 DEBUG(0,("Could not open account policy tdb.\n"));
833 exit(1);
836 if (*lp_rootdir()) {
837 if (sys_chroot(lp_rootdir()) == 0)
838 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
841 /* Setup oplocks */
842 if (!init_oplocks())
843 exit(1);
845 /* Setup change notify */
846 if (!init_change_notify())
847 exit(1);
849 /* re-initialise the timezone */
850 TimeInit();
852 /* register our message handlers */
853 message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
854 talloc_init_named("dummy!");
856 smbd_process();
858 uni_group_cache_shutdown();
859 exit_server("normal exit");
860 return(0);