winbindd: convert id to a pointer in wb_xids2sids_dom_done()
[Samba.git] / source4 / smbd / server.c
blob05d62c9a03ca7f00fbb9ebf8a80499014645b104
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"
47 #include "dsdb/samdb/ldb_modules/util.h"
48 #include "lib/util/server_id.h"
50 #ifdef HAVE_PTHREAD
51 #include <pthread.h>
52 #endif
54 struct server_state {
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)
64 DIR *dir;
65 struct dirent *de;
67 dir = opendir(path);
68 if (!dir) {
69 return;
72 for (de=readdir(dir);de;de=readdir(dir)) {
73 char *fname;
74 struct stat st;
76 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name)) {
77 continue;
80 fname = talloc_asprintf(path, "%s/%s", path, de->d_name);
81 if (stat(fname, &st) != 0) {
82 continue;
84 if (S_ISDIR(st.st_mode)) {
85 recursive_delete(fname);
86 talloc_free(fname);
87 continue;
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");
94 talloc_free(fname);
96 closedir(dir);
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)
108 char *path;
109 TALLOC_CTX *mem_ctx = talloc_new(NULL);
110 if (mem_ctx == NULL) {
111 exit_daemon("Failed to create memory context",
112 ENOMEM);
115 path = smbd_tmp_path(mem_ctx, lp_ctx, NULL);
116 if (path == NULL) {
117 exit_daemon("Failed to cleanup temporary files",
118 EINVAL);
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)
132 #if HAVE_GETPGRP
133 if (getpgrp() == getpid()) {
135 * We're the process group leader, send
136 * SIGTERM to our process group.
138 kill(-getpgrp(), SIGTERM);
140 #endif
141 _exit(127);
144 static void sigterm_signal_handler(struct tevent_context *ev,
145 struct tevent_signal *se,
146 int signum, int count, void *siginfo,
147 void *private_data)
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);
153 TALLOC_FREE(state);
154 sig_term(SIGTERM);
158 setup signal masks
160 static void setup_signals(void)
162 /* we are never interested in SIGPIPE */
163 BlockSignals(true,SIGPIPE);
165 #if defined(SIGFPE)
166 /* we are never interested in SIGFPE */
167 BlockSignals(true,SIGFPE);
168 #endif
170 /* We are no longer interested in USR1 */
171 BlockSignals(true, SIGUSR1);
173 #if defined(SIGUSR2)
174 /* We are no longer interested in USR2 */
175 BlockSignals(true,SIGUSR2);
176 #endif
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);
189 handle io on stdin
191 static void server_stdin_handler(struct tevent_context *event_ctx,
192 struct tevent_fd *fde,
193 uint16_t flags,
194 void *private_data)
196 struct server_state *state = talloc_get_type_abort(
197 private_data, struct server_state);
198 uint8_t c;
199 if (read(0, &c, 1) == 0) {
200 DBG_ERR("%s: EOF on stdin - PID %d terminating\n",
201 state->binary_name, (int)getpid());
202 #if HAVE_GETPGRP
203 if (getpgrp() == getpid()) {
204 DBG_ERR("Sending SIGTERM from pid %d\n",
205 (int)getpid());
206 kill(-getpgrp(), SIGTERM);
208 #endif
209 TALLOC_FREE(state);
210 exit(0);
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",
225 state->binary_name,
226 (int)getpid(),
227 (unsigned long long)t.tv_sec,
228 (unsigned long long)time(NULL));
229 TALLOC_FREE(state);
230 exit(0);
234 pre-open the key databases. This saves a lot of time in child
235 processes
237 static void prime_ldb_databases(struct tevent_context *event_ctx)
239 TALLOC_CTX *db_context;
240 db_context = talloc_new(event_ctx);
242 samdb_connect(db_context,
243 event_ctx,
244 cmdline_lp_ctx,
245 system_session(cmdline_lp_ctx),
247 privilege_connect(db_context, cmdline_lp_ctx);
249 /* we deliberately leave these open, which allows them to be
250 * re-used in ldb_wrap_connect() */
255 called from 'smbcontrol samba shutdown'
257 static void samba_parent_shutdown(struct imessaging_context *msg,
258 void *private_data,
259 uint32_t msg_type,
260 struct server_id src,
261 DATA_BLOB *data)
263 struct server_state *state =
264 talloc_get_type_abort(private_data,
265 struct server_state);
266 struct server_id_buf src_buf;
267 struct server_id dst = imessaging_get_server_id(msg);
268 struct server_id_buf dst_buf;
270 DBG_ERR("samba_shutdown of %s %s: from %s\n",
271 state->binary_name,
272 server_id_str_buf(dst, &dst_buf),
273 server_id_str_buf(src, &src_buf));
275 TALLOC_FREE(state);
276 exit(0);
280 called when a fatal condition occurs in a child task
282 static NTSTATUS samba_terminate(struct irpc_message *msg,
283 struct samba_terminate *r)
285 struct server_state *state = talloc_get_type(msg->private_data,
286 struct server_state);
287 DBG_ERR("samba_terminate of %s %d: %s\n",
288 state->binary_name, (int)getpid(), r->in.reason);
289 TALLOC_FREE(state);
290 exit(1);
294 setup messaging for the top level samba (parent) task
296 static NTSTATUS setup_parent_messaging(struct server_state *state,
297 struct loadparm_context *lp_ctx)
299 struct imessaging_context *msg;
300 NTSTATUS status;
302 msg = imessaging_init(state->event_ctx,
303 lp_ctx,
304 cluster_id(getpid(), SAMBA_PARENT_TASKID),
305 state->event_ctx);
306 NT_STATUS_HAVE_NO_MEMORY(msg);
308 status = irpc_add_name(msg, "samba");
309 if (!NT_STATUS_IS_OK(status)) {
310 return status;
313 status = imessaging_register(msg, state, MSG_SHUTDOWN,
314 samba_parent_shutdown);
315 if (!NT_STATUS_IS_OK(status)) {
316 return status;
319 status = IRPC_REGISTER(msg, irpc, SAMBA_TERMINATE,
320 samba_terminate, state);
321 if (!NT_STATUS_IS_OK(status)) {
322 return status;
325 return NT_STATUS_OK;
330 show build info
332 static void show_build(void)
334 #define CONFIG_OPTION(n) { #n, dyn_ ## n }
335 struct {
336 const char *name;
337 const char *value;
338 } config_options[] = {
339 CONFIG_OPTION(BINDIR),
340 CONFIG_OPTION(SBINDIR),
341 CONFIG_OPTION(CONFIGFILE),
342 CONFIG_OPTION(NCALRPCDIR),
343 CONFIG_OPTION(LOGFILEBASE),
344 CONFIG_OPTION(LMHOSTSFILE),
345 CONFIG_OPTION(DATADIR),
346 CONFIG_OPTION(MODULESDIR),
347 CONFIG_OPTION(LOCKDIR),
348 CONFIG_OPTION(STATEDIR),
349 CONFIG_OPTION(CACHEDIR),
350 CONFIG_OPTION(PIDDIR),
351 CONFIG_OPTION(PRIVATE_DIR),
352 CONFIG_OPTION(CODEPAGEDIR),
353 CONFIG_OPTION(SETUPDIR),
354 CONFIG_OPTION(WINBINDD_SOCKET_DIR),
355 CONFIG_OPTION(NTP_SIGND_SOCKET_DIR),
356 { NULL, NULL}
358 int i;
360 printf("Samba version: %s\n", SAMBA_VERSION_STRING);
361 printf("Build environment:\n");
363 printf("Paths:\n");
364 for (i=0; config_options[i].name; i++) {
365 printf(" %s: %s\n",
366 config_options[i].name,
367 config_options[i].value);
370 exit(0);
373 static int event_ctx_destructor(struct tevent_context *event_ctx)
375 imessaging_dgm_unref_ev(event_ctx);
376 return 0;
379 #ifdef HAVE_PTHREAD
380 static int to_children_fd = -1;
381 static void atfork_prepare(void) {
383 static void atfork_parent(void) {
385 static void atfork_child(void) {
386 if (to_children_fd != -1) {
387 close(to_children_fd);
388 to_children_fd = -1;
391 #endif
394 main server.
396 static int binary_smbd_main(const char *binary_name,
397 int argc,
398 const char *argv[])
400 bool opt_daemon = false;
401 bool opt_fork = true;
402 bool opt_interactive = false;
403 bool opt_no_process_group = false;
404 int opt;
405 poptContext pc;
406 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
407 STATIC_service_MODULES_PROTO;
408 init_module_fn static_init[] = { STATIC_service_MODULES };
409 init_module_fn *shared_init;
410 uint16_t stdin_event_flags;
411 NTSTATUS status;
412 const char *model = "standard";
413 int max_runtime = 0;
414 struct stat st;
415 enum {
416 OPT_DAEMON = 1000,
417 OPT_FOREGROUND,
418 OPT_INTERACTIVE,
419 OPT_PROCESS_MODEL,
420 OPT_SHOW_BUILD,
421 OPT_NO_PROCESS_GROUP,
423 struct poptOption long_options[] = {
424 POPT_AUTOHELP
425 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON,
426 "Become a daemon (default)", NULL },
427 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FOREGROUND,
428 "Run the daemon in foreground", NULL },
429 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE,
430 "Run interactive (not a daemon)", NULL},
431 {"model", 'M', POPT_ARG_STRING, NULL, OPT_PROCESS_MODEL,
432 "Select process model", "MODEL"},
433 {"maximum-runtime",0, POPT_ARG_INT, &max_runtime, 0,
434 "set maximum runtime of the server process, "
435 "till autotermination", "seconds"},
436 {"show-build", 'b', POPT_ARG_NONE, NULL, OPT_SHOW_BUILD,
437 "show build info", NULL },
438 {"no-process-group", '\0', POPT_ARG_NONE, NULL,
439 OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
440 POPT_COMMON_SAMBA
441 POPT_COMMON_VERSION
442 { NULL }
444 struct server_state *state = NULL;
445 struct tevent_signal *se = NULL;
447 setproctitle("root process");
449 pc = poptGetContext(binary_name, argc, argv, long_options, 0);
450 while((opt = poptGetNextOpt(pc)) != -1) {
451 switch(opt) {
452 case OPT_DAEMON:
453 opt_daemon = true;
454 break;
455 case OPT_FOREGROUND:
456 opt_fork = false;
457 break;
458 case OPT_INTERACTIVE:
459 opt_interactive = true;
460 break;
461 case OPT_PROCESS_MODEL:
462 model = poptGetOptArg(pc);
463 break;
464 case OPT_SHOW_BUILD:
465 show_build();
466 break;
467 case OPT_NO_PROCESS_GROUP:
468 opt_no_process_group = true;
469 break;
470 default:
471 fprintf(stderr, "\nInvalid option %s: %s\n\n",
472 poptBadOption(pc, 0), poptStrerror(opt));
473 poptPrintUsage(pc, stderr, 0);
474 return 1;
478 if (opt_daemon && opt_interactive) {
479 fprintf(stderr,"\nERROR: "
480 "Option -i|--interactive is "
481 "not allowed together with -D|--daemon\n\n");
482 poptPrintUsage(pc, stderr, 0);
483 return 1;
484 } else if (!opt_interactive && opt_fork) {
485 /* default is --daemon */
486 opt_daemon = true;
489 poptFreeContext(pc);
491 talloc_enable_null_tracking();
493 setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
494 setup_signals();
496 /* we want total control over the permissions on created files,
497 so set our umask to 0 */
498 umask(0);
500 DEBUG(0,("%s version %s started.\n",
501 binary_name,
502 SAMBA_VERSION_STRING));
503 DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team"
504 " 1992-2018\n"));
506 if (sizeof(uint16_t) < 2 ||
507 sizeof(uint32_t) < 4 ||
508 sizeof(uint64_t) < 8) {
509 DEBUG(0,("ERROR: Samba is not configured correctly "
510 "for the word size on your machine\n"));
511 DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, "
512 "sizeof(uint64_t) = %u\n",
513 (unsigned int)sizeof(uint16_t),
514 (unsigned int)sizeof(uint32_t),
515 (unsigned int)sizeof(uint64_t)));
516 return 1;
519 if (opt_daemon) {
520 DBG_NOTICE("Becoming a daemon.\n");
521 become_daemon(opt_fork, opt_no_process_group, false);
524 /* Create the memory context to hang everything off. */
525 state = talloc_zero(NULL, struct server_state);
526 if (state == NULL) {
527 exit_daemon("Samba cannot create server state", ENOMEM);
529 state->binary_name = binary_name;
531 cleanup_tmp_files(cmdline_lp_ctx);
533 if (!directory_exist(lpcfg_lock_directory(cmdline_lp_ctx))) {
534 mkdir(lpcfg_lock_directory(cmdline_lp_ctx), 0755);
537 pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);
539 if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
540 if (!open_schannel_session_store(state,
541 cmdline_lp_ctx)) {
542 TALLOC_FREE(state);
543 exit_daemon("Samba cannot open schannel store "
544 "for secured NETLOGON operations.", EACCES);
548 /* make sure we won't go through nss_winbind */
549 if (!winbind_off()) {
550 TALLOC_FREE(state);
551 exit_daemon("Samba failed to disable recusive "
552 "winbindd calls.", EACCES);
555 gensec_init(); /* FIXME: */
557 process_model_init(cmdline_lp_ctx);
559 shared_init = load_samba_modules(NULL, "service");
561 run_init_functions(NULL, static_init);
562 run_init_functions(NULL, shared_init);
564 talloc_free(shared_init);
566 /* the event context is the top level structure in smbd. Everything else
567 should hang off that */
568 state->event_ctx = s4_event_context_init(state);
570 if (state->event_ctx == NULL) {
571 TALLOC_FREE(state);
572 exit_daemon("Initializing event context failed", EACCES);
575 talloc_set_destructor(state->event_ctx, event_ctx_destructor);
577 if (opt_interactive) {
578 /* terminate when stdin goes away */
579 stdin_event_flags = TEVENT_FD_READ;
580 } else {
581 /* stay alive forever */
582 stdin_event_flags = 0;
585 #if HAVE_SETPGID
587 * If we're interactive we want to set our own process group for
588 * signal management, unless --no-process-group specified.
590 if (opt_interactive && !opt_no_process_group)
591 setpgid((pid_t)0, (pid_t)0);
592 #endif
594 /* catch EOF on stdin */
595 #ifdef SIGTTIN
596 signal(SIGTTIN, SIG_IGN);
597 #endif
599 if (fstat(0, &st) != 0) {
600 TALLOC_FREE(state);
601 exit_daemon("Samba failed to set standard input handler",
602 ENOTTY);
605 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
606 struct tevent_fd *fde = tevent_add_fd(state->event_ctx,
607 state->event_ctx,
609 stdin_event_flags,
610 server_stdin_handler,
611 state);
612 if (fde == NULL) {
613 TALLOC_FREE(state);
614 exit_daemon("Initializing stdin failed", ENOMEM);
618 if (max_runtime) {
619 struct tevent_timer *te;
620 DBG_ERR("%s PID %d was called with maxruntime %d - "
621 "current ts %llu\n",
622 binary_name, (int)getpid(),
623 max_runtime, (unsigned long long) time(NULL));
624 te = tevent_add_timer(state->event_ctx, state->event_ctx,
625 timeval_current_ofs(max_runtime, 0),
626 max_runtime_handler,
627 state);
628 if (te == NULL) {
629 TALLOC_FREE(state);
630 exit_daemon("Maxruntime handler failed", ENOMEM);
634 se = tevent_add_signal(state->event_ctx,
635 state->event_ctx,
636 SIGTERM,
638 sigterm_signal_handler,
639 state);
640 if (se == NULL) {
641 TALLOC_FREE(state);
642 exit_daemon("Initialize SIGTERM handler failed", ENOMEM);
645 if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
646 && !lpcfg_parm_bool(cmdline_lp_ctx, NULL,
647 "server role check", "inhibit", false)
648 && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb")
649 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
650 "remote")
651 && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
652 "mapiproxy")) {
653 DEBUG(0, ("At this time the 'samba' binary should only be used "
654 "for either:\n"));
655 DEBUGADD(0, ("'server role = active directory domain "
656 "controller' or to access the ntvfs file server "
657 "with 'server services = +smb' or the rpc proxy "
658 "with 'dcerpc endpoint servers = remote'\n"));
659 DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for "
660 "domain member and standalone file server tasks\n"));
661 exit_daemon("Samba detected misconfigured 'server role' "
662 "and exited. Check logs for details", EINVAL);
665 prime_ldb_databases(state->event_ctx);
667 status = setup_parent_messaging(state, cmdline_lp_ctx);
668 if (!NT_STATUS_IS_OK(status)) {
669 TALLOC_FREE(state);
670 exit_daemon("Samba failed to setup parent messaging",
671 NT_STATUS_V(status));
674 DBG_ERR("%s: using '%s' process model\n", binary_name, model);
677 int child_pipe[2];
678 int rc;
679 bool start_services = false;
681 rc = pipe(child_pipe);
682 if (rc < 0) {
683 TALLOC_FREE(state);
684 exit_daemon("Samba failed to open process control pipe",
685 errno);
687 smb_set_close_on_exec(child_pipe[0]);
688 smb_set_close_on_exec(child_pipe[1]);
690 #ifdef HAVE_PTHREAD
691 to_children_fd = child_pipe[1];
692 pthread_atfork(atfork_prepare, atfork_parent,
693 atfork_child);
694 start_services = true;
695 #else
696 pid_t pid;
697 struct tfork *t = NULL;
698 t = tfork_create();
699 if (t == NULL) {
700 exit_daemon(
701 "Samba unable to fork master process",
704 pid = tfork_child_pid(t);
705 if (pid == 0) {
706 start_services = false;
707 } else {
708 /* In the child process */
709 start_services = true;
710 close(child_pipe[1]);
712 #endif
713 if (start_services) {
714 status = server_service_startup(
715 state->event_ctx, cmdline_lp_ctx, model,
716 lpcfg_server_services(cmdline_lp_ctx),
717 child_pipe[0]);
718 if (!NT_STATUS_IS_OK(status)) {
719 TALLOC_FREE(state);
720 exit_daemon("Samba failed to start services",
721 NT_STATUS_V(status));
726 if (opt_daemon) {
727 daemon_ready("samba");
730 /* wait for events - this is where smbd sits for most of its
731 life */
732 tevent_loop_wait(state->event_ctx);
734 /* as everything hangs off this state->event context, freeing state
735 will initiate a clean shutdown of all services */
736 TALLOC_FREE(state);
738 return 0;
741 int main(int argc, const char *argv[])
743 setproctitle_init(argc, discard_const(argv), environ);
745 return binary_smbd_main("samba", argc, argv);