s4:dsdb:tests: Add return code check
[Samba.git] / source4 / smbd / server.c
blobed81c01afc19149480d75a70cf3fdfe7e399d602
1 /*
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/>.
25 #include "includes.h"
26 #include "lib/events/events.h"
27 #include "version.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"
48 #ifdef HAVE_PTHREAD
49 #include <pthread.h>
50 #endif
52 struct server_state {
53 struct tevent_context *event_ctx;
54 const char *binary_name;
58 recursively delete a directory tree
60 static void recursive_delete(const char *path)
62 DIR *dir;
63 struct dirent *de;
65 dir = opendir(path);
66 if (!dir) {
67 return;
70 for (de=readdir(dir);de;de=readdir(dir)) {
71 char *fname;
72 struct stat st;
74 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name)) {
75 continue;
78 fname = talloc_asprintf(path, "%s/%s", path, de->d_name);
79 if (stat(fname, &st) != 0) {
80 continue;
82 if (S_ISDIR(st.st_mode)) {
83 recursive_delete(fname);
84 talloc_free(fname);
85 continue;
87 if (unlink(fname) != 0) {
88 DBG_ERR("Unabled to delete '%s' - %s\n",
89 fname, strerror(errno));
90 smb_panic("unable to cleanup tmp files");
92 talloc_free(fname);
94 closedir(dir);
98 cleanup temporary files. This is the new alternative to
99 TDB_CLEAR_IF_FIRST. Unfortunately TDB_CLEAR_IF_FIRST is not
100 efficient on unix systems due to the lack of scaling of the byte
101 range locking system. So instead of putting the burden on tdb to
102 cleanup tmp files, this function deletes them.
104 static void cleanup_tmp_files(struct loadparm_context *lp_ctx)
106 char *path;
107 TALLOC_CTX *mem_ctx = talloc_new(NULL);
108 if (mem_ctx == NULL) {
109 exit_daemon("Failed to create memory context",
110 ENOMEM);
113 path = smbd_tmp_path(mem_ctx, lp_ctx, NULL);
114 if (path == NULL) {
115 exit_daemon("Failed to cleanup temporary files",
116 EINVAL);
119 recursive_delete(path);
120 talloc_free(mem_ctx);
123 static void sig_hup(int sig)
125 debug_schedule_reopen_logs();
128 static void sig_term(int sig)
130 #if HAVE_GETPGRP
131 if (getpgrp() == getpid()) {
133 * We're the process group leader, send
134 * SIGTERM to our process group.
136 kill(-getpgrp(), SIGTERM);
138 #endif
139 _exit(127);
142 static void sigterm_signal_handler(struct tevent_context *ev,
143 struct tevent_signal *se,
144 int signum, int count, void *siginfo,
145 void *private_data)
147 struct server_state *state = talloc_get_type_abort(
148 private_data, struct server_state);
150 DBG_DEBUG("Process %s got SIGTERM\n", state->binary_name);
151 TALLOC_FREE(state);
152 sig_term(SIGTERM);
156 setup signal masks
158 static void setup_signals(void)
160 /* we are never interested in SIGPIPE */
161 BlockSignals(true,SIGPIPE);
163 #if defined(SIGFPE)
164 /* we are never interested in SIGFPE */
165 BlockSignals(true,SIGFPE);
166 #endif
168 /* We are no longer interested in USR1 */
169 BlockSignals(true, SIGUSR1);
171 #if defined(SIGUSR2)
172 /* We are no longer interested in USR2 */
173 BlockSignals(true,SIGUSR2);
174 #endif
176 /* POSIX demands that signals are inherited. If the invoking process has
177 * these signals masked, we will have problems,
178 * as we won't receive them. */
179 BlockSignals(false, SIGHUP);
180 BlockSignals(false, SIGTERM);
182 CatchSignal(SIGHUP, sig_hup);
183 CatchSignal(SIGTERM, sig_term);
187 handle io on stdin
189 static void server_stdin_handler(struct tevent_context *event_ctx,
190 struct tevent_fd *fde,
191 uint16_t flags,
192 void *private_data)
194 struct server_state *state = talloc_get_type_abort(
195 private_data, struct server_state);
196 uint8_t c;
197 if (read(0, &c, 1) == 0) {
198 DBG_ERR("%s: EOF on stdin - PID %d terminating\n",
199 state->binary_name, (int)getpid());
200 #if HAVE_GETPGRP
201 if (getpgrp() == getpid()) {
202 DBG_ERR("Sending SIGTERM from pid %d\n",
203 (int)getpid());
204 kill(-getpgrp(), SIGTERM);
206 #endif
207 TALLOC_FREE(state);
208 exit(0);
213 die if the user selected maximum runtime is exceeded
215 _NORETURN_ static void max_runtime_handler(struct tevent_context *ev,
216 struct tevent_timer *te,
217 struct timeval t, void *private_data)
219 struct server_state *state = talloc_get_type_abort(
220 private_data, struct server_state);
221 DBG_ERR("%s: maximum runtime exceeded - "
222 "terminating PID %d at %llu, current ts: %llu\n",
223 state->binary_name,
224 (int)getpid(),
225 (unsigned long long)t.tv_sec,
226 (unsigned long long)time(NULL));
227 TALLOC_FREE(state);
228 exit(0);
232 pre-open the key databases. This saves a lot of time in child
233 processes
235 static void prime_ldb_databases(struct tevent_context *event_ctx)
237 TALLOC_CTX *db_context;
238 db_context = talloc_new(event_ctx);
240 samdb_connect(db_context,
241 event_ctx,
242 cmdline_lp_ctx,
243 system_session(cmdline_lp_ctx),
244 NULL,
246 privilege_connect(db_context, cmdline_lp_ctx);
248 /* we deliberately leave these open, which allows them to be
249 * re-used in ldb_wrap_connect() */
254 called when a fatal condition occurs in a child task
256 static NTSTATUS samba_terminate(struct irpc_message *msg,
257 struct samba_terminate *r)
259 struct server_state *state = talloc_get_type(msg->private_data,
260 struct server_state);
261 DBG_ERR("samba_terminate of %s %d: %s\n",
262 state->binary_name, (int)getpid(), r->in.reason);
263 TALLOC_FREE(state);
264 exit(1);
268 setup messaging for the top level samba (parent) task
270 static NTSTATUS setup_parent_messaging(struct server_state *state,
271 struct loadparm_context *lp_ctx)
273 struct imessaging_context *msg;
274 NTSTATUS status;
276 msg = imessaging_init(state->event_ctx,
277 lp_ctx,
278 cluster_id(0, SAMBA_PARENT_TASKID),
279 state->event_ctx);
280 NT_STATUS_HAVE_NO_MEMORY(msg);
282 status = irpc_add_name(msg, "samba");
283 if (!NT_STATUS_IS_OK(status)) {
284 return status;
287 status = IRPC_REGISTER(msg, irpc, SAMBA_TERMINATE,
288 samba_terminate, state);
290 return status;
295 show build info
297 static void show_build(void)
299 #define CONFIG_OPTION(n) { #n, dyn_ ## n }
300 struct {
301 const char *name;
302 const char *value;
303 } config_options[] = {
304 CONFIG_OPTION(BINDIR),
305 CONFIG_OPTION(SBINDIR),
306 CONFIG_OPTION(CONFIGFILE),
307 CONFIG_OPTION(NCALRPCDIR),
308 CONFIG_OPTION(LOGFILEBASE),
309 CONFIG_OPTION(LMHOSTSFILE),
310 CONFIG_OPTION(DATADIR),
311 CONFIG_OPTION(MODULESDIR),
312 CONFIG_OPTION(LOCKDIR),
313 CONFIG_OPTION(STATEDIR),
314 CONFIG_OPTION(CACHEDIR),
315 CONFIG_OPTION(PIDDIR),
316 CONFIG_OPTION(PRIVATE_DIR),
317 CONFIG_OPTION(CODEPAGEDIR),
318 CONFIG_OPTION(SETUPDIR),
319 CONFIG_OPTION(WINBINDD_SOCKET_DIR),
320 CONFIG_OPTION(NTP_SIGND_SOCKET_DIR),
321 { NULL, NULL}
323 int i;
325 printf("Samba version: %s\n", SAMBA_VERSION_STRING);
326 printf("Build environment:\n");
328 printf("Paths:\n");
329 for (i=0; config_options[i].name; i++) {
330 printf(" %s: %s\n",
331 config_options[i].name,
332 config_options[i].value);
335 exit(0);
338 static int event_ctx_destructor(struct tevent_context *event_ctx)
340 imessaging_dgm_unref_ev(event_ctx);
341 return 0;
344 #ifdef HAVE_PTHREAD
345 static int to_children_fd = -1;
346 static void atfork_prepare(void) {
348 static void atfork_parent(void) {
350 static void atfork_child(void) {
351 if (to_children_fd != -1) {
352 close(to_children_fd);
353 to_children_fd = -1;
356 #endif
359 main server.
361 static int binary_smbd_main(const char *binary_name,
362 int argc,
363 const char *argv[])
365 bool opt_daemon = false;
366 bool opt_fork = true;
367 bool opt_interactive = false;
368 bool opt_no_process_group = false;
369 int opt;
370 poptContext pc;
371 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
372 STATIC_service_MODULES_PROTO;
373 init_module_fn static_init[] = { STATIC_service_MODULES };
374 init_module_fn *shared_init;
375 uint16_t stdin_event_flags;
376 NTSTATUS status;
377 const char *model = "standard";
378 int max_runtime = 0;
379 struct stat st;
380 enum {
381 OPT_DAEMON = 1000,
382 OPT_FOREGROUND,
383 OPT_INTERACTIVE,
384 OPT_PROCESS_MODEL,
385 OPT_SHOW_BUILD,
386 OPT_NO_PROCESS_GROUP,
388 struct poptOption long_options[] = {
389 POPT_AUTOHELP
390 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON,
391 "Become a daemon (default)", NULL },
392 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FOREGROUND,
393 "Run the daemon in foreground", NULL },
394 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE,
395 "Run interactive (not a daemon)", NULL},
396 {"model", 'M', POPT_ARG_STRING, NULL, OPT_PROCESS_MODEL,
397 "Select process model", "MODEL"},
398 {"maximum-runtime",0, POPT_ARG_INT, &max_runtime, 0,
399 "set maximum runtime of the server process, "
400 "till autotermination", "seconds"},
401 {"show-build", 'b', POPT_ARG_NONE, NULL, OPT_SHOW_BUILD,
402 "show build info", NULL },
403 {"no-process-group", '\0', POPT_ARG_NONE, NULL,
404 OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
405 POPT_COMMON_SAMBA
406 POPT_COMMON_VERSION
407 { NULL }
409 struct server_state *state = NULL;
410 struct tevent_signal *se = NULL;
412 setproctitle("root process");
414 pc = poptGetContext(binary_name, argc, argv, long_options, 0);
415 while((opt = poptGetNextOpt(pc)) != -1) {
416 switch(opt) {
417 case OPT_DAEMON:
418 opt_daemon = true;
419 break;
420 case OPT_FOREGROUND:
421 opt_fork = false;
422 break;
423 case OPT_INTERACTIVE:
424 opt_interactive = true;
425 break;
426 case OPT_PROCESS_MODEL:
427 model = poptGetOptArg(pc);
428 break;
429 case OPT_SHOW_BUILD:
430 show_build();
431 break;
432 case OPT_NO_PROCESS_GROUP:
433 opt_no_process_group = true;
434 break;
435 default:
436 fprintf(stderr, "\nInvalid option %s: %s\n\n",
437 poptBadOption(pc, 0), poptStrerror(opt));
438 poptPrintUsage(pc, stderr, 0);
439 return 1;
443 if (opt_daemon && opt_interactive) {
444 fprintf(stderr,"\nERROR: "
445 "Option -i|--interactive is "
446 "not allowed together with -D|--daemon\n\n");
447 poptPrintUsage(pc, stderr, 0);
448 return 1;
449 } else if (!opt_interactive && opt_fork) {
450 /* default is --daemon */
451 opt_daemon = true;
454 poptFreeContext(pc);
456 talloc_enable_null_tracking();
458 setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
459 setup_signals();
461 /* we want total control over the permissions on created files,
462 so set our umask to 0 */
463 umask(0);
465 DEBUG(0,("%s version %s started.\n",
466 binary_name,
467 SAMBA_VERSION_STRING));
468 DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team"
469 " 1992-2018\n"));
471 if (sizeof(uint16_t) < 2 ||
472 sizeof(uint32_t) < 4 ||
473 sizeof(uint64_t) < 8) {
474 DEBUG(0,("ERROR: Samba is not configured correctly "
475 "for the word size on your machine\n"));
476 DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, "
477 "sizeof(uint64_t) = %u\n",
478 (unsigned int)sizeof(uint16_t),
479 (unsigned int)sizeof(uint32_t),
480 (unsigned int)sizeof(uint64_t)));
481 return 1;
484 if (opt_daemon) {
485 DBG_NOTICE("Becoming a daemon.\n");
486 become_daemon(opt_fork, opt_no_process_group, false);
489 /* Create the memory context to hang everything off. */
490 state = talloc_zero(NULL, struct server_state);
491 if (state == NULL) {
492 exit_daemon("Samba cannot create server state", ENOMEM);
494 state->binary_name = binary_name;
496 cleanup_tmp_files(cmdline_lp_ctx);
498 if (!directory_exist(lpcfg_lock_directory(cmdline_lp_ctx))) {
499 mkdir(lpcfg_lock_directory(cmdline_lp_ctx), 0755);
502 if (!directory_exist(lpcfg_pid_directory(cmdline_lp_ctx))) {
503 mkdir(lpcfg_pid_directory(cmdline_lp_ctx), 0755);
506 pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);
508 if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
509 if (!open_schannel_session_store(state,
510 cmdline_lp_ctx)) {
511 TALLOC_FREE(state);
512 exit_daemon("Samba cannot open schannel store "
513 "for secured NETLOGON operations.", EACCES);
517 /* make sure we won't go through nss_winbind */
518 if (!winbind_off()) {
519 TALLOC_FREE(state);
520 exit_daemon("Samba failed to disable recusive "
521 "winbindd calls.", EACCES);
524 gensec_init(); /* FIXME: */
526 process_model_init(cmdline_lp_ctx);
528 shared_init = load_samba_modules(NULL, "service");
530 run_init_functions(NULL, static_init);
531 run_init_functions(NULL, shared_init);
533 talloc_free(shared_init);
535 /* the event context is the top level structure in smbd. Everything else
536 should hang off that */
537 state->event_ctx = s4_event_context_init(state);
539 if (state->event_ctx == NULL) {
540 TALLOC_FREE(state);
541 exit_daemon("Initializing event context failed", EACCES);
544 talloc_set_destructor(state->event_ctx, event_ctx_destructor);
546 if (opt_interactive) {
547 /* terminate when stdin goes away */
548 stdin_event_flags = TEVENT_FD_READ;
549 } else {
550 /* stay alive forever */
551 stdin_event_flags = 0;
554 #if HAVE_SETPGID
556 * If we're interactive we want to set our own process group for
557 * signal management, unless --no-process-group specified.
559 if (opt_interactive && !opt_no_process_group)
560 setpgid((pid_t)0, (pid_t)0);
561 #endif
563 /* catch EOF on stdin */
564 #ifdef SIGTTIN
565 signal(SIGTTIN, SIG_IGN);
566 #endif
568 if (fstat(0, &st) != 0) {
569 TALLOC_FREE(state);
570 exit_daemon("Samba failed to set standard input handler",
571 ENOTTY);
574 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
575 struct tevent_fd *fde = tevent_add_fd(state->event_ctx,
576 state->event_ctx,
578 stdin_event_flags,
579 server_stdin_handler,
580 state);
581 if (fde == NULL) {
582 TALLOC_FREE(state);
583 exit_daemon("Initializing stdin failed", ENOMEM);
587 if (max_runtime) {
588 struct tevent_timer *te;
589 DBG_ERR("%s PID %d was called with maxruntime %d - "
590 "current ts %llu\n",
591 binary_name, (int)getpid(),
592 max_runtime, (unsigned long long) time(NULL));
593 te = tevent_add_timer(state->event_ctx, state->event_ctx,
594 timeval_current_ofs(max_runtime, 0),
595 max_runtime_handler,
596 state);
597 if (te == NULL) {
598 TALLOC_FREE(state);
599 exit_daemon("Maxruntime handler failed", ENOMEM);
603 se = tevent_add_signal(state->event_ctx,
604 state->event_ctx,
605 SIGTERM,
607 sigterm_signal_handler,
608 state);
609 if (se == NULL) {
610 TALLOC_FREE(state);
611 exit_daemon("Initialize SIGTERM handler failed", ENOMEM);
614 if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
615 && !lpcfg_parm_bool(cmdline_lp_ctx, NULL,
616 "server role check", "inhibit", false)
617 && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb")
618 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
619 "remote")
620 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
621 "mapiproxy")) {
622 DEBUG(0, ("At this time the 'samba' binary should only be used "
623 "for either:\n"));
624 DEBUGADD(0, ("'server role = active directory domain "
625 "controller' or to access the ntvfs file server "
626 "with 'server services = +smb' or the rpc proxy "
627 "with 'dcerpc endpoint servers = remote'\n"));
628 DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for "
629 "domain member and standalone file server tasks\n"));
630 exit_daemon("Samba detected misconfigured 'server role' "
631 "and exited. Check logs for details", EINVAL);
634 prime_ldb_databases(state->event_ctx);
636 status = setup_parent_messaging(state, cmdline_lp_ctx);
637 if (!NT_STATUS_IS_OK(status)) {
638 TALLOC_FREE(state);
639 exit_daemon("Samba failed to setup parent messaging",
640 NT_STATUS_V(status));
643 DBG_ERR("%s: using '%s' process model\n", binary_name, model);
646 int child_pipe[2];
647 int rc;
648 bool start_services = false;
650 rc = pipe(child_pipe);
651 if (rc < 0) {
652 TALLOC_FREE(state);
653 exit_daemon("Samba failed to open process control pipe",
654 errno);
656 smb_set_close_on_exec(child_pipe[0]);
657 smb_set_close_on_exec(child_pipe[1]);
659 #ifdef HAVE_PTHREAD
660 to_children_fd = child_pipe[1];
661 pthread_atfork(atfork_prepare, atfork_parent,
662 atfork_child);
663 start_services = true;
664 #else
665 pid_t pid;
666 struct tfork *t = NULL;
667 t = tfork_create();
668 if (t == NULL) {
669 exit_daemon(
670 "Samba unable to fork master process",
673 pid = tfork_child_pid(t);
674 if (pid == 0) {
675 start_services = false;
676 } else {
677 /* In the child process */
678 start_services = true;
679 close(child_pipe[1]);
681 #endif
682 if (start_services) {
683 status = server_service_startup(
684 state->event_ctx, cmdline_lp_ctx, model,
685 lpcfg_server_services(cmdline_lp_ctx),
686 child_pipe[0]);
687 if (!NT_STATUS_IS_OK(status)) {
688 TALLOC_FREE(state);
689 exit_daemon("Samba failed to start services",
690 NT_STATUS_V(status));
695 if (opt_daemon) {
696 daemon_ready("samba");
699 /* wait for events - this is where smbd sits for most of its
700 life */
701 tevent_loop_wait(state->event_ctx);
703 /* as everything hangs off this state->event context, freeing state
704 will initiate a clean shutdown of all services */
705 TALLOC_FREE(state);
707 return 0;
710 int main(int argc, const char *argv[])
712 setproctitle_init(argc, discard_const(argv), environ);
714 return binary_smbd_main("samba", argc, argv);