Fix denial of service - memory corruption.
[Samba.git] / source / smbd / server.c
bloba670334a106f5400f5614b38a5d7426d8010786b
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
7 Copyright (C) Volker Lendecke 1993-2007
8 Copyright (C) Jeremy Allison 1993-2007
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
26 static_decl_rpc;
28 static int am_parent = 1;
30 extern struct auth_context *negprot_global_auth_context;
31 extern SIG_ATOMIC_T got_sig_term;
32 extern SIG_ATOMIC_T reload_after_sighup;
33 static SIG_ATOMIC_T got_sig_cld;
35 #ifdef WITH_DFS
36 extern int dcelogin_atmost_once;
37 #endif /* WITH_DFS */
39 /* really we should have a top level context structure that has the
40 client file descriptor as an element. That would require a major rewrite :(
42 the following 2 functions are an alternative - they make the file
43 descriptor private to smbd
45 static int server_fd = -1;
47 int smbd_server_fd(void)
49 return server_fd;
52 static void smbd_set_server_fd(int fd)
54 server_fd = fd;
57 int get_client_fd(void)
59 return server_fd;
62 #ifdef CLUSTER_SUPPORT
63 static int client_get_tcp_info(struct sockaddr_storage *server,
64 struct sockaddr_storage *client)
66 socklen_t length;
67 if (server_fd == -1) {
68 return -1;
70 length = sizeof(*server);
71 if (getsockname(server_fd, (struct sockaddr *)server, &length) != 0) {
72 return -1;
74 length = sizeof(*client);
75 if (getpeername(server_fd, (struct sockaddr *)client, &length) != 0) {
76 return -1;
78 return 0;
80 #endif
82 struct event_context *smbd_event_context(void)
84 static struct event_context *ctx;
86 if (!ctx && !(ctx = event_context_init(talloc_autofree_context()))) {
87 smb_panic("Could not init smbd event context");
89 return ctx;
92 struct messaging_context *smbd_messaging_context(void)
94 static struct messaging_context *ctx;
96 if (ctx == NULL) {
97 ctx = messaging_init(talloc_autofree_context(), server_id_self(),
98 smbd_event_context());
100 if (ctx == NULL) {
101 DEBUG(0, ("Could not init smbd messaging context.\n"));
103 return ctx;
106 struct memcache *smbd_memcache(void)
108 static struct memcache *cache;
110 if (!cache
111 && !(cache = memcache_init(talloc_autofree_context(),
112 lp_max_stat_cache_size()*1024))) {
114 smb_panic("Could not init smbd memcache");
116 return cache;
119 /*******************************************************************
120 What to do when smb.conf is updated.
121 ********************************************************************/
123 static void smb_conf_updated(struct messaging_context *msg,
124 void *private_data,
125 uint32_t msg_type,
126 struct server_id server_id,
127 DATA_BLOB *data)
129 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
130 "updated. Reloading.\n"));
131 reload_services(False);
135 /*******************************************************************
136 Delete a statcache entry.
137 ********************************************************************/
139 static void smb_stat_cache_delete(struct messaging_context *msg,
140 void *private_data,
141 uint32_t msg_tnype,
142 struct server_id server_id,
143 DATA_BLOB *data)
145 const char *name = (const char *)data->data;
146 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
147 stat_cache_delete(name);
150 /****************************************************************************
151 Terminate signal.
152 ****************************************************************************/
154 static void sig_term(void)
156 got_sig_term = 1;
157 sys_select_signal(SIGTERM);
160 /****************************************************************************
161 Catch a sighup.
162 ****************************************************************************/
164 static void sig_hup(int sig)
166 reload_after_sighup = 1;
167 sys_select_signal(SIGHUP);
170 /****************************************************************************
171 Catch a sigcld
172 ****************************************************************************/
173 static void sig_cld(int sig)
175 got_sig_cld = 1;
176 sys_select_signal(SIGCLD);
179 /****************************************************************************
180 Send a SIGTERM to our process group.
181 *****************************************************************************/
183 static void killkids(void)
185 if(am_parent) kill(0,SIGTERM);
188 /****************************************************************************
189 Process a sam sync message - not sure whether to do this here or
190 somewhere else.
191 ****************************************************************************/
193 static void msg_sam_sync(struct messaging_context *msg,
194 void *private_data,
195 uint32_t msg_type,
196 struct server_id server_id,
197 DATA_BLOB *data)
199 DEBUG(10, ("** sam sync message received, ignoring\n"));
203 /****************************************************************************
204 Open the socket communication - inetd.
205 ****************************************************************************/
207 static bool open_sockets_inetd(void)
209 /* Started from inetd. fd 0 is the socket. */
210 /* We will abort gracefully when the client or remote system
211 goes away */
212 int fd = dup(0);
214 if (fd < 0 || fd >= FD_SETSIZE) {
215 return false;
218 smbd_set_server_fd(fd);
220 /* close our standard file descriptors */
221 close_low_fds(False); /* Don't close stderr */
223 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
224 set_socket_options(smbd_server_fd(), lp_socket_options());
226 return True;
229 static void msg_exit_server(struct messaging_context *msg,
230 void *private_data,
231 uint32_t msg_type,
232 struct server_id server_id,
233 DATA_BLOB *data)
235 DEBUG(3, ("got a SHUTDOWN message\n"));
236 exit_server_cleanly(NULL);
239 #ifdef DEVELOPER
240 static void msg_inject_fault(struct messaging_context *msg,
241 void *private_data,
242 uint32_t msg_type,
243 struct server_id src,
244 DATA_BLOB *data)
246 int sig;
248 if (data->length != sizeof(sig)) {
250 DEBUG(0, ("Process %s sent bogus signal injection request\n",
251 procid_str_static(&src)));
252 return;
255 sig = *(int *)data->data;
256 if (sig == -1) {
257 exit_server("internal error injected");
258 return;
261 #if HAVE_STRSIGNAL
262 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
263 procid_str_static(&src), sig, strsignal(sig)));
264 #else
265 DEBUG(0, ("Process %s requested injection of signal %d\n",
266 procid_str_static(&src), sig));
267 #endif
269 kill(sys_getpid(), sig);
271 #endif /* DEVELOPER */
273 struct child_pid {
274 struct child_pid *prev, *next;
275 pid_t pid;
278 static struct child_pid *children;
279 static int num_children;
281 static void add_child_pid(pid_t pid)
283 struct child_pid *child;
285 if (lp_max_smbd_processes() == 0) {
286 /* Don't bother with the child list if we don't care anyway */
287 return;
290 child = SMB_MALLOC_P(struct child_pid);
291 if (child == NULL) {
292 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
293 return;
295 child->pid = pid;
296 DLIST_ADD(children, child);
297 num_children += 1;
300 static void remove_child_pid(pid_t pid, bool unclean_shutdown)
302 struct child_pid *child;
304 if (unclean_shutdown) {
305 /* a child terminated uncleanly so tickle all processes to see
306 if they can grab any of the pending locks
308 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n", (unsigned int)pid));
309 messaging_send_buf(smbd_messaging_context(), procid_self(),
310 MSG_SMB_BRL_VALIDATE, NULL, 0);
311 message_send_all(smbd_messaging_context(),
312 MSG_SMB_UNLOCK, NULL, 0, NULL);
315 if (lp_max_smbd_processes() == 0) {
316 /* Don't bother with the child list if we don't care anyway */
317 return;
320 for (child = children; child != NULL; child = child->next) {
321 if (child->pid == pid) {
322 struct child_pid *tmp = child;
323 DLIST_REMOVE(children, child);
324 SAFE_FREE(tmp);
325 num_children -= 1;
326 return;
330 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
333 /****************************************************************************
334 Have we reached the process limit ?
335 ****************************************************************************/
337 static bool allowable_number_of_smbd_processes(void)
339 int max_processes = lp_max_smbd_processes();
341 if (!max_processes)
342 return True;
344 return num_children < max_processes;
347 /****************************************************************************
348 Open the socket communication.
349 ****************************************************************************/
351 static bool open_sockets_smbd(bool is_daemon, bool interactive, const char *smb_ports)
353 int num_interfaces = iface_count();
354 int num_sockets = 0;
355 int fd_listenset[FD_SETSIZE];
356 fd_set listen_set;
357 int s;
358 int maxfd = 0;
359 int i;
360 char *ports;
361 struct dns_reg_state * dns_reg = NULL;
362 unsigned dns_port = 0;
364 #ifdef HAVE_ATEXIT
366 static int atexit_set;
367 if(atexit_set == 0) {
368 atexit_set=1;
369 atexit(killkids);
372 #endif
374 if (!is_daemon) {
376 * Stop zombies the old way.
377 * We aren't forking any new
378 * 'normal' connections when
379 * run from [x]inetd.
381 CatchChild();
382 return open_sockets_inetd();
385 /* Stop zombies */
386 CatchSignal(SIGCLD, sig_cld);
388 FD_ZERO(&listen_set);
390 /* use a reasonable default set of ports - listing on 445 and 139 */
391 if (!smb_ports) {
392 ports = lp_smb_ports();
393 if (!ports || !*ports) {
394 ports = smb_xstrdup(SMB_PORTS);
395 } else {
396 ports = smb_xstrdup(ports);
398 } else {
399 ports = smb_xstrdup(smb_ports);
402 if (lp_interfaces() && lp_bind_interfaces_only()) {
403 /* We have been given an interfaces line, and been
404 told to only bind to those interfaces. Create a
405 socket per interface and bind to only these.
408 /* Now open a listen socket for each of the
409 interfaces. */
410 for(i = 0; i < num_interfaces; i++) {
411 TALLOC_CTX *frame = NULL;
412 const struct sockaddr_storage *ifss =
413 iface_n_sockaddr_storage(i);
414 char *tok;
415 const char *ptr;
417 if (ifss == NULL) {
418 DEBUG(0,("open_sockets_smbd: "
419 "interface %d has NULL IP address !\n",
420 i));
421 continue;
424 frame = talloc_stackframe();
425 for (ptr=ports;
426 next_token_talloc(frame,&ptr, &tok, " \t,");) {
427 unsigned port = atoi(tok);
428 if (port == 0 || port > 0xffff) {
429 continue;
432 /* Keep the first port for mDNS service
433 * registration.
435 if (dns_port == 0) {
436 dns_port = port;
439 s = fd_listenset[num_sockets] =
440 open_socket_in(SOCK_STREAM,
441 port,
442 num_sockets == 0 ? 0 : 2,
443 ifss,
444 true);
445 if(s < 0 || s >= FD_SETSIZE) {
446 close(s);
447 continue;
450 /* ready to listen */
451 set_socket_options(s,"SO_KEEPALIVE");
452 set_socket_options(s,lp_socket_options());
454 /* Set server socket to
455 * non-blocking for the accept. */
456 set_blocking(s,False);
458 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
459 DEBUG(0,("open_sockets_smbd: listen: "
460 "%s\n", strerror(errno)));
461 close(s);
462 TALLOC_FREE(frame);
463 return False;
465 FD_SET(s,&listen_set);
466 maxfd = MAX( maxfd, s);
468 num_sockets++;
469 if (num_sockets >= FD_SETSIZE) {
470 DEBUG(0,("open_sockets_smbd: Too "
471 "many sockets to bind to\n"));
472 TALLOC_FREE(frame);
473 return False;
476 TALLOC_FREE(frame);
478 } else {
479 /* Just bind to 0.0.0.0 - accept connections
480 from anywhere. */
482 TALLOC_CTX *frame = talloc_stackframe();
483 char *tok;
484 const char *ptr;
485 const char *sock_addr = lp_socket_address();
486 char *sock_tok;
487 const char *sock_ptr;
489 if (strequal(sock_addr, "0.0.0.0") ||
490 strequal(sock_addr, "::")) {
491 #if HAVE_IPV6
492 sock_addr = "::,0.0.0.0";
493 #else
494 sock_addr = "0.0.0.0";
495 #endif
498 for (sock_ptr=sock_addr;
499 next_token_talloc(frame, &sock_ptr, &sock_tok, " \t,"); ) {
500 for (ptr=ports; next_token_talloc(frame, &ptr, &tok, " \t,"); ) {
501 struct sockaddr_storage ss;
503 unsigned port = atoi(tok);
504 if (port == 0 || port > 0xffff) {
505 continue;
508 /* Keep the first port for mDNS service
509 * registration.
511 if (dns_port == 0) {
512 dns_port = port;
515 /* open an incoming socket */
516 if (!interpret_string_addr(&ss, sock_tok,
517 AI_NUMERICHOST|AI_PASSIVE)) {
518 continue;
521 s = open_socket_in(SOCK_STREAM,
522 port,
523 num_sockets == 0 ? 0 : 2,
524 &ss,
525 true);
526 if (s < 0 || s >= FD_SETSIZE) {
527 continue;
530 /* ready to listen */
531 set_socket_options(s,"SO_KEEPALIVE");
532 set_socket_options(s,lp_socket_options());
534 /* Set server socket to non-blocking
535 * for the accept. */
536 set_blocking(s,False);
538 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
539 DEBUG(0,("open_sockets_smbd: "
540 "listen: %s\n",
541 strerror(errno)));
542 close(s);
543 TALLOC_FREE(frame);
544 return False;
547 fd_listenset[num_sockets] = s;
548 FD_SET(s,&listen_set);
549 maxfd = MAX( maxfd, s);
551 num_sockets++;
553 if (num_sockets >= FD_SETSIZE) {
554 DEBUG(0,("open_sockets_smbd: Too "
555 "many sockets to bind to\n"));
556 TALLOC_FREE(frame);
557 return False;
561 TALLOC_FREE(frame);
564 SAFE_FREE(ports);
566 if (num_sockets == 0) {
567 DEBUG(0,("open_sockets_smbd: No "
568 "sockets available to bind to.\n"));
569 return false;
572 /* Setup the main smbd so that we can get messages. Note that
573 do this after starting listening. This is needed as when in
574 clustered mode, ctdb won't allow us to start doing database
575 operations until it has gone thru a full startup, which
576 includes checking to see that smbd is listening. */
577 claim_connection(NULL,"",
578 FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_DBWRAP);
580 /* Listen to messages */
582 messaging_register(smbd_messaging_context(), NULL,
583 MSG_SMB_SAM_SYNC, msg_sam_sync);
584 messaging_register(smbd_messaging_context(), NULL,
585 MSG_SHUTDOWN, msg_exit_server);
586 messaging_register(smbd_messaging_context(), NULL,
587 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
588 messaging_register(smbd_messaging_context(), NULL,
589 MSG_SMB_CONF_UPDATED, smb_conf_updated);
590 messaging_register(smbd_messaging_context(), NULL,
591 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
592 brl_register_msgs(smbd_messaging_context());
594 #ifdef CLUSTER_SUPPORT
595 if (lp_clustering()) {
596 ctdbd_register_reconfigure(messaging_ctdbd_connection());
598 #endif
600 #ifdef DEVELOPER
601 messaging_register(smbd_messaging_context(), NULL,
602 MSG_SMB_INJECT_FAULT, msg_inject_fault);
603 #endif
605 /* Kick off our mDNS registration. */
606 if (dns_port != 0) {
607 #ifdef WITH_AVAHI_SUPPORT
608 void *avahi_conn;
609 avahi_conn = avahi_start_register(
610 smbd_event_context(), smbd_event_context(),
611 dns_port);
612 if (avahi_conn == NULL) {
613 DEBUG(10, ("avahi_start_register failed\n"));
615 #endif
618 /* now accept incoming connections - forking a new process
619 for each incoming connection */
620 DEBUG(2,("waiting for a connection\n"));
621 while (1) {
622 struct timeval now, idle_timeout;
623 fd_set r_fds, w_fds;
624 int num;
626 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
627 message_dispatch(smbd_messaging_context());
629 if (got_sig_cld) {
630 pid_t pid;
631 int status;
633 got_sig_cld = False;
635 while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
636 bool unclean_shutdown = False;
638 /* If the child terminated normally, assume
639 it was an unclean shutdown unless the
640 status is 0
642 if (WIFEXITED(status)) {
643 unclean_shutdown = WEXITSTATUS(status);
645 /* If the child terminated due to a signal
646 we always assume it was unclean.
648 if (WIFSIGNALED(status)) {
649 unclean_shutdown = True;
651 remove_child_pid(pid, unclean_shutdown);
655 idle_timeout = timeval_zero();
657 memcpy((char *)&r_fds, (char *)&listen_set,
658 sizeof(listen_set));
659 FD_ZERO(&w_fds);
660 GetTimeOfDay(&now);
662 /* Kick off our mDNS registration. */
663 if (dns_port != 0) {
664 dns_register_smbd(&dns_reg, dns_port, &maxfd,
665 &r_fds, &idle_timeout);
668 event_add_to_select_args(smbd_event_context(), &now,
669 &r_fds, &w_fds, &idle_timeout,
670 &maxfd);
672 num = sys_select(maxfd+1,&r_fds,&w_fds,NULL,
673 timeval_is_zero(&idle_timeout) ?
674 NULL : &idle_timeout);
676 if (num == -1 && errno == EINTR) {
677 if (got_sig_term) {
678 exit_server_cleanly(NULL);
681 /* check for sighup processing */
682 if (reload_after_sighup) {
683 change_to_root_user();
684 DEBUG(1,("Reloading services after SIGHUP\n"));
685 reload_services(False);
686 reload_after_sighup = 0;
689 continue;
693 /* If the idle timeout fired and we don't have any connected
694 * users, exit gracefully. We should be running under a process
695 * controller that will restart us if necessry.
697 if (num == 0 && count_all_current_connections() == 0) {
698 exit_server_cleanly("idle timeout");
701 /* process pending nDNS responses */
702 if (dns_register_smbd_reply(dns_reg, &r_fds, &idle_timeout)) {
703 --num;
706 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
707 continue;
710 /* check if we need to reload services */
711 check_reload(time(NULL));
713 /* Find the sockets that are read-ready -
714 accept on these. */
715 for( ; num > 0; num--) {
716 struct sockaddr addr;
717 socklen_t in_addrlen = sizeof(addr);
718 pid_t child = 0;
719 int fd;
721 s = -1;
722 for(i = 0; i < num_sockets; i++) {
723 if(FD_ISSET(fd_listenset[i],&r_fds)) {
724 s = fd_listenset[i];
725 /* Clear this so we don't look
726 at it again. */
727 FD_CLR(fd_listenset[i],&r_fds);
728 break;
732 fd = accept(s,&addr,&in_addrlen);
733 if (fd == -1 && errno == EINTR)
734 continue;
735 if (fd == -1) {
736 DEBUG(2,("open_sockets_smbd: accept: %s\n",
737 strerror(errno)));
738 continue;
740 if (fd < 0 || fd >= FD_SETSIZE) {
741 DEBUG(2,("open_sockets_smbd: bad fd %d\n",
742 fd ));
743 continue;
746 smbd_set_server_fd(fd);
748 /* Ensure child is set to blocking mode */
749 set_blocking(smbd_server_fd(),True);
751 if (smbd_server_fd() != -1 && interactive)
752 return True;
754 if (allowable_number_of_smbd_processes() &&
755 smbd_server_fd() != -1 &&
756 ((child = sys_fork())==0)) {
757 char remaddr[INET6_ADDRSTRLEN];
759 /* Child code ... */
761 /* Stop zombies, the parent explicitly handles
762 * them, counting worker smbds. */
763 CatchChild();
765 /* close the listening socket(s) */
766 for(i = 0; i < num_sockets; i++)
767 close(fd_listenset[i]);
769 /* close our mDNS daemon handle */
770 dns_register_close(&dns_reg);
772 /* close our standard file
773 descriptors */
774 close_low_fds(False);
775 am_parent = 0;
777 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
778 set_socket_options(smbd_server_fd(),
779 lp_socket_options());
781 /* this is needed so that we get decent entries
782 in smbstatus for port 445 connects */
783 set_remote_machine_name(get_peer_addr(smbd_server_fd(),
784 remaddr,
785 sizeof(remaddr)),
786 false);
788 if (!reinit_after_fork(
789 smbd_messaging_context(),
790 smbd_event_context(),
791 true)) {
792 DEBUG(0,("reinit_after_fork() failed\n"));
793 smb_panic("reinit_after_fork() failed");
796 return True;
798 /* The parent doesn't need this socket */
799 close(smbd_server_fd());
801 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
802 Clear the closed fd info out of server_fd --
803 and more importantly, out of client_fd in
804 util_sock.c, to avoid a possible
805 getpeername failure if we reopen the logs
806 and use %I in the filename.
809 smbd_set_server_fd(-1);
811 if (child != 0) {
812 add_child_pid(child);
815 /* Force parent to check log size after
816 * spawning child. Fix from
817 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
818 * parent smbd will log to logserver.smb. It
819 * writes only two messages for each child
820 * started/finished. But each child writes,
821 * say, 50 messages also in logserver.smb,
822 * begining with the debug_count of the
823 * parent, before the child opens its own log
824 * file logserver.client. In a worst case
825 * scenario the size of logserver.smb would be
826 * checked after about 50*50=2500 messages
827 * (ca. 100kb).
828 * */
829 force_check_log_size();
831 } /* end for num */
832 } /* end while 1 */
834 /* NOTREACHED return True; */
837 /****************************************************************************
838 Reload printers
839 **************************************************************************/
840 void reload_printers(void)
842 int snum;
843 int n_services = lp_numservices();
844 int pnum = lp_servicenumber(PRINTERS_NAME);
845 const char *pname;
847 pcap_cache_reload();
849 /* remove stale printers */
850 for (snum = 0; snum < n_services; snum++) {
851 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
852 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
853 lp_autoloaded(snum)))
854 continue;
856 pname = lp_printername(snum);
857 if (!pcap_printername_ok(pname)) {
858 DEBUG(3, ("removing stale printer %s\n", pname));
860 if (is_printer_published(NULL, snum, NULL))
861 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
862 del_a_printer(pname);
863 lp_killservice(snum);
867 load_printers();
870 /****************************************************************************
871 Reload the services file.
872 **************************************************************************/
874 bool reload_services(bool test)
876 bool ret;
878 if (lp_loaded()) {
879 char *fname = lp_configfile();
880 if (file_exist(fname, NULL) &&
881 !strcsequal(fname, get_dyn_CONFIGFILE())) {
882 set_dyn_CONFIGFILE(fname);
883 test = False;
887 reopen_logs();
889 if (test && !lp_file_list_changed())
890 return(True);
892 lp_killunused(conn_snum_used);
894 ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
896 reload_printers();
898 /* perhaps the config filename is now set */
899 if (!test)
900 reload_services(True);
902 reopen_logs();
904 load_interfaces();
906 if (smbd_server_fd() != -1) {
907 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
908 set_socket_options(smbd_server_fd(), lp_socket_options());
911 mangle_reset_cache();
912 reset_stat_cache();
914 /* this forces service parameters to be flushed */
915 set_current_service(NULL,0,True);
917 return(ret);
920 /****************************************************************************
921 Exit the server.
922 ****************************************************************************/
924 /* Reasons for shutting down a server process. */
925 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
927 static void exit_server_common(enum server_exit_reason how,
928 const char *const reason) NORETURN_ATTRIBUTE;
930 static void exit_server_common(enum server_exit_reason how,
931 const char *const reason)
933 static int firsttime=1;
934 bool had_open_conn;
936 if (!firsttime)
937 exit(0);
938 firsttime = 0;
940 change_to_root_user();
942 if (negprot_global_auth_context) {
943 (negprot_global_auth_context->free)(&negprot_global_auth_context);
946 had_open_conn = conn_close_all();
948 invalidate_all_vuids();
950 /* 3 second timeout. */
951 print_notify_send_messages(smbd_messaging_context(), 3);
953 /* delete our entry in the connections database. */
954 yield_connection(NULL,"");
956 respond_to_all_remaining_local_messages();
958 #ifdef WITH_DFS
959 if (dcelogin_atmost_once) {
960 dfs_unlogin();
962 #endif
964 #ifdef USE_DMAPI
965 /* Destroy Samba DMAPI session only if we are master smbd process */
966 if (am_parent) {
967 if (!dmapi_destroy_session()) {
968 DEBUG(0,("Unable to close Samba DMAPI session\n"));
971 #endif
973 locking_end();
974 printing_end();
976 if (how != SERVER_EXIT_NORMAL) {
977 int oldlevel = DEBUGLEVEL;
979 DEBUGLEVEL = 10;
981 DEBUGSEP(0);
982 DEBUG(0,("Abnormal server exit: %s\n",
983 reason ? reason : "no explanation provided"));
984 DEBUGSEP(0);
986 log_stack_trace();
988 DEBUGLEVEL = oldlevel;
989 dump_core();
991 } else {
992 DEBUG(3,("Server exit (%s)\n",
993 (reason ? reason : "normal exit")));
996 /* if we had any open SMB connections when we exited then we
997 need to tell the parent smbd so that it can trigger a retry
998 of any locks we may have been holding or open files we were
999 blocking */
1000 if (had_open_conn) {
1001 exit(1);
1002 } else {
1003 exit(0);
1007 void exit_server(const char *const explanation)
1009 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
1012 void exit_server_cleanly(const char *const explanation)
1014 exit_server_common(SERVER_EXIT_NORMAL, explanation);
1017 void exit_server_fault(void)
1019 exit_server("critical server fault");
1023 /****************************************************************************
1024 received when we should release a specific IP
1025 ****************************************************************************/
1026 static void release_ip(const char *ip, void *priv)
1028 char addr[INET6_ADDRSTRLEN];
1030 if (strcmp(client_socket_addr(get_client_fd(),addr,sizeof(addr)), ip) == 0) {
1031 /* we can't afford to do a clean exit - that involves
1032 database writes, which would potentially mean we
1033 are still running after the failover has finished -
1034 we have to get rid of this process ID straight
1035 away */
1036 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
1037 ip));
1038 /* note we must exit with non-zero status so the unclean handler gets
1039 called in the parent, so that the brl database is tickled */
1040 _exit(1);
1044 static void msg_release_ip(struct messaging_context *msg_ctx, void *private_data,
1045 uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
1047 release_ip((char *)data->data, NULL);
1050 /****************************************************************************
1051 Initialise connect, service and file structs.
1052 ****************************************************************************/
1054 static bool init_structs(void )
1057 * Set the machine NETBIOS name if not already
1058 * set from the config file.
1061 if (!init_names())
1062 return False;
1064 conn_init();
1066 file_init();
1068 /* for RPC pipes */
1069 init_rpc_pipe_hnd();
1071 init_dptrs();
1073 if (!secrets_init())
1074 return False;
1076 return True;
1080 * Send keepalive packets to our client
1082 static bool keepalive_fn(const struct timeval *now, void *private_data)
1084 if (!send_keepalive(smbd_server_fd())) {
1085 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
1086 return False;
1088 return True;
1092 * Do the recurring check if we're idle
1094 static bool deadtime_fn(const struct timeval *now, void *private_data)
1096 if ((conn_num_open() == 0)
1097 || (conn_idle_all(now->tv_sec))) {
1098 DEBUG( 2, ( "Closing idle connection\n" ) );
1099 messaging_send(smbd_messaging_context(), procid_self(),
1100 MSG_SHUTDOWN, &data_blob_null);
1101 return False;
1104 return True;
1108 * Do the recurring log file and smb.conf reload checks.
1111 static bool housekeeping_fn(const struct timeval *now, void *private_data)
1113 change_to_root_user();
1115 /* update printer queue caches if necessary */
1116 update_monitored_printq_cache();
1118 /* check if we need to reload services */
1119 check_reload(time(NULL));
1121 /* Change machine password if neccessary. */
1122 attempt_machine_password_change();
1125 * Force a log file check.
1127 force_check_log_size();
1128 check_log_size();
1129 return true;
1132 /****************************************************************************
1133 main program.
1134 ****************************************************************************/
1136 /* Declare prototype for build_options() to avoid having to run it through
1137 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1138 prototype generation system is too complicated. */
1140 extern void build_options(bool screen);
1142 int main(int argc,const char *argv[])
1144 /* shall I run as a daemon */
1145 static bool is_daemon = False;
1146 static bool interactive = False;
1147 static bool Fork = True;
1148 static bool no_process_group = False;
1149 static bool log_stdout = False;
1150 static char *ports = NULL;
1151 static char *profile_level = NULL;
1152 int opt;
1153 poptContext pc;
1154 bool print_build_options = False;
1155 enum {
1156 OPT_DAEMON = 1000,
1157 OPT_INTERACTIVE,
1158 OPT_FORK,
1159 OPT_NO_PROCESS_GROUP,
1160 OPT_LOG_STDOUT
1162 struct poptOption long_options[] = {
1163 POPT_AUTOHELP
1164 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1165 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1166 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1167 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1168 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1169 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1170 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1171 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1172 POPT_COMMON_SAMBA
1173 POPT_COMMON_DYNCONFIG
1174 POPT_TABLEEND
1176 TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
1178 TimeInit();
1180 #ifdef HAVE_SET_AUTH_PARAMETERS
1181 set_auth_parameters(argc,argv);
1182 #endif
1184 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1185 while((opt = poptGetNextOpt(pc)) != -1) {
1186 switch (opt) {
1187 case OPT_DAEMON:
1188 is_daemon = true;
1189 break;
1190 case OPT_INTERACTIVE:
1191 interactive = true;
1192 break;
1193 case OPT_FORK:
1194 Fork = false;
1195 break;
1196 case OPT_NO_PROCESS_GROUP:
1197 no_process_group = true;
1198 break;
1199 case OPT_LOG_STDOUT:
1200 log_stdout = true;
1201 break;
1202 case 'b':
1203 print_build_options = True;
1204 break;
1205 default:
1206 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1207 poptBadOption(pc, 0), poptStrerror(opt));
1208 poptPrintUsage(pc, stderr, 0);
1209 exit(1);
1212 poptFreeContext(pc);
1214 if (interactive) {
1215 Fork = False;
1216 log_stdout = True;
1219 setup_logging(argv[0],log_stdout);
1221 if (print_build_options) {
1222 build_options(True); /* Display output to screen as well as debug */
1223 exit(0);
1226 load_case_tables();
1228 #ifdef HAVE_SETLUID
1229 /* needed for SecureWare on SCO */
1230 setluid(0);
1231 #endif
1233 sec_init();
1235 set_remote_machine_name("smbd", False);
1237 if (interactive && (DEBUGLEVEL >= 9)) {
1238 talloc_enable_leak_report();
1241 if (log_stdout && Fork) {
1242 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1243 exit(1);
1246 /* we want to re-seed early to prevent time delays causing
1247 client problems at a later date. (tridge) */
1248 generate_random_buffer(NULL, 0);
1250 /* make absolutely sure we run as root - to handle cases where people
1251 are crazy enough to have it setuid */
1253 gain_root_privilege();
1254 gain_root_group_privilege();
1256 fault_setup((void (*)(void *))exit_server_fault);
1257 dump_core_setup("smbd");
1259 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
1260 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
1262 /* we are never interested in SIGPIPE */
1263 BlockSignals(True,SIGPIPE);
1265 #if defined(SIGFPE)
1266 /* we are never interested in SIGFPE */
1267 BlockSignals(True,SIGFPE);
1268 #endif
1270 #if defined(SIGUSR2)
1271 /* We are no longer interested in USR2 */
1272 BlockSignals(True,SIGUSR2);
1273 #endif
1275 /* POSIX demands that signals are inherited. If the invoking process has
1276 * these signals masked, we will have problems, as we won't recieve them. */
1277 BlockSignals(False, SIGHUP);
1278 BlockSignals(False, SIGUSR1);
1279 BlockSignals(False, SIGTERM);
1281 /* Ensure we leave no zombies until we
1282 * correctly set up child handling below. */
1283 CatchChild();
1285 /* we want total control over the permissions on created files,
1286 so set our umask to 0 */
1287 umask(0);
1289 init_sec_ctx();
1291 reopen_logs();
1293 DEBUG(0,("smbd version %s started.\n", SAMBA_VERSION_STRING));
1294 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1296 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1297 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1299 /* Output the build options to the debug log */
1300 build_options(False);
1302 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1303 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1304 exit(1);
1307 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1308 DEBUG(0, ("error opening config file\n"));
1309 exit(1);
1312 if (smbd_messaging_context() == NULL)
1313 exit(1);
1315 if (!reload_services(False))
1316 return(-1);
1318 init_structs();
1320 #ifdef WITH_PROFILE
1321 if (!profile_setup(smbd_messaging_context(), False)) {
1322 DEBUG(0,("ERROR: failed to setup profiling\n"));
1323 return -1;
1325 if (profile_level != NULL) {
1326 int pl = atoi(profile_level);
1327 struct server_id src;
1329 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1330 src.pid = getpid();
1331 set_profile_level(pl, src);
1333 #endif
1335 DEBUG(3,( "loaded services\n"));
1337 if (!is_daemon && !is_a_socket(0)) {
1338 if (!interactive)
1339 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1342 * Setting is_daemon here prevents us from eventually calling
1343 * the open_sockets_inetd()
1346 is_daemon = True;
1349 if (is_daemon && !interactive) {
1350 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1351 become_daemon(Fork, no_process_group);
1354 #if HAVE_SETPGID
1356 * If we're interactive we want to set our own process group for
1357 * signal management.
1359 if (interactive && !no_process_group)
1360 setpgid( (pid_t)0, (pid_t)0);
1361 #endif
1363 if (!directory_exist(lp_lockdir(), NULL))
1364 mkdir(lp_lockdir(), 0755);
1366 if (is_daemon)
1367 pidfile_create("smbd");
1369 if (!reinit_after_fork(smbd_messaging_context(),
1370 smbd_event_context(), false)) {
1371 DEBUG(0,("reinit_after_fork() failed\n"));
1372 exit(1);
1375 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1377 if (smbd_memcache() == NULL) {
1378 exit(1);
1381 memcache_set_global(smbd_memcache());
1383 /* Initialise the password backed before the global_sam_sid
1384 to ensure that we fetch from ldap before we make a domain sid up */
1386 if(!initialize_password_db(False, smbd_event_context()))
1387 exit(1);
1389 if (!secrets_init()) {
1390 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1391 exit(1);
1394 if(!get_global_sam_sid()) {
1395 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1396 exit(1);
1399 if (!session_init())
1400 exit(1);
1402 if (!connections_init(True))
1403 exit(1);
1405 if (!locking_init())
1406 exit(1);
1408 namecache_enable();
1410 if (!W_ERROR_IS_OK(registry_init_full()))
1411 exit(1);
1413 #if 0
1414 if (!init_svcctl_db())
1415 exit(1);
1416 #endif
1418 if (!print_backend_init(smbd_messaging_context()))
1419 exit(1);
1421 if (!init_guest_info()) {
1422 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1423 return -1;
1426 /* only start the background queue daemon if we are
1427 running as a daemon -- bad things will happen if
1428 smbd is launched via inetd and we fork a copy of
1429 ourselves here */
1431 if (is_daemon && !interactive
1432 && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1433 start_background_queue();
1436 if (!open_sockets_smbd(is_daemon, interactive, ports))
1437 exit(1);
1440 * everything after this point is run after the fork()
1443 static_init_rpc;
1445 init_modules();
1447 /* Possibly reload the services file. Only worth doing in
1448 * daemon mode. In inetd mode, we know we only just loaded this.
1450 if (is_daemon) {
1451 reload_services(True);
1454 if (!init_account_policy()) {
1455 DEBUG(0,("Could not open account policy tdb.\n"));
1456 exit(1);
1459 if (*lp_rootdir()) {
1460 if (sys_chroot(lp_rootdir()) != 0) {
1461 DEBUG(0,("Failed to change root to %s\n", lp_rootdir()));
1462 exit(1);
1464 if (chdir("/") == -1) {
1465 DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir()));
1466 exit(1);
1468 DEBUG(0,("Changed root to %s\n", lp_rootdir()));
1471 /* Setup oplocks */
1472 if (!init_oplocks(smbd_messaging_context()))
1473 exit(1);
1475 /* Setup aio signal handler. */
1476 initialize_async_io_handler();
1478 /* register our message handlers */
1479 messaging_register(smbd_messaging_context(), NULL,
1480 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1481 messaging_register(smbd_messaging_context(), NULL,
1482 MSG_SMB_RELEASE_IP, msg_release_ip);
1483 messaging_register(smbd_messaging_context(), NULL,
1484 MSG_SMB_CLOSE_FILE, msg_close_file);
1486 if ((lp_keepalive() != 0)
1487 && !(event_add_idle(smbd_event_context(), NULL,
1488 timeval_set(lp_keepalive(), 0),
1489 "keepalive", keepalive_fn,
1490 NULL))) {
1491 DEBUG(0, ("Could not add keepalive event\n"));
1492 exit(1);
1495 if (!(event_add_idle(smbd_event_context(), NULL,
1496 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1497 "deadtime", deadtime_fn, NULL))) {
1498 DEBUG(0, ("Could not add deadtime event\n"));
1499 exit(1);
1502 if (!(event_add_idle(smbd_event_context(), NULL,
1503 timeval_set(SMBD_SELECT_TIMEOUT, 0),
1504 "housekeeping", housekeeping_fn, NULL))) {
1505 DEBUG(0, ("Could not add housekeeping event\n"));
1506 exit(1);
1509 #ifdef CLUSTER_SUPPORT
1511 if (lp_clustering()) {
1513 * We need to tell ctdb about our client's TCP
1514 * connection, so that for failover ctdbd can send
1515 * tickle acks, triggering a reconnection by the
1516 * client.
1519 struct sockaddr_storage srv, clnt;
1521 if (client_get_tcp_info(&srv, &clnt) == 0) {
1523 NTSTATUS status;
1525 status = ctdbd_register_ips(
1526 messaging_ctdbd_connection(),
1527 &srv, &clnt, release_ip, NULL);
1529 if (!NT_STATUS_IS_OK(status)) {
1530 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
1531 nt_errstr(status)));
1533 } else
1535 DEBUG(0,("Unable to get tcp info for "
1536 "CTDB_CONTROL_TCP_CLIENT: %s\n",
1537 strerror(errno)));
1541 #endif
1543 TALLOC_FREE(frame);
1545 smbd_process();
1547 namecache_shutdown();
1549 exit_server_cleanly(NULL);
1550 return(0);