s3-registry: only include registry headers when really needed.
[Samba.git] / source3 / smbd / server.c
blobfcfabcd06f07498b583c3aab793d6f841a21184b
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"
25 #include "smbd/globals.h"
26 #include "librpc/gen_ndr/messaging.h"
27 #include "registry.h"
29 static_decl_rpc;
31 #ifdef WITH_DFS
32 extern int dcelogin_atmost_once;
33 #endif /* WITH_DFS */
35 int smbd_server_fd(void)
37 return server_fd;
40 static void smbd_set_server_fd(int fd)
42 server_fd = fd;
45 int get_client_fd(void)
47 return server_fd;
50 struct event_context *smbd_event_context(void)
52 if (!smbd_event_ctx) {
53 smbd_event_ctx = event_context_init(talloc_autofree_context());
55 if (!smbd_event_ctx) {
56 smb_panic("Could not init smbd event context");
58 return smbd_event_ctx;
61 struct messaging_context *smbd_messaging_context(void)
63 if (smbd_msg_ctx == NULL) {
64 smbd_msg_ctx = messaging_init(talloc_autofree_context(),
65 procid_self(),
66 smbd_event_context());
68 if (smbd_msg_ctx == NULL) {
69 DEBUG(0, ("Could not init smbd messaging context.\n"));
71 return smbd_msg_ctx;
74 struct memcache *smbd_memcache(void)
76 if (!smbd_memcache_ctx) {
77 smbd_memcache_ctx = memcache_init(talloc_autofree_context(),
78 lp_max_stat_cache_size()*1024);
80 if (!smbd_memcache_ctx) {
81 smb_panic("Could not init smbd memcache");
84 return smbd_memcache_ctx;
87 /*******************************************************************
88 What to do when smb.conf is updated.
89 ********************************************************************/
91 static void smb_conf_updated(struct messaging_context *msg,
92 void *private_data,
93 uint32_t msg_type,
94 struct server_id server_id,
95 DATA_BLOB *data)
97 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
98 "updated. Reloading.\n"));
99 change_to_root_user();
100 reload_services(False);
104 /*******************************************************************
105 Delete a statcache entry.
106 ********************************************************************/
108 static void smb_stat_cache_delete(struct messaging_context *msg,
109 void *private_data,
110 uint32_t msg_tnype,
111 struct server_id server_id,
112 DATA_BLOB *data)
114 const char *name = (const char *)data->data;
115 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
116 stat_cache_delete(name);
119 /****************************************************************************
120 Send a SIGTERM to our process group.
121 *****************************************************************************/
123 static void killkids(void)
125 if(am_parent) kill(0,SIGTERM);
128 /****************************************************************************
129 Process a sam sync message - not sure whether to do this here or
130 somewhere else.
131 ****************************************************************************/
133 static void msg_sam_sync(struct messaging_context *msg,
134 void *private_data,
135 uint32_t msg_type,
136 struct server_id server_id,
137 DATA_BLOB *data)
139 DEBUG(10, ("** sam sync message received, ignoring\n"));
142 static void msg_exit_server(struct messaging_context *msg,
143 void *private_data,
144 uint32_t msg_type,
145 struct server_id server_id,
146 DATA_BLOB *data)
148 DEBUG(3, ("got a SHUTDOWN message\n"));
149 exit_server_cleanly(NULL);
152 #ifdef DEVELOPER
153 static void msg_inject_fault(struct messaging_context *msg,
154 void *private_data,
155 uint32_t msg_type,
156 struct server_id src,
157 DATA_BLOB *data)
159 int sig;
161 if (data->length != sizeof(sig)) {
162 DEBUG(0, ("Process %s sent bogus signal injection request\n",
163 procid_str_static(&src)));
164 return;
167 sig = *(int *)data->data;
168 if (sig == -1) {
169 exit_server("internal error injected");
170 return;
173 #if HAVE_STRSIGNAL
174 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
175 procid_str_static(&src), sig, strsignal(sig)));
176 #else
177 DEBUG(0, ("Process %s requested injection of signal %d\n",
178 procid_str_static(&src), sig));
179 #endif
181 kill(sys_getpid(), sig);
183 #endif /* DEVELOPER */
186 * Parent smbd process sets its own debug level first and then
187 * sends a message to all the smbd children to adjust their debug
188 * level to that of the parent.
191 static void smbd_msg_debug(struct messaging_context *msg_ctx,
192 void *private_data,
193 uint32_t msg_type,
194 struct server_id server_id,
195 DATA_BLOB *data)
197 struct child_pid *child;
199 debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
201 for (child = children; child != NULL; child = child->next) {
202 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
203 MSG_DEBUG,
204 data->data,
205 strlen((char *) data->data) + 1);
209 static void add_child_pid(pid_t pid)
211 struct child_pid *child;
213 child = SMB_MALLOC_P(struct child_pid);
214 if (child == NULL) {
215 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
216 return;
218 child->pid = pid;
219 DLIST_ADD(children, child);
220 num_children += 1;
224 at most every smbd:cleanuptime seconds (default 20), we scan the BRL
225 and locking database for entries to cleanup. As a side effect this
226 also cleans up dead entries in the connections database (due to the
227 traversal in message_send_all()
229 Using a timer for this prevents a flood of traversals when a large
230 number of clients disconnect at the same time (perhaps due to a
231 network outage).
234 static void cleanup_timeout_fn(struct event_context *event_ctx,
235 struct timed_event *te,
236 struct timeval now,
237 void *private_data)
239 struct timed_event **cleanup_te = (struct timed_event **)private_data;
241 DEBUG(1,("Cleaning up brl and lock database after unclean shutdown\n"));
242 message_send_all(smbd_messaging_context(), MSG_SMB_UNLOCK, NULL, 0, NULL);
243 messaging_send_buf(smbd_messaging_context(), procid_self(),
244 MSG_SMB_BRL_VALIDATE, NULL, 0);
245 /* mark the cleanup as having been done */
246 (*cleanup_te) = NULL;
249 static void remove_child_pid(pid_t pid, bool unclean_shutdown)
251 struct child_pid *child;
252 static struct timed_event *cleanup_te;
253 struct server_id child_id;
255 if (unclean_shutdown) {
256 /* a child terminated uncleanly so tickle all
257 processes to see if they can grab any of the
258 pending locks
260 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n",
261 (unsigned int)pid));
262 if (!cleanup_te) {
263 /* call the cleanup timer, but not too often */
264 int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
265 cleanup_te = event_add_timed(smbd_event_context(), NULL,
266 timeval_current_ofs(cleanup_time, 0),
267 cleanup_timeout_fn,
268 &cleanup_te);
269 DEBUG(1,("Scheduled cleanup of brl and lock database after unclean shutdown\n"));
273 child_id = procid_self(); /* Just initialize pid and potentially vnn */
274 child_id.pid = pid;
276 if (!serverid_deregister(&child_id)) {
277 DEBUG(1, ("Could not remove pid %d from serverid.tdb\n",
278 (int)pid));
281 for (child = children; child != NULL; child = child->next) {
282 if (child->pid == pid) {
283 struct child_pid *tmp = child;
284 DLIST_REMOVE(children, child);
285 SAFE_FREE(tmp);
286 num_children -= 1;
287 return;
291 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
294 /****************************************************************************
295 Have we reached the process limit ?
296 ****************************************************************************/
298 static bool allowable_number_of_smbd_processes(void)
300 int max_processes = lp_max_smbd_processes();
302 if (!max_processes)
303 return True;
305 return num_children < max_processes;
308 static void smbd_sig_chld_handler(struct tevent_context *ev,
309 struct tevent_signal *se,
310 int signum,
311 int count,
312 void *siginfo,
313 void *private_data)
315 pid_t pid;
316 int status;
318 while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
319 bool unclean_shutdown = False;
321 /* If the child terminated normally, assume
322 it was an unclean shutdown unless the
323 status is 0
325 if (WIFEXITED(status)) {
326 unclean_shutdown = WEXITSTATUS(status);
328 /* If the child terminated due to a signal
329 we always assume it was unclean.
331 if (WIFSIGNALED(status)) {
332 unclean_shutdown = True;
334 remove_child_pid(pid, unclean_shutdown);
338 static void smbd_setup_sig_chld_handler(void)
340 struct tevent_signal *se;
342 se = tevent_add_signal(smbd_event_context(),
343 smbd_event_context(),
344 SIGCHLD, 0,
345 smbd_sig_chld_handler,
346 NULL);
347 if (!se) {
348 exit_server("failed to setup SIGCHLD handler");
352 struct smbd_open_socket;
354 struct smbd_parent_context {
355 bool interactive;
357 /* the list of listening sockets */
358 struct smbd_open_socket *sockets;
361 struct smbd_open_socket {
362 struct smbd_open_socket *prev, *next;
363 struct smbd_parent_context *parent;
364 int fd;
365 struct tevent_fd *fde;
368 static void smbd_open_socket_close_fn(struct tevent_context *ev,
369 struct tevent_fd *fde,
370 int fd,
371 void *private_data)
373 /* this might be the socket_wrapper swrap_close() */
374 close(fd);
377 static void smbd_accept_connection(struct tevent_context *ev,
378 struct tevent_fd *fde,
379 uint16_t flags,
380 void *private_data)
382 struct smbd_open_socket *s = talloc_get_type_abort(private_data,
383 struct smbd_open_socket);
384 struct sockaddr_storage addr;
385 socklen_t in_addrlen = sizeof(addr);
386 pid_t pid = 0;
387 uint64_t unique_id;
389 smbd_set_server_fd(accept(s->fd,(struct sockaddr *)&addr,&in_addrlen));
391 if (smbd_server_fd() == -1 && errno == EINTR)
392 return;
394 if (smbd_server_fd() == -1) {
395 DEBUG(0,("open_sockets_smbd: accept: %s\n",
396 strerror(errno)));
397 return;
400 if (s->parent->interactive) {
401 smbd_process();
402 exit_server_cleanly("end of interactive mode");
403 return;
406 if (!allowable_number_of_smbd_processes()) {
407 close(smbd_server_fd());
408 smbd_set_server_fd(-1);
409 return;
413 * Generate a unique id in the parent process so that we use
414 * the global random state in the parent.
416 generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
418 pid = sys_fork();
419 if (pid == 0) {
420 NTSTATUS status = NT_STATUS_OK;
422 /* Child code ... */
423 am_parent = 0;
425 set_my_unique_id(unique_id);
427 /* Stop zombies, the parent explicitly handles
428 * them, counting worker smbds. */
429 CatchChild();
431 /* close our standard file
432 descriptors */
433 close_low_fds(False);
436 * Can't use TALLOC_FREE here. Nulling out the argument to it
437 * would overwrite memory we've just freed.
439 talloc_free(s->parent);
440 s = NULL;
442 status = reinit_after_fork(smbd_messaging_context(),
443 smbd_event_context(), true);
444 if (!NT_STATUS_IS_OK(status)) {
445 if (NT_STATUS_EQUAL(status,
446 NT_STATUS_TOO_MANY_OPENED_FILES)) {
447 DEBUG(0,("child process cannot initialize "
448 "because too many files are open\n"));
449 goto exit;
451 DEBUG(0,("reinit_after_fork() failed\n"));
452 smb_panic("reinit_after_fork() failed");
455 smbd_setup_sig_term_handler();
456 smbd_setup_sig_hup_handler();
458 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
459 |FLAG_MSG_DBWRAP
460 |FLAG_MSG_PRINT_GENERAL)) {
461 exit_server_cleanly("Could not register myself in "
462 "serverid.tdb");
465 smbd_process();
466 exit:
467 exit_server_cleanly("end of child");
468 return;
469 } else if (pid < 0) {
470 DEBUG(0,("smbd_accept_connection: sys_fork() failed: %s\n",
471 strerror(errno)));
474 /* The parent doesn't need this socket */
475 close(smbd_server_fd());
477 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
478 Clear the closed fd info out of server_fd --
479 and more importantly, out of client_fd in
480 util_sock.c, to avoid a possible
481 getpeername failure if we reopen the logs
482 and use %I in the filename.
485 smbd_set_server_fd(-1);
487 if (pid != 0) {
488 add_child_pid(pid);
491 /* Force parent to check log size after
492 * spawning child. Fix from
493 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
494 * parent smbd will log to logserver.smb. It
495 * writes only two messages for each child
496 * started/finished. But each child writes,
497 * say, 50 messages also in logserver.smb,
498 * begining with the debug_count of the
499 * parent, before the child opens its own log
500 * file logserver.client. In a worst case
501 * scenario the size of logserver.smb would be
502 * checked after about 50*50=2500 messages
503 * (ca. 100kb).
504 * */
505 force_check_log_size();
508 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
509 const struct sockaddr_storage *ifss,
510 uint16_t port)
512 struct smbd_open_socket *s;
514 s = talloc(parent, struct smbd_open_socket);
515 if (!s) {
516 return false;
519 s->parent = parent;
520 s->fd = open_socket_in(SOCK_STREAM,
521 port,
522 parent->sockets == NULL ? 0 : 2,
523 ifss,
524 true);
525 if (s->fd == -1) {
526 DEBUG(0,("smbd_open_once_socket: open_socket_in: "
527 "%s\n", strerror(errno)));
528 TALLOC_FREE(s);
530 * We ignore an error here, as we've done before
532 return true;
535 /* ready to listen */
536 set_socket_options(s->fd, "SO_KEEPALIVE");
537 set_socket_options(s->fd, lp_socket_options());
539 /* Set server socket to
540 * non-blocking for the accept. */
541 set_blocking(s->fd, False);
543 if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
544 DEBUG(0,("open_sockets_smbd: listen: "
545 "%s\n", strerror(errno)));
546 close(s->fd);
547 TALLOC_FREE(s);
548 return false;
551 s->fde = tevent_add_fd(smbd_event_context(),
553 s->fd, TEVENT_FD_READ,
554 smbd_accept_connection,
556 if (!s->fde) {
557 DEBUG(0,("open_sockets_smbd: "
558 "tevent_add_fd: %s\n",
559 strerror(errno)));
560 close(s->fd);
561 TALLOC_FREE(s);
562 return false;
564 tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
566 DLIST_ADD_END(parent->sockets, s, struct smbd_open_socket *);
568 return true;
571 /****************************************************************************
572 Open the socket communication.
573 ****************************************************************************/
575 static bool open_sockets_smbd(struct smbd_parent_context *parent,
576 const char *smb_ports)
578 int num_interfaces = iface_count();
579 int i;
580 char *ports;
581 unsigned dns_port = 0;
583 #ifdef HAVE_ATEXIT
584 atexit(killkids);
585 #endif
587 /* Stop zombies */
588 smbd_setup_sig_chld_handler();
590 /* use a reasonable default set of ports - listing on 445 and 139 */
591 if (!smb_ports) {
592 ports = lp_smb_ports();
593 if (!ports || !*ports) {
594 ports = talloc_strdup(talloc_tos(), SMB_PORTS);
595 } else {
596 ports = talloc_strdup(talloc_tos(), ports);
598 } else {
599 ports = talloc_strdup(talloc_tos(), smb_ports);
602 if (lp_interfaces() && lp_bind_interfaces_only()) {
603 /* We have been given an interfaces line, and been
604 told to only bind to those interfaces. Create a
605 socket per interface and bind to only these.
608 /* Now open a listen socket for each of the
609 interfaces. */
610 for(i = 0; i < num_interfaces; i++) {
611 const struct sockaddr_storage *ifss =
612 iface_n_sockaddr_storage(i);
613 char *tok;
614 const char *ptr;
616 if (ifss == NULL) {
617 DEBUG(0,("open_sockets_smbd: "
618 "interface %d has NULL IP address !\n",
619 i));
620 continue;
623 for (ptr=ports;
624 next_token_talloc(talloc_tos(),&ptr, &tok, " \t,");) {
625 unsigned port = atoi(tok);
626 if (port == 0 || port > 0xffff) {
627 continue;
630 if (!smbd_open_one_socket(parent, ifss, port)) {
631 return false;
635 } else {
636 /* Just bind to 0.0.0.0 - accept connections
637 from anywhere. */
639 char *tok;
640 const char *ptr;
641 const char *sock_addr = lp_socket_address();
642 char *sock_tok;
643 const char *sock_ptr;
645 if (strequal(sock_addr, "0.0.0.0") ||
646 strequal(sock_addr, "::")) {
647 #if HAVE_IPV6
648 sock_addr = "::,0.0.0.0";
649 #else
650 sock_addr = "0.0.0.0";
651 #endif
654 for (sock_ptr=sock_addr;
655 next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
656 for (ptr=ports; next_token_talloc(talloc_tos(), &ptr, &tok, " \t,"); ) {
657 struct sockaddr_storage ss;
659 unsigned port = atoi(tok);
660 if (port == 0 || port > 0xffff) {
661 continue;
664 /* Keep the first port for mDNS service
665 * registration.
667 if (dns_port == 0) {
668 dns_port = port;
671 /* open an incoming socket */
672 if (!interpret_string_addr(&ss, sock_tok,
673 AI_NUMERICHOST|AI_PASSIVE)) {
674 continue;
677 if (!smbd_open_one_socket(parent, &ss, port)) {
678 return false;
684 if (parent->sockets == NULL) {
685 DEBUG(0,("open_sockets_smbd: No "
686 "sockets available to bind to.\n"));
687 return false;
690 /* Setup the main smbd so that we can get messages. Note that
691 do this after starting listening. This is needed as when in
692 clustered mode, ctdb won't allow us to start doing database
693 operations until it has gone thru a full startup, which
694 includes checking to see that smbd is listening. */
696 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_SMBD
697 |FLAG_MSG_DBWRAP)) {
698 DEBUG(0, ("open_sockets_smbd: Failed to register "
699 "myself in serverid.tdb\n"));
700 return false;
703 /* Listen to messages */
705 messaging_register(smbd_messaging_context(), NULL,
706 MSG_SMB_SAM_SYNC, msg_sam_sync);
707 messaging_register(smbd_messaging_context(), NULL,
708 MSG_SHUTDOWN, msg_exit_server);
709 messaging_register(smbd_messaging_context(), NULL,
710 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
711 messaging_register(smbd_messaging_context(), NULL,
712 MSG_SMB_CONF_UPDATED, smb_conf_updated);
713 messaging_register(smbd_messaging_context(), NULL,
714 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
715 messaging_register(smbd_messaging_context(), NULL,
716 MSG_DEBUG, smbd_msg_debug);
717 brl_register_msgs(smbd_messaging_context());
719 #ifdef CLUSTER_SUPPORT
720 if (lp_clustering()) {
721 ctdbd_register_reconfigure(messaging_ctdbd_connection());
723 #endif
725 #ifdef DEVELOPER
726 messaging_register(smbd_messaging_context(), NULL,
727 MSG_SMB_INJECT_FAULT, msg_inject_fault);
728 #endif
730 if (dns_port != 0) {
731 #ifdef WITH_DNSSD_SUPPORT
732 smbd_setup_mdns_registration(smbd_event_context(),
733 parent, dns_port);
734 #endif
735 #ifdef WITH_AVAHI_SUPPORT
736 void *avahi_conn;
738 avahi_conn = avahi_start_register(
739 smbd_event_context(), smbd_event_context(), dns_port);
740 if (avahi_conn == NULL) {
741 DEBUG(10, ("avahi_start_register failed\n"));
743 #endif
746 return true;
749 static void smbd_parent_loop(struct smbd_parent_context *parent)
751 /* now accept incoming connections - forking a new process
752 for each incoming connection */
753 DEBUG(2,("waiting for connections\n"));
754 while (1) {
755 int ret;
756 TALLOC_CTX *frame = talloc_stackframe();
758 ret = tevent_loop_once(smbd_event_context());
759 if (ret != 0) {
760 exit_server_cleanly("tevent_loop_once() error");
763 TALLOC_FREE(frame);
764 } /* end while 1 */
766 /* NOTREACHED return True; */
769 /****************************************************************************
770 Reload printers
771 **************************************************************************/
772 void reload_printers(void)
774 int snum;
775 int n_services = lp_numservices();
776 int pnum = lp_servicenumber(PRINTERS_NAME);
777 const char *pname;
779 pcap_cache_reload();
781 /* remove stale printers */
782 for (snum = 0; snum < n_services; snum++) {
783 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
784 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
785 lp_autoloaded(snum)))
786 continue;
788 pname = lp_printername(snum);
789 if (!pcap_printername_ok(pname)) {
790 DEBUG(3, ("removing stale printer %s\n", pname));
792 if (is_printer_published(NULL, snum, NULL))
793 nt_printer_publish(NULL, snum, DSPRINT_UNPUBLISH);
794 del_a_printer(pname);
795 lp_killservice(snum);
799 load_printers();
802 /****************************************************************************
803 Reload the services file.
804 **************************************************************************/
806 bool reload_services(bool test)
808 bool ret;
810 if (lp_loaded()) {
811 char *fname = lp_configfile();
812 if (file_exist(fname) &&
813 !strcsequal(fname, get_dyn_CONFIGFILE())) {
814 set_dyn_CONFIGFILE(fname);
815 test = False;
819 reopen_logs();
821 if (test && !lp_file_list_changed())
822 return(True);
824 lp_killunused(conn_snum_used);
826 ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
828 reload_printers();
830 /* perhaps the config filename is now set */
831 if (!test)
832 reload_services(True);
834 reopen_logs();
836 load_interfaces();
838 if (smbd_server_fd() != -1) {
839 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
840 set_socket_options(smbd_server_fd(), lp_socket_options());
843 mangle_reset_cache();
844 reset_stat_cache();
846 /* this forces service parameters to be flushed */
847 set_current_service(NULL,0,True);
849 return(ret);
852 static struct files_struct *log_writeable_file_fn(
853 struct files_struct *fsp, void *private_data)
855 bool *found = (bool *)private_data;
856 char *path;
858 if (!fsp->can_write) {
859 return NULL;
861 if (!(*found)) {
862 DEBUG(0, ("Writable files open at exit:\n"));
863 *found = true;
866 path = talloc_asprintf(talloc_tos(), "%s/%s", fsp->conn->connectpath,
867 smb_fname_str_dbg(fsp->fsp_name));
868 if (path == NULL) {
869 DEBUGADD(0, ("<NOMEM>\n"));
872 DEBUGADD(0, ("%s\n", path));
874 TALLOC_FREE(path);
875 return NULL;
878 /****************************************************************************
879 Exit the server.
880 ****************************************************************************/
882 /* Reasons for shutting down a server process. */
883 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
885 static void exit_server_common(enum server_exit_reason how,
886 const char *const reason) _NORETURN_;
888 static void exit_server_common(enum server_exit_reason how,
889 const char *const reason)
891 bool had_open_conn = false;
892 struct smbd_server_connection *sconn = smbd_server_conn;
894 if (!exit_firsttime)
895 exit(0);
896 exit_firsttime = false;
898 change_to_root_user();
900 if (sconn && sconn->smb1.negprot.auth_context) {
901 struct auth_context *a = sconn->smb1.negprot.auth_context;
902 a->free(&sconn->smb1.negprot.auth_context);
905 if (lp_log_writeable_files_on_exit()) {
906 bool found = false;
907 files_forall(log_writeable_file_fn, &found);
910 if (sconn) {
911 had_open_conn = conn_close_all(sconn);
912 invalidate_all_vuids(sconn);
915 /* 3 second timeout. */
916 print_notify_send_messages(smbd_messaging_context(), 3);
918 /* delete our entry in the serverid database. */
919 serverid_deregister_self();
921 #ifdef WITH_DFS
922 if (dcelogin_atmost_once) {
923 dfs_unlogin();
925 #endif
927 #ifdef USE_DMAPI
928 /* Destroy Samba DMAPI session only if we are master smbd process */
929 if (am_parent) {
930 if (!dmapi_destroy_session()) {
931 DEBUG(0,("Unable to close Samba DMAPI session\n"));
934 #endif
936 locking_end();
937 printing_end();
940 * we need to force the order of freeing the following,
941 * because smbd_msg_ctx is not a talloc child of smbd_server_conn.
943 sconn = NULL;
944 TALLOC_FREE(smbd_server_conn);
945 TALLOC_FREE(smbd_msg_ctx);
946 TALLOC_FREE(smbd_event_ctx);
948 if (how != SERVER_EXIT_NORMAL) {
949 int oldlevel = DEBUGLEVEL;
951 DEBUGLEVEL = 10;
953 DEBUGSEP(0);
954 DEBUG(0,("Abnormal server exit: %s\n",
955 reason ? reason : "no explanation provided"));
956 DEBUGSEP(0);
958 log_stack_trace();
960 DEBUGLEVEL = oldlevel;
961 dump_core();
963 } else {
964 DEBUG(3,("Server exit (%s)\n",
965 (reason ? reason : "normal exit")));
966 if (am_parent) {
967 pidfile_unlink();
969 gencache_stabilize();
972 /* if we had any open SMB connections when we exited then we
973 need to tell the parent smbd so that it can trigger a retry
974 of any locks we may have been holding or open files we were
975 blocking */
976 if (had_open_conn) {
977 exit(1);
978 } else {
979 exit(0);
983 void exit_server(const char *const explanation)
985 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
988 void exit_server_cleanly(const char *const explanation)
990 exit_server_common(SERVER_EXIT_NORMAL, explanation);
993 void exit_server_fault(void)
995 exit_server("critical server fault");
998 /****************************************************************************
999 Initialise connect, service and file structs.
1000 ****************************************************************************/
1002 static bool init_structs(void )
1005 * Set the machine NETBIOS name if not already
1006 * set from the config file.
1009 if (!init_names())
1010 return False;
1012 file_init();
1014 if (!secrets_init())
1015 return False;
1017 return True;
1020 /****************************************************************************
1021 main program.
1022 ****************************************************************************/
1024 /* Declare prototype for build_options() to avoid having to run it through
1025 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1026 prototype generation system is too complicated. */
1028 extern void build_options(bool screen);
1030 int main(int argc,const char *argv[])
1032 /* shall I run as a daemon */
1033 bool is_daemon = false;
1034 bool interactive = false;
1035 bool Fork = true;
1036 bool no_process_group = false;
1037 bool log_stdout = false;
1038 char *ports = NULL;
1039 char *profile_level = NULL;
1040 int opt;
1041 poptContext pc;
1042 bool print_build_options = False;
1043 enum {
1044 OPT_DAEMON = 1000,
1045 OPT_INTERACTIVE,
1046 OPT_FORK,
1047 OPT_NO_PROCESS_GROUP,
1048 OPT_LOG_STDOUT
1050 struct poptOption long_options[] = {
1051 POPT_AUTOHELP
1052 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1053 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1054 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1055 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1056 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1057 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1058 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1059 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1060 POPT_COMMON_SAMBA
1061 POPT_COMMON_DYNCONFIG
1062 POPT_TABLEEND
1064 struct smbd_parent_context *parent = NULL;
1065 TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
1067 smbd_init_globals();
1069 TimeInit();
1071 #ifdef HAVE_SET_AUTH_PARAMETERS
1072 set_auth_parameters(argc,argv);
1073 #endif
1075 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1076 while((opt = poptGetNextOpt(pc)) != -1) {
1077 switch (opt) {
1078 case OPT_DAEMON:
1079 is_daemon = true;
1080 break;
1081 case OPT_INTERACTIVE:
1082 interactive = true;
1083 break;
1084 case OPT_FORK:
1085 Fork = false;
1086 break;
1087 case OPT_NO_PROCESS_GROUP:
1088 no_process_group = true;
1089 break;
1090 case OPT_LOG_STDOUT:
1091 log_stdout = true;
1092 break;
1093 case 'b':
1094 print_build_options = True;
1095 break;
1096 default:
1097 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1098 poptBadOption(pc, 0), poptStrerror(opt));
1099 poptPrintUsage(pc, stderr, 0);
1100 exit(1);
1103 poptFreeContext(pc);
1105 if (interactive) {
1106 Fork = False;
1107 log_stdout = True;
1110 setup_logging(argv[0],log_stdout);
1112 if (print_build_options) {
1113 build_options(True); /* Display output to screen as well as debug */
1114 exit(0);
1117 load_case_tables();
1119 #ifdef HAVE_SETLUID
1120 /* needed for SecureWare on SCO */
1121 setluid(0);
1122 #endif
1124 sec_init();
1126 set_remote_machine_name("smbd", False);
1128 if (interactive && (DEBUGLEVEL >= 9)) {
1129 talloc_enable_leak_report();
1132 if (log_stdout && Fork) {
1133 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1134 exit(1);
1137 /* we want to re-seed early to prevent time delays causing
1138 client problems at a later date. (tridge) */
1139 generate_random_buffer(NULL, 0);
1141 /* make absolutely sure we run as root - to handle cases where people
1142 are crazy enough to have it setuid */
1144 gain_root_privilege();
1145 gain_root_group_privilege();
1147 fault_setup((void (*)(void *))exit_server_fault);
1148 dump_core_setup("smbd");
1150 /* we are never interested in SIGPIPE */
1151 BlockSignals(True,SIGPIPE);
1153 #if defined(SIGFPE)
1154 /* we are never interested in SIGFPE */
1155 BlockSignals(True,SIGFPE);
1156 #endif
1158 #if defined(SIGUSR2)
1159 /* We are no longer interested in USR2 */
1160 BlockSignals(True,SIGUSR2);
1161 #endif
1163 /* POSIX demands that signals are inherited. If the invoking process has
1164 * these signals masked, we will have problems, as we won't recieve them. */
1165 BlockSignals(False, SIGHUP);
1166 BlockSignals(False, SIGUSR1);
1167 BlockSignals(False, SIGTERM);
1169 /* Ensure we leave no zombies until we
1170 * correctly set up child handling below. */
1172 CatchChild();
1174 /* we want total control over the permissions on created files,
1175 so set our umask to 0 */
1176 umask(0);
1178 init_sec_ctx();
1180 reopen_logs();
1182 DEBUG(0,("smbd version %s started.\n", samba_version_string()));
1183 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1185 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1186 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1188 /* Output the build options to the debug log */
1189 build_options(False);
1191 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1192 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1193 exit(1);
1196 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1197 DEBUG(0, ("error opening config file\n"));
1198 exit(1);
1201 if (smbd_messaging_context() == NULL)
1202 exit(1);
1204 if (!reload_services(False))
1205 return(-1);
1207 init_structs();
1209 #ifdef WITH_PROFILE
1210 if (!profile_setup(smbd_messaging_context(), False)) {
1211 DEBUG(0,("ERROR: failed to setup profiling\n"));
1212 return -1;
1214 if (profile_level != NULL) {
1215 int pl = atoi(profile_level);
1216 struct server_id src;
1218 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1219 src.pid = getpid();
1220 set_profile_level(pl, src);
1222 #endif
1224 DEBUG(3,( "loaded services\n"));
1226 if (!is_daemon && !is_a_socket(0)) {
1227 if (!interactive)
1228 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1231 * Setting is_daemon here prevents us from eventually calling
1232 * the open_sockets_inetd()
1235 is_daemon = True;
1238 if (is_daemon && !interactive) {
1239 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1240 become_daemon(Fork, no_process_group, log_stdout);
1243 #if HAVE_SETPGID
1245 * If we're interactive we want to set our own process group for
1246 * signal management.
1248 if (interactive && !no_process_group)
1249 setpgid( (pid_t)0, (pid_t)0);
1250 #endif
1252 if (!directory_exist(lp_lockdir()))
1253 mkdir(lp_lockdir(), 0755);
1255 if (is_daemon)
1256 pidfile_create("smbd");
1258 if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1259 smbd_event_context(), false))) {
1260 DEBUG(0,("reinit_after_fork() failed\n"));
1261 exit(1);
1264 smbd_setup_sig_term_handler();
1265 smbd_setup_sig_hup_handler();
1267 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1269 if (smbd_memcache() == NULL) {
1270 exit(1);
1273 memcache_set_global(smbd_memcache());
1275 /* Initialise the password backed before the global_sam_sid
1276 to ensure that we fetch from ldap before we make a domain sid up */
1278 if(!initialize_password_db(False, smbd_event_context()))
1279 exit(1);
1281 if (!secrets_init()) {
1282 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1283 exit(1);
1286 if(!get_global_sam_sid()) {
1287 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1288 exit(1);
1291 if (!sessionid_init()) {
1292 exit(1);
1295 if (!connections_init(True))
1296 exit(1);
1298 if (!locking_init())
1299 exit(1);
1301 if (!messaging_tdb_parent_init()) {
1302 exit(1);
1305 if (!notify_internal_parent_init()) {
1306 exit(1);
1309 if (!serverid_parent_init()) {
1310 exit(1);
1313 if (!W_ERROR_IS_OK(registry_init_full()))
1314 exit(1);
1316 #if 0
1317 if (!init_svcctl_db())
1318 exit(1);
1319 #endif
1321 if (!print_backend_init(smbd_messaging_context()))
1322 exit(1);
1324 if (!init_guest_info()) {
1325 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1326 return -1;
1329 /* Open the share_info.tdb here, so we don't have to open
1330 after the fork on every single connection. This is a small
1331 performance improvment and reduces the total number of system
1332 fds used. */
1333 if (!share_info_db_init()) {
1334 DEBUG(0,("ERROR: failed to load share info db.\n"));
1335 exit(1);
1338 /* only start the background queue daemon if we are
1339 running as a daemon -- bad things will happen if
1340 smbd is launched via inetd and we fork a copy of
1341 ourselves here */
1343 if (is_daemon && !interactive
1344 && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1345 start_background_queue();
1348 if (!is_daemon) {
1349 /* inetd mode */
1350 TALLOC_FREE(frame);
1352 /* Started from inetd. fd 0 is the socket. */
1353 /* We will abort gracefully when the client or remote system
1354 goes away */
1355 smbd_set_server_fd(dup(0));
1357 /* close our standard file descriptors */
1358 close_low_fds(False); /* Don't close stderr */
1360 #ifdef HAVE_ATEXIT
1361 atexit(killkids);
1362 #endif
1364 /* Stop zombies */
1365 smbd_setup_sig_chld_handler();
1367 smbd_process();
1369 exit_server_cleanly(NULL);
1370 return(0);
1373 parent = talloc_zero(smbd_event_context(), struct smbd_parent_context);
1374 if (!parent) {
1375 exit_server("talloc(struct smbd_parent_context) failed");
1377 parent->interactive = interactive;
1379 if (!open_sockets_smbd(parent, ports))
1380 exit_server("open_sockets_smbd() failed");
1382 TALLOC_FREE(frame);
1383 /* make sure we always have a valid stackframe */
1384 frame = talloc_stackframe();
1386 smbd_parent_loop(parent);
1388 exit_server_cleanly(NULL);
1389 TALLOC_FREE(frame);
1390 return(0);