ea421b3bd68811ed8e4fe4163b6241a7e2946061
[samba.git] / source4 / smbd / server.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Main SMB server routines
5
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>
10
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.
15
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.
20
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/>.
23 */
24
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"
49
50 #ifdef HAVE_PTHREAD
51 #include <pthread.h>
52 #endif
53
54 struct server_state {
55         struct tevent_context *event_ctx;
56         const char *binary_name;
57 };
58
59 /*
60   recursively delete a directory tree
61 */
62 static void recursive_delete(const char *path)
63 {
64         DIR *dir;
65         struct dirent *de;
66
67         dir = opendir(path);
68         if (!dir) {
69                 return;
70         }
71
72         for (de=readdir(dir);de;de=readdir(dir)) {
73                 char *fname;
74                 struct stat st;
75
76                 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name)) {
77                         continue;
78                 }
79
80                 fname = talloc_asprintf(path, "%s/%s", path, de->d_name);
81                 if (stat(fname, &st) != 0) {
82                         continue;
83                 }
84                 if (S_ISDIR(st.st_mode)) {
85                         recursive_delete(fname);
86                         talloc_free(fname);
87                         continue;
88                 }
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");
93                 }
94                 talloc_free(fname);
95         }
96         closedir(dir);
97 }
98
99 /*
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.
105 */
106 static void cleanup_tmp_files(struct loadparm_context *lp_ctx)
107 {
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);
113         }
114
115         path = smbd_tmp_path(mem_ctx, lp_ctx, NULL);
116         if (path == NULL) {
117                 exit_daemon("Failed to cleanup temporary files",
118                             EINVAL);
119         }
120
121         recursive_delete(path);
122         talloc_free(mem_ctx);
123 }
124
125 static void sig_hup(int sig)
126 {
127         debug_schedule_reopen_logs();
128 }
129
130 static void sig_term(int sig)
131 {
132 #ifdef HAVE_GETPGRP
133         if (getpgrp() == getpid()) {
134                 /*
135                  * We're the process group leader, send
136                  * SIGTERM to our process group.
137                  */
138                 kill(-getpgrp(), SIGTERM);
139         }
140 #endif
141         _exit(127);
142 }
143
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)
148 {
149         struct server_state *state = talloc_get_type_abort(
150                 private_data, struct server_state);
151
152         DBG_DEBUG("Process %s got SIGTERM\n", state->binary_name);
153         TALLOC_FREE(state);
154         sig_term(SIGTERM);
155 }
156
157 /*
158   setup signal masks
159 */
160 static void setup_signals(void)
161 {
162         /* we are never interested in SIGPIPE */
163         BlockSignals(true,SIGPIPE);
164
165 #if defined(SIGFPE)
166         /* we are never interested in SIGFPE */
167         BlockSignals(true,SIGFPE);
168 #endif
169
170         /* We are no longer interested in USR1 */
171         BlockSignals(true, SIGUSR1);
172
173 #if defined(SIGUSR2)
174         /* We are no longer interested in USR2 */
175         BlockSignals(true,SIGUSR2);
176 #endif
177
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);
183
184         CatchSignal(SIGHUP, sig_hup);
185         CatchSignal(SIGTERM, sig_term);
186 }
187
188 /*
189   handle io on stdin
190 */
191 static void server_stdin_handler(struct tevent_context *event_ctx,
192                                 struct tevent_fd *fde,
193                                 uint16_t flags,
194                                 void *private_data)
195 {
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 #ifdef HAVE_GETPGRP
203                 if (getpgrp() == getpid()) {
204                         DBG_ERR("Sending SIGTERM from pid %d\n",
205                                 (int)getpid());
206                         kill(-getpgrp(), SIGTERM);
207                 }
208 #endif
209                 TALLOC_FREE(state);
210                 exit(0);
211         }
212 }
213
214 /*
215   die if the user selected maximum runtime is exceeded
216 */
217 _NORETURN_ static void max_runtime_handler(struct tevent_context *ev,
218                                            struct tevent_timer *te,
219                                            struct timeval t, void *private_data)
220 {
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);
231 }
232
233 /*
234   pre-open the key databases. This saves a lot of time in child
235   processes
236  */
237 static int prime_ldb_databases(struct tevent_context *event_ctx, bool *am_backup)
238 {
239         struct ldb_result *res = NULL;
240         struct ldb_dn *samba_dsdb_dn = NULL;
241         struct ldb_context *ldb_ctx = NULL;
242         struct ldb_context *pdb = NULL;
243         static const char *attrs[] = { "backupDate", NULL };
244         const char *msg = NULL;
245         int ret;
246         TALLOC_CTX *db_context = talloc_new(event_ctx);
247         if (db_context == NULL) {
248                 return LDB_ERR_OPERATIONS_ERROR;
249         }
250
251         *am_backup = false;
252
253         /* note we deliberately leave these open, which allows them to be
254          * re-used in ldb_wrap_connect() */
255         ldb_ctx = samdb_connect(db_context,
256                                 event_ctx,
257                                 cmdline_lp_ctx,
258                                 system_session(cmdline_lp_ctx),
259                                 NULL,
260                                 0);
261         if (ldb_ctx == NULL) {
262                 talloc_free(db_context);
263                 return LDB_ERR_OPERATIONS_ERROR;
264         }
265         pdb = privilege_connect(db_context, cmdline_lp_ctx);
266         if (pdb == NULL) {
267                 talloc_free(db_context);
268                 return LDB_ERR_OPERATIONS_ERROR;
269         }
270
271         /* check the root DB object to see if it's marked as a backup */
272         samba_dsdb_dn = ldb_dn_new(db_context, ldb_ctx, "@SAMBA_DSDB");
273         if (!samba_dsdb_dn) {
274                 talloc_free(db_context);
275                 return LDB_ERR_OPERATIONS_ERROR;
276         }
277
278         ret = dsdb_search_dn(ldb_ctx, db_context, &res, samba_dsdb_dn, attrs,
279                              DSDB_FLAG_AS_SYSTEM);
280         if (ret != LDB_SUCCESS) {
281                 talloc_free(db_context);
282                 return ret;
283         }
284
285         if (res->count > 0) {
286                 msg = ldb_msg_find_attr_as_string(res->msgs[0], "backupDate",
287                                                   NULL);
288                 if (msg != NULL) {
289                         *am_backup = true;
290                 }
291         }
292         return LDB_SUCCESS;
293 }
294
295 /*
296   called from 'smbcontrol samba shutdown'
297  */
298 static void samba_parent_shutdown(struct imessaging_context *msg,
299                                   void *private_data,
300                                   uint32_t msg_type,
301                                   struct server_id src,
302                                   DATA_BLOB *data)
303 {
304         struct server_state *state =
305                 talloc_get_type_abort(private_data,
306                 struct server_state);
307         struct server_id_buf src_buf;
308         struct server_id dst = imessaging_get_server_id(msg);
309         struct server_id_buf dst_buf;
310
311         DBG_ERR("samba_shutdown of %s %s: from %s\n",
312                 state->binary_name,
313                 server_id_str_buf(dst, &dst_buf),
314                 server_id_str_buf(src, &src_buf));
315
316         TALLOC_FREE(state);
317         exit(0);
318 }
319
320 /*
321   called when a fatal condition occurs in a child task
322  */
323 static NTSTATUS samba_terminate(struct irpc_message *msg,
324                                 struct samba_terminate *r)
325 {
326         struct server_state *state = talloc_get_type(msg->private_data,
327                                         struct server_state);
328         DBG_ERR("samba_terminate of %s %d: %s\n",
329                 state->binary_name, (int)getpid(), r->in.reason);
330         TALLOC_FREE(state);
331         exit(1);
332 }
333
334 /*
335   setup messaging for the top level samba (parent) task
336  */
337 static NTSTATUS setup_parent_messaging(struct server_state *state,
338                                        struct loadparm_context *lp_ctx)
339 {
340         struct imessaging_context *msg;
341         NTSTATUS status;
342
343         msg = imessaging_init(state->event_ctx,
344                               lp_ctx,
345                               cluster_id(getpid(), SAMBA_PARENT_TASKID),
346                               state->event_ctx);
347         NT_STATUS_HAVE_NO_MEMORY(msg);
348
349         status = irpc_add_name(msg, "samba");
350         if (!NT_STATUS_IS_OK(status)) {
351                 return status;
352         }
353
354         status = imessaging_register(msg, state, MSG_SHUTDOWN,
355                                      samba_parent_shutdown);
356         if (!NT_STATUS_IS_OK(status)) {
357                 return status;
358         }
359
360         status = IRPC_REGISTER(msg, irpc, SAMBA_TERMINATE,
361                                samba_terminate, state);
362         if (!NT_STATUS_IS_OK(status)) {
363                 return status;
364         }
365
366         return NT_STATUS_OK;
367 }
368
369
370 /*
371   show build info
372  */
373 static void show_build(void)
374 {
375 #define CONFIG_OPTION(n) { #n, dyn_ ## n }
376         struct {
377                 const char *name;
378                 const char *value;
379         } config_options[] = {
380                 CONFIG_OPTION(BINDIR),
381                 CONFIG_OPTION(SBINDIR),
382                 CONFIG_OPTION(CONFIGFILE),
383                 CONFIG_OPTION(NCALRPCDIR),
384                 CONFIG_OPTION(LOGFILEBASE),
385                 CONFIG_OPTION(LMHOSTSFILE),
386                 CONFIG_OPTION(DATADIR),
387                 CONFIG_OPTION(MODULESDIR),
388                 CONFIG_OPTION(LOCKDIR),
389                 CONFIG_OPTION(STATEDIR),
390                 CONFIG_OPTION(CACHEDIR),
391                 CONFIG_OPTION(PIDDIR),
392                 CONFIG_OPTION(PRIVATE_DIR),
393                 CONFIG_OPTION(CODEPAGEDIR),
394                 CONFIG_OPTION(SETUPDIR),
395                 CONFIG_OPTION(WINBINDD_SOCKET_DIR),
396                 CONFIG_OPTION(NTP_SIGND_SOCKET_DIR),
397                 { NULL, NULL}
398         };
399         int i;
400
401         printf("Samba version: %s\n", SAMBA_VERSION_STRING);
402         printf("Build environment:\n");
403
404         printf("Paths:\n");
405         for (i=0; config_options[i].name; i++) {
406                 printf("   %s: %s\n",
407                         config_options[i].name,
408                         config_options[i].value);
409         }
410
411         exit(0);
412 }
413
414 static int event_ctx_destructor(struct tevent_context *event_ctx)
415 {
416         imessaging_dgm_unref_ev(event_ctx);
417         return 0;
418 }
419
420 #ifdef HAVE_PTHREAD
421 static int to_children_fd = -1;
422 static void atfork_prepare(void) {
423 }
424 static void atfork_parent(void) {
425 }
426 static void atfork_child(void) {
427         if (to_children_fd != -1) {
428                 close(to_children_fd);
429                 to_children_fd = -1;
430         }
431 }
432 #endif
433
434 /*
435  main server.
436 */
437 static int binary_smbd_main(const char *binary_name,
438                                 int argc,
439                                 const char *argv[])
440 {
441         bool opt_daemon = false;
442         bool opt_fork = true;
443         bool opt_interactive = false;
444         bool opt_no_process_group = false;
445         bool db_is_backup = false;
446         int opt;
447         int ret;
448         poptContext pc;
449 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
450         STATIC_service_MODULES_PROTO;
451         init_module_fn static_init[] = { STATIC_service_MODULES };
452         init_module_fn *shared_init;
453         uint16_t stdin_event_flags;
454         NTSTATUS status;
455         const char *model = "prefork";
456         int max_runtime = 0;
457         struct stat st;
458         enum {
459                 OPT_DAEMON = 1000,
460                 OPT_FOREGROUND,
461                 OPT_INTERACTIVE,
462                 OPT_PROCESS_MODEL,
463                 OPT_SHOW_BUILD,
464                 OPT_NO_PROCESS_GROUP,
465         };
466         struct poptOption long_options[] = {
467                 POPT_AUTOHELP
468                 {
469                         .longName   = "daemon",
470                         .shortName  = 'D',
471                         .argInfo    = POPT_ARG_NONE,
472                         .val        = OPT_DAEMON,
473                         .descrip    = "Become a daemon (default)",
474                 },
475                 {
476                         .longName   = "foreground",
477                         .shortName  = 'F',
478                         .argInfo    = POPT_ARG_NONE,
479                         .val        = OPT_FOREGROUND,
480                         .descrip    = "Run the daemon in foreground",
481                 },
482                 {
483                         .longName   = "interactive",
484                         .shortName  = 'i',
485                         .argInfo    = POPT_ARG_NONE,
486                         .val        = OPT_INTERACTIVE,
487                         .descrip    = "Run interactive (not a daemon)",
488                 },
489                 {
490                         .longName   = "model",
491                         .shortName  = 'M',
492                         .argInfo    = POPT_ARG_STRING,
493                         .val        = OPT_PROCESS_MODEL,
494                         .descrip    = "Select process model",
495                         .argDescrip = "MODEL",
496                 },
497                 {
498                         .longName   = "maximum-runtime",
499                         .argInfo    = POPT_ARG_INT,
500                         .arg        = &max_runtime,
501                         .descrip    = "set maximum runtime of the server process, "
502                                       "till autotermination",
503                         .argDescrip = "seconds"
504                 },
505                 {
506                         .longName   = "show-build",
507                         .shortName  = 'b',
508                         .argInfo    = POPT_ARG_NONE,
509                         .val        = OPT_SHOW_BUILD,
510                         .descrip    = "show build info",
511                 },
512                 {
513                         .longName   = "no-process-group",
514                         .argInfo    = POPT_ARG_NONE,
515                         .val        = OPT_NO_PROCESS_GROUP,
516                         .descrip    = "Don't create a new process group",
517                 },
518                 POPT_COMMON_SAMBA
519                 POPT_COMMON_VERSION
520                 POPT_TABLEEND
521         };
522         struct server_state *state = NULL;
523         struct tevent_signal *se = NULL;
524
525         setproctitle("root process");
526
527         pc = poptGetContext(binary_name, argc, argv, long_options, 0);
528         while((opt = poptGetNextOpt(pc)) != -1) {
529                 switch(opt) {
530                 case OPT_DAEMON:
531                         opt_daemon = true;
532                         break;
533                 case OPT_FOREGROUND:
534                         opt_fork = false;
535                         break;
536                 case OPT_INTERACTIVE:
537                         opt_interactive = true;
538                         break;
539                 case OPT_PROCESS_MODEL:
540                         model = poptGetOptArg(pc);
541                         break;
542                 case OPT_SHOW_BUILD:
543                         show_build();
544                         break;
545                 case OPT_NO_PROCESS_GROUP:
546                         opt_no_process_group = true;
547                         break;
548                 default:
549                         fprintf(stderr, "\nInvalid option %s: %s\n\n",
550                                   poptBadOption(pc, 0), poptStrerror(opt));
551                         poptPrintUsage(pc, stderr, 0);
552                         return 1;
553                 }
554         }
555
556         if (opt_daemon && opt_interactive) {
557                 fprintf(stderr,"\nERROR: "
558                         "Option -i|--interactive is "
559                         "not allowed together with -D|--daemon\n\n");
560                 poptPrintUsage(pc, stderr, 0);
561                 return 1;
562         } else if (!opt_interactive && opt_fork) {
563                 /* default is --daemon */
564                 opt_daemon = true;
565         }
566
567         poptFreeContext(pc);
568
569         talloc_enable_null_tracking();
570
571         setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
572         setup_signals();
573
574         /* we want total control over the permissions on created files,
575            so set our umask to 0 */
576         umask(0);
577
578         DEBUG(0,("%s version %s started.\n",
579                 binary_name,
580                 SAMBA_VERSION_STRING));
581         DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team"
582                 " 1992-2019\n"));
583
584         if (sizeof(uint16_t) < 2 ||
585                         sizeof(uint32_t) < 4 ||
586                         sizeof(uint64_t) < 8) {
587                 DEBUG(0,("ERROR: Samba is not configured correctly "
588                         "for the word size on your machine\n"));
589                 DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, "
590                         "sizeof(uint64_t) = %u\n",
591                         (unsigned int)sizeof(uint16_t),
592                         (unsigned int)sizeof(uint32_t),
593                         (unsigned int)sizeof(uint64_t)));
594                 return 1;
595         }
596
597         if (opt_daemon) {
598                 DBG_NOTICE("Becoming a daemon.\n");
599                 become_daemon(opt_fork, opt_no_process_group, false);
600         }
601
602         /* Create the memory context to hang everything off. */
603         state = talloc_zero(NULL, struct server_state);
604         if (state == NULL) {
605                 exit_daemon("Samba cannot create server state", ENOMEM);
606         };
607         state->binary_name = binary_name;
608
609         cleanup_tmp_files(cmdline_lp_ctx);
610
611         if (!directory_exist(lpcfg_lock_directory(cmdline_lp_ctx))) {
612                 mkdir(lpcfg_lock_directory(cmdline_lp_ctx), 0755);
613         }
614
615         if (!directory_exist(lpcfg_pid_directory(cmdline_lp_ctx))) {
616                 mkdir(lpcfg_pid_directory(cmdline_lp_ctx), 0755);
617         }
618
619         pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);
620
621         if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
622                 if (!open_schannel_session_store(state,
623                                 cmdline_lp_ctx)) {
624                         TALLOC_FREE(state);
625                         exit_daemon("Samba cannot open schannel store "
626                                 "for secured NETLOGON operations.", EACCES);
627                 }
628         }
629
630         /* make sure we won't go through nss_winbind */
631         if (!winbind_off()) {
632                 TALLOC_FREE(state);
633                 exit_daemon("Samba failed to disable recusive "
634                         "winbindd calls.", EACCES);
635         }
636
637         gensec_init(); /* FIXME: */
638
639         process_model_init(cmdline_lp_ctx);
640
641         shared_init = load_samba_modules(NULL, "service");
642
643         run_init_functions(NULL, static_init);
644         run_init_functions(NULL, shared_init);
645
646         talloc_free(shared_init);
647
648         /* the event context is the top level structure in smbd. Everything else
649            should hang off that */
650         state->event_ctx = s4_event_context_init(state);
651
652         if (state->event_ctx == NULL) {
653                 TALLOC_FREE(state);
654                 exit_daemon("Initializing event context failed", EACCES);
655         }
656
657         talloc_set_destructor(state->event_ctx, event_ctx_destructor);
658
659         if (opt_interactive) {
660                 /* terminate when stdin goes away */
661                 stdin_event_flags = TEVENT_FD_READ;
662         } else {
663                 /* stay alive forever */
664                 stdin_event_flags = 0;
665         }
666
667 #ifdef HAVE_SETPGID
668         /*
669          * If we're interactive we want to set our own process group for
670          * signal management, unless --no-process-group specified.
671          */
672         if (opt_interactive && !opt_no_process_group)
673                 setpgid((pid_t)0, (pid_t)0);
674 #endif
675
676         /* catch EOF on stdin */
677 #ifdef SIGTTIN
678         signal(SIGTTIN, SIG_IGN);
679 #endif
680
681         if (fstat(0, &st) != 0) {
682                 TALLOC_FREE(state);
683                 exit_daemon("Samba failed to set standard input handler",
684                                 ENOTTY);
685         }
686
687         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
688                 struct tevent_fd *fde = tevent_add_fd(state->event_ctx,
689                                 state->event_ctx,
690                                 0,
691                                 stdin_event_flags,
692                                 server_stdin_handler,
693                                 state);
694                 if (fde == NULL) {
695                         TALLOC_FREE(state);
696                         exit_daemon("Initializing stdin failed", ENOMEM);
697                 }
698         }
699
700         if (max_runtime) {
701                 struct tevent_timer *te;
702                 DBG_ERR("%s PID %d was called with maxruntime %d - "
703                         "current ts %llu\n",
704                         binary_name, (int)getpid(),
705                         max_runtime, (unsigned long long) time(NULL));
706                 te = tevent_add_timer(state->event_ctx, state->event_ctx,
707                                  timeval_current_ofs(max_runtime, 0),
708                                  max_runtime_handler,
709                                  state);
710                 if (te == NULL) {
711                         TALLOC_FREE(state);
712                         exit_daemon("Maxruntime handler failed", ENOMEM);
713                 }
714         }
715
716         se = tevent_add_signal(state->event_ctx,
717                                 state->event_ctx,
718                                 SIGTERM,
719                                 0,
720                                 sigterm_signal_handler,
721                                 state);
722         if (se == NULL) {
723                 TALLOC_FREE(state);
724                 exit_daemon("Initialize SIGTERM handler failed", ENOMEM);
725         }
726
727         if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
728             && !lpcfg_parm_bool(cmdline_lp_ctx, NULL,
729                         "server role check", "inhibit", false)
730             && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb")
731             && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
732                         "remote")
733             && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
734                         "mapiproxy")) {
735                 DEBUG(0, ("At this time the 'samba' binary should only be used "
736                         "for either:\n"));
737                 DEBUGADD(0, ("'server role = active directory domain "
738                         "controller' or to access the ntvfs file server "
739                         "with 'server services = +smb' or the rpc proxy "
740                         "with 'dcerpc endpoint servers = remote'\n"));
741                 DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for "
742                         "domain member and standalone file server tasks\n"));
743                 exit_daemon("Samba detected misconfigured 'server role' "
744                         "and exited. Check logs for details", EINVAL);
745         };
746
747         ret = prime_ldb_databases(state->event_ctx, &db_is_backup);
748         if (ret != LDB_SUCCESS) {
749                 TALLOC_FREE(state);
750                 exit_daemon("Samba failed to prime database", EINVAL);
751         }
752
753         if (db_is_backup) {
754                 TALLOC_FREE(state);
755                 exit_daemon("Database is a backup. Please run samba-tool domain"
756                             " backup restore", EINVAL);
757         }
758
759         status = setup_parent_messaging(state, cmdline_lp_ctx);
760         if (!NT_STATUS_IS_OK(status)) {
761                 TALLOC_FREE(state);
762                 exit_daemon("Samba failed to setup parent messaging",
763                         NT_STATUS_V(status));
764         }
765
766         DBG_ERR("%s: using '%s' process model\n", binary_name, model);
767
768         {
769                 int child_pipe[2];
770                 int rc;
771                 bool start_services = false;
772
773                 rc = pipe(child_pipe);
774                 if (rc < 0) {
775                         TALLOC_FREE(state);
776                         exit_daemon("Samba failed to open process control pipe",
777                                     errno);
778                 }
779                 smb_set_close_on_exec(child_pipe[0]);
780                 smb_set_close_on_exec(child_pipe[1]);
781
782 #ifdef HAVE_PTHREAD
783                 to_children_fd = child_pipe[1];
784                 pthread_atfork(atfork_prepare, atfork_parent,
785                                atfork_child);
786                 start_services = true;
787 #else
788                 pid_t pid;
789                 struct tfork *t = NULL;
790                 t = tfork_create();
791                 if (t == NULL) {
792                         exit_daemon(
793                                 "Samba unable to fork master process",
794                                 0);
795                 }
796                 pid = tfork_child_pid(t);
797                 if (pid == 0) {
798                         start_services = false;
799                 } else {
800                         /* In the child process */
801                         start_services = true;
802                         close(child_pipe[1]);
803                 }
804 #endif
805                 if (start_services) {
806                         status = server_service_startup(
807                                 state->event_ctx, cmdline_lp_ctx, model,
808                                 lpcfg_server_services(cmdline_lp_ctx),
809                                 child_pipe[0]);
810                         if (!NT_STATUS_IS_OK(status)) {
811                                 TALLOC_FREE(state);
812                                 exit_daemon("Samba failed to start services",
813                                 NT_STATUS_V(status));
814                         }
815                 }
816         }
817
818         if (opt_daemon) {
819                 daemon_ready("samba");
820         }
821
822         /* wait for events - this is where smbd sits for most of its
823            life */
824         tevent_loop_wait(state->event_ctx);
825
826         /* as everything hangs off this state->event context, freeing state
827            will initiate a clean shutdown of all services */
828         TALLOC_FREE(state);
829
830         return 0;
831 }
832
833 int main(int argc, const char *argv[])
834 {
835         setproctitle_init(argc, discard_const(argv), environ);
836
837         return binary_smbd_main("samba", argc, argv);
838 }