2 Unix SMB/CIFS implementation.
4 Main SMB server routines
6 Copyright (C) Andrew Tridgell 1992-2005
7 Copyright (C) Martin Pool 2002
8 Copyright (C) Jelmer Vernooij 2002
9 Copyright (C) James J Myers 2003 <myersjj@samba.org>
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "lib/events/events.h"
28 #include "lib/cmdline/popt_common.h"
29 #include "system/dir.h"
30 #include "system/filesys.h"
31 #include "auth/gensec/gensec.h"
32 #include "libcli/auth/schannel.h"
33 #include "smbd/process_model.h"
34 #include "param/secrets.h"
35 #include "lib/util/pidfile.h"
36 #include "param/param.h"
37 #include "dsdb/samdb/samdb.h"
38 #include "auth/session.h"
39 #include "lib/messaging/irpc.h"
40 #include "librpc/gen_ndr/ndr_irpc.h"
41 #include "cluster/cluster.h"
42 #include "dynconfig/dynconfig.h"
43 #include "lib/util/samba_modules.h"
44 #include "nsswitch/winbind_client.h"
45 #include "libds/common/roles.h"
46 #include "lib/util/tfork.h"
47 #include "dsdb/samdb/ldb_modules/util.h"
48 #include "lib/util/server_id.h"
55 struct tevent_context *event_ctx;
56 const char *binary_name;
60 recursively delete a directory tree
62 static void recursive_delete(const char *path)
72 for (de=readdir(dir);de;de=readdir(dir)) {
76 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name)) {
80 fname = talloc_asprintf(path, "%s/%s", path, de->d_name);
81 if (stat(fname, &st) != 0) {
84 if (S_ISDIR(st.st_mode)) {
85 recursive_delete(fname);
89 if (unlink(fname) != 0) {
90 DBG_ERR("Unabled to delete '%s' - %s\n",
91 fname, strerror(errno));
92 smb_panic("unable to cleanup tmp files");
100 cleanup temporary files. This is the new alternative to
101 TDB_CLEAR_IF_FIRST. Unfortunately TDB_CLEAR_IF_FIRST is not
102 efficient on unix systems due to the lack of scaling of the byte
103 range locking system. So instead of putting the burden on tdb to
104 cleanup tmp files, this function deletes them.
106 static void cleanup_tmp_files(struct loadparm_context *lp_ctx)
109 TALLOC_CTX *mem_ctx = talloc_new(NULL);
110 if (mem_ctx == NULL) {
111 exit_daemon("Failed to create memory context",
115 path = smbd_tmp_path(mem_ctx, lp_ctx, NULL);
117 exit_daemon("Failed to cleanup temporary files",
121 recursive_delete(path);
122 talloc_free(mem_ctx);
125 static void sig_hup(int sig)
127 debug_schedule_reopen_logs();
130 static void sig_term(int sig)
133 if (getpgrp() == getpid()) {
135 * We're the process group leader, send
136 * SIGTERM to our process group.
138 kill(-getpgrp(), SIGTERM);
144 static void sigterm_signal_handler(struct tevent_context *ev,
145 struct tevent_signal *se,
146 int signum, int count, void *siginfo,
149 struct server_state *state = talloc_get_type_abort(
150 private_data, struct server_state);
152 DBG_DEBUG("Process %s got SIGTERM\n", state->binary_name);
160 static void setup_signals(void)
162 /* we are never interested in SIGPIPE */
163 BlockSignals(true,SIGPIPE);
166 /* we are never interested in SIGFPE */
167 BlockSignals(true,SIGFPE);
170 /* We are no longer interested in USR1 */
171 BlockSignals(true, SIGUSR1);
174 /* We are no longer interested in USR2 */
175 BlockSignals(true,SIGUSR2);
178 /* POSIX demands that signals are inherited. If the invoking process has
179 * these signals masked, we will have problems,
180 * as we won't receive them. */
181 BlockSignals(false, SIGHUP);
182 BlockSignals(false, SIGTERM);
184 CatchSignal(SIGHUP, sig_hup);
185 CatchSignal(SIGTERM, sig_term);
191 static void server_stdin_handler(struct tevent_context *event_ctx,
192 struct tevent_fd *fde,
196 struct server_state *state = talloc_get_type_abort(
197 private_data, struct server_state);
199 if (read(0, &c, 1) == 0) {
200 DBG_ERR("%s: EOF on stdin - PID %d terminating\n",
201 state->binary_name, (int)getpid());
203 if (getpgrp() == getpid()) {
204 DBG_ERR("Sending SIGTERM from pid %d\n",
206 kill(-getpgrp(), SIGTERM);
215 die if the user selected maximum runtime is exceeded
217 _NORETURN_ static void max_runtime_handler(struct tevent_context *ev,
218 struct tevent_timer *te,
219 struct timeval t, void *private_data)
221 struct server_state *state = talloc_get_type_abort(
222 private_data, struct server_state);
223 DBG_ERR("%s: maximum runtime exceeded - "
224 "terminating PID %d at %llu, current ts: %llu\n",
227 (unsigned long long)t.tv_sec,
228 (unsigned long long)time(NULL));
234 * When doing an in-place upgrade of Samba, the database format may have
235 * changed between versions. E.g. between 4.7 and 4.8 the DB changed from
236 * DN-based indexes to GUID-based indexes, so we have to re-index the DB after
238 * This function handles migrating an older samba DB to a new Samba release.
239 * Note that we have to maintain DB compatibility between *all* older versions
240 * of Samba, not just the ones still under maintenance support.
242 static int handle_inplace_db_upgrade(struct ldb_context *ldb_ctx)
247 * The DSDB stack will handle reindexing the DB (if needed) upon the first
248 * DB write. Open and close a transaction on the DB now to trigger a
249 * reindex if required, rather than waiting for the first write.
250 * We do this here to guarantee that the DB will have been re-indexed by
251 * the time the main samba code runs.
252 * Refer to dsdb_schema_set_indices_and_attributes() for the actual reindexing
254 * source4/dsdb/samdb/ldb_modules/schema_load.c:schema_load_start_transaction()
256 ret = ldb_transaction_start(ldb_ctx);
257 if (ret != LDB_SUCCESS) {
261 ret = ldb_transaction_commit(ldb_ctx);
262 if (ret != LDB_SUCCESS) {
269 pre-open the key databases. This saves a lot of time in child
272 static int prime_ldb_databases(struct tevent_context *event_ctx, bool *am_backup)
274 struct ldb_result *res = NULL;
275 struct ldb_dn *samba_dsdb_dn = NULL;
276 struct ldb_context *ldb_ctx = NULL;
277 struct ldb_context *pdb = NULL;
278 static const char *attrs[] = { "backupDate", NULL };
279 const char *msg = NULL;
281 TALLOC_CTX *db_context = talloc_new(event_ctx);
282 if (db_context == NULL) {
283 return LDB_ERR_OPERATIONS_ERROR;
288 /* note we deliberately leave these open, which allows them to be
289 * re-used in ldb_wrap_connect() */
290 ldb_ctx = samdb_connect(db_context,
293 system_session(cmdline_lp_ctx),
296 if (ldb_ctx == NULL) {
297 talloc_free(db_context);
298 return LDB_ERR_OPERATIONS_ERROR;
301 ret = handle_inplace_db_upgrade(ldb_ctx);
302 if (ret != LDB_SUCCESS) {
303 talloc_free(db_context);
307 pdb = privilege_connect(db_context, cmdline_lp_ctx);
309 talloc_free(db_context);
310 return LDB_ERR_OPERATIONS_ERROR;
313 /* check the root DB object to see if it's marked as a backup */
314 samba_dsdb_dn = ldb_dn_new(db_context, ldb_ctx, "@SAMBA_DSDB");
315 if (!samba_dsdb_dn) {
316 talloc_free(db_context);
317 return LDB_ERR_OPERATIONS_ERROR;
320 ret = dsdb_search_dn(ldb_ctx, db_context, &res, samba_dsdb_dn, attrs,
321 DSDB_FLAG_AS_SYSTEM);
322 if (ret != LDB_SUCCESS) {
323 talloc_free(db_context);
327 if (res->count > 0) {
328 msg = ldb_msg_find_attr_as_string(res->msgs[0], "backupDate",
338 called from 'smbcontrol samba shutdown'
340 static void samba_parent_shutdown(struct imessaging_context *msg,
343 struct server_id src,
346 struct server_state *state =
347 talloc_get_type_abort(private_data,
348 struct server_state);
349 struct server_id_buf src_buf;
350 struct server_id dst = imessaging_get_server_id(msg);
351 struct server_id_buf dst_buf;
353 DBG_ERR("samba_shutdown of %s %s: from %s\n",
355 server_id_str_buf(dst, &dst_buf),
356 server_id_str_buf(src, &src_buf));
363 called when a fatal condition occurs in a child task
365 static NTSTATUS samba_terminate(struct irpc_message *msg,
366 struct samba_terminate *r)
368 struct server_state *state = talloc_get_type(msg->private_data,
369 struct server_state);
370 DBG_ERR("samba_terminate of %s %d: %s\n",
371 state->binary_name, (int)getpid(), r->in.reason);
377 setup messaging for the top level samba (parent) task
379 static NTSTATUS setup_parent_messaging(struct server_state *state,
380 struct loadparm_context *lp_ctx)
382 struct imessaging_context *msg;
385 msg = imessaging_init(state->event_ctx,
387 cluster_id(getpid(), SAMBA_PARENT_TASKID),
389 NT_STATUS_HAVE_NO_MEMORY(msg);
391 status = irpc_add_name(msg, "samba");
392 if (!NT_STATUS_IS_OK(status)) {
396 status = imessaging_register(msg, state, MSG_SHUTDOWN,
397 samba_parent_shutdown);
398 if (!NT_STATUS_IS_OK(status)) {
402 status = IRPC_REGISTER(msg, irpc, SAMBA_TERMINATE,
403 samba_terminate, state);
404 if (!NT_STATUS_IS_OK(status)) {
415 static void show_build(void)
417 #define CONFIG_OPTION(n) { #n, dyn_ ## n }
421 } config_options[] = {
422 CONFIG_OPTION(BINDIR),
423 CONFIG_OPTION(SBINDIR),
424 CONFIG_OPTION(CONFIGFILE),
425 CONFIG_OPTION(NCALRPCDIR),
426 CONFIG_OPTION(LOGFILEBASE),
427 CONFIG_OPTION(LMHOSTSFILE),
428 CONFIG_OPTION(DATADIR),
429 CONFIG_OPTION(MODULESDIR),
430 CONFIG_OPTION(LOCKDIR),
431 CONFIG_OPTION(STATEDIR),
432 CONFIG_OPTION(CACHEDIR),
433 CONFIG_OPTION(PIDDIR),
434 CONFIG_OPTION(PRIVATE_DIR),
435 CONFIG_OPTION(CODEPAGEDIR),
436 CONFIG_OPTION(SETUPDIR),
437 CONFIG_OPTION(WINBINDD_SOCKET_DIR),
438 CONFIG_OPTION(NTP_SIGND_SOCKET_DIR),
443 printf("Samba version: %s\n", SAMBA_VERSION_STRING);
444 printf("Build environment:\n");
447 for (i=0; config_options[i].name; i++) {
449 config_options[i].name,
450 config_options[i].value);
456 static int event_ctx_destructor(struct tevent_context *event_ctx)
458 imessaging_dgm_unref_ev(event_ctx);
463 static int to_children_fd = -1;
464 static void atfork_prepare(void) {
466 static void atfork_parent(void) {
468 static void atfork_child(void) {
469 if (to_children_fd != -1) {
470 close(to_children_fd);
479 static int binary_smbd_main(const char *binary_name,
483 bool opt_daemon = false;
484 bool opt_fork = true;
485 bool opt_interactive = false;
486 bool opt_no_process_group = false;
487 bool db_is_backup = false;
491 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
492 STATIC_service_MODULES_PROTO;
493 init_module_fn static_init[] = { STATIC_service_MODULES };
494 init_module_fn *shared_init;
495 uint16_t stdin_event_flags;
497 const char *model = "prefork";
506 OPT_NO_PROCESS_GROUP,
508 struct poptOption long_options[] = {
511 .longName = "daemon",
513 .argInfo = POPT_ARG_NONE,
515 .descrip = "Become a daemon (default)",
518 .longName = "foreground",
520 .argInfo = POPT_ARG_NONE,
521 .val = OPT_FOREGROUND,
522 .descrip = "Run the daemon in foreground",
525 .longName = "interactive",
527 .argInfo = POPT_ARG_NONE,
528 .val = OPT_INTERACTIVE,
529 .descrip = "Run interactive (not a daemon)",
534 .argInfo = POPT_ARG_STRING,
535 .val = OPT_PROCESS_MODEL,
536 .descrip = "Select process model",
537 .argDescrip = "MODEL",
540 .longName = "maximum-runtime",
541 .argInfo = POPT_ARG_INT,
543 .descrip = "set maximum runtime of the server process, "
544 "till autotermination",
545 .argDescrip = "seconds"
548 .longName = "show-build",
550 .argInfo = POPT_ARG_NONE,
551 .val = OPT_SHOW_BUILD,
552 .descrip = "show build info",
555 .longName = "no-process-group",
556 .argInfo = POPT_ARG_NONE,
557 .val = OPT_NO_PROCESS_GROUP,
558 .descrip = "Don't create a new process group",
564 struct server_state *state = NULL;
565 struct tevent_signal *se = NULL;
567 setproctitle("root process");
569 pc = poptGetContext(binary_name, argc, argv, long_options, 0);
570 while((opt = poptGetNextOpt(pc)) != -1) {
578 case OPT_INTERACTIVE:
579 opt_interactive = true;
581 case OPT_PROCESS_MODEL:
582 model = poptGetOptArg(pc);
587 case OPT_NO_PROCESS_GROUP:
588 opt_no_process_group = true;
591 fprintf(stderr, "\nInvalid option %s: %s\n\n",
592 poptBadOption(pc, 0), poptStrerror(opt));
593 poptPrintUsage(pc, stderr, 0);
598 if (opt_daemon && opt_interactive) {
599 fprintf(stderr,"\nERROR: "
600 "Option -i|--interactive is "
601 "not allowed together with -D|--daemon\n\n");
602 poptPrintUsage(pc, stderr, 0);
604 } else if (!opt_interactive && opt_fork) {
605 /* default is --daemon */
611 talloc_enable_null_tracking();
613 setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
616 /* we want total control over the permissions on created files,
617 so set our umask to 0 */
620 DEBUG(0,("%s version %s started.\n",
622 SAMBA_VERSION_STRING));
623 DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team"
626 if (sizeof(uint16_t) < 2 ||
627 sizeof(uint32_t) < 4 ||
628 sizeof(uint64_t) < 8) {
629 DEBUG(0,("ERROR: Samba is not configured correctly "
630 "for the word size on your machine\n"));
631 DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, "
632 "sizeof(uint64_t) = %u\n",
633 (unsigned int)sizeof(uint16_t),
634 (unsigned int)sizeof(uint32_t),
635 (unsigned int)sizeof(uint64_t)));
640 DBG_NOTICE("Becoming a daemon.\n");
641 become_daemon(opt_fork, opt_no_process_group, false);
644 /* Create the memory context to hang everything off. */
645 state = talloc_zero(NULL, struct server_state);
647 exit_daemon("Samba cannot create server state", ENOMEM);
649 state->binary_name = binary_name;
651 cleanup_tmp_files(cmdline_lp_ctx);
653 if (!directory_exist(lpcfg_lock_directory(cmdline_lp_ctx))) {
654 mkdir(lpcfg_lock_directory(cmdline_lp_ctx), 0755);
657 if (!directory_exist(lpcfg_pid_directory(cmdline_lp_ctx))) {
658 mkdir(lpcfg_pid_directory(cmdline_lp_ctx), 0755);
661 pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);
663 if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
664 if (!open_schannel_session_store(state,
667 exit_daemon("Samba cannot open schannel store "
668 "for secured NETLOGON operations.", EACCES);
672 /* make sure we won't go through nss_winbind */
673 if (!winbind_off()) {
675 exit_daemon("Samba failed to disable recusive "
676 "winbindd calls.", EACCES);
679 gensec_init(); /* FIXME: */
681 process_model_init(cmdline_lp_ctx);
683 shared_init = load_samba_modules(NULL, "service");
685 run_init_functions(NULL, static_init);
686 run_init_functions(NULL, shared_init);
688 talloc_free(shared_init);
690 /* the event context is the top level structure in smbd. Everything else
691 should hang off that */
692 state->event_ctx = s4_event_context_init(state);
694 if (state->event_ctx == NULL) {
696 exit_daemon("Initializing event context failed", EACCES);
699 talloc_set_destructor(state->event_ctx, event_ctx_destructor);
701 if (opt_interactive) {
702 /* terminate when stdin goes away */
703 stdin_event_flags = TEVENT_FD_READ;
705 /* stay alive forever */
706 stdin_event_flags = 0;
711 * If we're interactive we want to set our own process group for
712 * signal management, unless --no-process-group specified.
714 if (opt_interactive && !opt_no_process_group)
715 setpgid((pid_t)0, (pid_t)0);
718 /* catch EOF on stdin */
720 signal(SIGTTIN, SIG_IGN);
723 if (fstat(0, &st) != 0) {
725 exit_daemon("Samba failed to set standard input handler",
729 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
730 struct tevent_fd *fde = tevent_add_fd(state->event_ctx,
734 server_stdin_handler,
738 exit_daemon("Initializing stdin failed", ENOMEM);
743 struct tevent_timer *te;
744 DBG_ERR("%s PID %d was called with maxruntime %d - "
746 binary_name, (int)getpid(),
747 max_runtime, (unsigned long long) time(NULL));
748 te = tevent_add_timer(state->event_ctx, state->event_ctx,
749 timeval_current_ofs(max_runtime, 0),
754 exit_daemon("Maxruntime handler failed", ENOMEM);
758 se = tevent_add_signal(state->event_ctx,
762 sigterm_signal_handler,
766 exit_daemon("Initialize SIGTERM handler failed", ENOMEM);
769 if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
770 && !lpcfg_parm_bool(cmdline_lp_ctx, NULL,
771 "server role check", "inhibit", false)
772 && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb")
773 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
775 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
777 DEBUG(0, ("At this time the 'samba' binary should only be used "
779 DEBUGADD(0, ("'server role = active directory domain "
780 "controller' or to access the ntvfs file server "
781 "with 'server services = +smb' or the rpc proxy "
782 "with 'dcerpc endpoint servers = remote'\n"));
783 DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for "
784 "domain member and standalone file server tasks\n"));
785 exit_daemon("Samba detected misconfigured 'server role' "
786 "and exited. Check logs for details", EINVAL);
789 ret = prime_ldb_databases(state->event_ctx, &db_is_backup);
790 if (ret != LDB_SUCCESS) {
792 exit_daemon("Samba failed to prime database", EINVAL);
797 exit_daemon("Database is a backup. Please run samba-tool domain"
798 " backup restore", EINVAL);
801 status = setup_parent_messaging(state, cmdline_lp_ctx);
802 if (!NT_STATUS_IS_OK(status)) {
804 exit_daemon("Samba failed to setup parent messaging",
805 NT_STATUS_V(status));
808 DBG_ERR("%s: using '%s' process model\n", binary_name, model);
813 bool start_services = false;
815 rc = pipe(child_pipe);
818 exit_daemon("Samba failed to open process control pipe",
821 smb_set_close_on_exec(child_pipe[0]);
822 smb_set_close_on_exec(child_pipe[1]);
825 to_children_fd = child_pipe[1];
826 pthread_atfork(atfork_prepare, atfork_parent,
828 start_services = true;
831 struct tfork *t = NULL;
835 "Samba unable to fork master process",
838 pid = tfork_child_pid(t);
840 start_services = false;
842 /* In the child process */
843 start_services = true;
844 close(child_pipe[1]);
847 if (start_services) {
848 status = server_service_startup(
849 state->event_ctx, cmdline_lp_ctx, model,
850 lpcfg_server_services(cmdline_lp_ctx),
852 if (!NT_STATUS_IS_OK(status)) {
854 exit_daemon("Samba failed to start services",
855 NT_STATUS_V(status));
861 daemon_ready("samba");
864 /* wait for events - this is where smbd sits for most of its
866 tevent_loop_wait(state->event_ctx);
868 /* as everything hangs off this state->event context, freeing state
869 will initiate a clean shutdown of all services */
875 int main(int argc, const char *argv[])
877 setproctitle_init(argc, discard_const(argv), environ);
879 return binary_smbd_main("samba", argc, argv);