s4/smbd: set the process group.
[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
47 struct server_state {
48         struct tevent_context *event_ctx;
49         const char *binary_name;
50 };
51
52 /*
53   recursively delete a directory tree
54 */
55 static void recursive_delete(const char *path)
56 {
57         DIR *dir;
58         struct dirent *de;
59
60         dir = opendir(path);
61         if (!dir) {
62                 return;
63         }
64
65         for (de=readdir(dir);de;de=readdir(dir)) {
66                 char *fname;
67                 struct stat st;
68
69                 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name)) {
70                         continue;
71                 }
72
73                 fname = talloc_asprintf(path, "%s/%s", path, de->d_name);
74                 if (stat(fname, &st) != 0) {
75                         continue;
76                 }
77                 if (S_ISDIR(st.st_mode)) {
78                         recursive_delete(fname);
79                         talloc_free(fname);
80                         continue;
81                 }
82                 if (unlink(fname) != 0) {
83                         DEBUG(0,("Unabled to delete '%s' - %s\n",
84                                  fname, strerror(errno)));
85                         smb_panic("unable to cleanup tmp files");
86                 }
87                 talloc_free(fname);
88         }
89         closedir(dir);
90 }
91
92 /*
93   cleanup temporary files. This is the new alternative to
94   TDB_CLEAR_IF_FIRST. Unfortunately TDB_CLEAR_IF_FIRST is not
95   efficient on unix systems due to the lack of scaling of the byte
96   range locking system. So instead of putting the burden on tdb to
97   cleanup tmp files, this function deletes them.
98 */
99 static void cleanup_tmp_files(struct loadparm_context *lp_ctx)
100 {
101         char *path;
102         TALLOC_CTX *mem_ctx = talloc_new(NULL);
103
104         path = smbd_tmp_path(mem_ctx, lp_ctx, NULL);
105
106         recursive_delete(path);
107         talloc_free(mem_ctx);
108 }
109
110 static void sig_hup(int sig)
111 {
112         debug_schedule_reopen_logs();
113 }
114
115 static void sig_term(int sig)
116 {
117 #if HAVE_GETPGRP
118         if (getpgrp() == getpid()) {
119                 /*
120                  * We're the process group leader, send
121                  * SIGTERM to our process group.
122                  */
123                 DEBUG(0,("SIGTERM: killing children\n"));
124                 kill(-getpgrp(), SIGTERM);
125         }
126 #endif
127         DEBUG(0,("Exiting pid %d on SIGTERM\n", (int)getpid()));
128         exit(127);
129 }
130
131 static void sigterm_signal_handler(struct tevent_context *ev,
132                                 struct tevent_signal *se,
133                                 int signum, int count, void *siginfo,
134                                 void *private_data)
135 {
136         struct server_state *state = talloc_get_type_abort(
137                 private_data, struct server_state);
138
139         DEBUG(10,("Process %s got SIGTERM\n", state->binary_name));
140         TALLOC_FREE(state);
141         sig_term(SIGTERM);
142 }
143
144 /*
145   setup signal masks
146 */
147 static void setup_signals(void)
148 {
149         /* we are never interested in SIGPIPE */
150         BlockSignals(true,SIGPIPE);
151
152 #if defined(SIGFPE)
153         /* we are never interested in SIGFPE */
154         BlockSignals(true,SIGFPE);
155 #endif
156
157         /* We are no longer interested in USR1 */
158         BlockSignals(true, SIGUSR1);
159
160 #if defined(SIGUSR2)
161         /* We are no longer interested in USR2 */
162         BlockSignals(true,SIGUSR2);
163 #endif
164
165         /* POSIX demands that signals are inherited. If the invoking process has
166          * these signals masked, we will have problems,
167          * as we won't receive them. */
168         BlockSignals(false, SIGHUP);
169         BlockSignals(false, SIGTERM);
170
171         CatchSignal(SIGHUP, sig_hup);
172         CatchSignal(SIGTERM, sig_term);
173 }
174
175 /*
176   handle io on stdin
177 */
178 static void server_stdin_handler(struct tevent_context *event_ctx,
179                                 struct tevent_fd *fde,
180                                 uint16_t flags,
181                                 void *private_data)
182 {
183         struct server_state *state = talloc_get_type_abort(
184                 private_data, struct server_state);
185         uint8_t c;
186         if (read(0, &c, 1) == 0) {
187                 DEBUG(0,("%s: EOF on stdin - PID %d terminating\n",
188                                 state->binary_name, (int)getpid()));
189 #if HAVE_GETPGRP
190                 if (getpgrp() == getpid()) {
191                         DEBUG(0,("Sending SIGTERM from pid %d\n",
192                                 (int)getpid()));
193                         kill(-getpgrp(), SIGTERM);
194                 }
195 #endif
196                 TALLOC_FREE(state);
197                 exit(0);
198         }
199 }
200
201 /*
202   die if the user selected maximum runtime is exceeded
203 */
204 _NORETURN_ static void max_runtime_handler(struct tevent_context *ev,
205                                            struct tevent_timer *te,
206                                            struct timeval t, void *private_data)
207 {
208         struct server_state *state = talloc_get_type_abort(
209                 private_data, struct server_state);
210         DEBUG(0,("%s: maximum runtime exceeded - "
211                 "terminating PID %d at %llu, current ts: %llu\n",
212                  state->binary_name,
213                 (int)getpid(),
214                 (unsigned long long)t.tv_sec,
215                 (unsigned long long)time(NULL)));
216         TALLOC_FREE(state);
217         exit(0);
218 }
219
220 /*
221   pre-open the key databases. This saves a lot of time in child
222   processes
223  */
224 static void prime_ldb_databases(struct tevent_context *event_ctx)
225 {
226         TALLOC_CTX *db_context;
227         db_context = talloc_new(event_ctx);
228
229         samdb_connect(db_context,
230                         event_ctx,
231                         cmdline_lp_ctx,
232                         system_session(cmdline_lp_ctx),
233                         0);
234         privilege_connect(db_context, cmdline_lp_ctx);
235
236         /* we deliberately leave these open, which allows them to be
237          * re-used in ldb_wrap_connect() */
238 }
239
240
241 /*
242   called when a fatal condition occurs in a child task
243  */
244 static NTSTATUS samba_terminate(struct irpc_message *msg,
245                                 struct samba_terminate *r)
246 {
247         struct server_state *state = talloc_get_type(msg->private_data,
248                                         struct server_state);
249         DBG_ERR("samba_terminate of %s %d: %s\n",
250                 state->binary_name, (int)getpid(), r->in.reason);
251         TALLOC_FREE(state);
252         exit(1);
253 }
254
255 /*
256   setup messaging for the top level samba (parent) task
257  */
258 static NTSTATUS setup_parent_messaging(struct server_state *state,
259                                        struct loadparm_context *lp_ctx)
260 {
261         struct imessaging_context *msg;
262         NTSTATUS status;
263
264         msg = imessaging_init(state->event_ctx,
265                               lp_ctx,
266                               cluster_id(0, SAMBA_PARENT_TASKID),
267                               state->event_ctx);
268         NT_STATUS_HAVE_NO_MEMORY(msg);
269
270         status = irpc_add_name(msg, "samba");
271         if (!NT_STATUS_IS_OK(status)) {
272                 return status;
273         }
274
275         status = IRPC_REGISTER(msg, irpc, SAMBA_TERMINATE,
276                                samba_terminate, state);
277
278         return status;
279 }
280
281
282 /*
283   show build info
284  */
285 static void show_build(void)
286 {
287 #define CONFIG_OPTION(n) { #n, dyn_ ## n }
288         struct {
289                 const char *name;
290                 const char *value;
291         } config_options[] = {
292                 CONFIG_OPTION(BINDIR),
293                 CONFIG_OPTION(SBINDIR),
294                 CONFIG_OPTION(CONFIGFILE),
295                 CONFIG_OPTION(NCALRPCDIR),
296                 CONFIG_OPTION(LOGFILEBASE),
297                 CONFIG_OPTION(LMHOSTSFILE),
298                 CONFIG_OPTION(DATADIR),
299                 CONFIG_OPTION(MODULESDIR),
300                 CONFIG_OPTION(LOCKDIR),
301                 CONFIG_OPTION(STATEDIR),
302                 CONFIG_OPTION(CACHEDIR),
303                 CONFIG_OPTION(PIDDIR),
304                 CONFIG_OPTION(PRIVATE_DIR),
305                 CONFIG_OPTION(CODEPAGEDIR),
306                 CONFIG_OPTION(SETUPDIR),
307                 CONFIG_OPTION(WINBINDD_SOCKET_DIR),
308                 CONFIG_OPTION(NTP_SIGND_SOCKET_DIR),
309                 { NULL, NULL}
310         };
311         int i;
312
313         printf("Samba version: %s\n", SAMBA_VERSION_STRING);
314         printf("Build environment:\n");
315 #ifdef BUILD_SYSTEM
316         printf("   Build host:  %s\n", BUILD_SYSTEM);
317 #endif
318
319         printf("Paths:\n");
320         for (i=0; config_options[i].name; i++) {
321                 printf("   %s: %s\n",
322                         config_options[i].name,
323                         config_options[i].value);
324         }
325
326         exit(0);
327 }
328
329 static int event_ctx_destructor(struct tevent_context *event_ctx)
330 {
331         imessaging_dgm_unref_ev(event_ctx);
332         return 0;
333 }
334
335 /*
336  main server.
337 */
338 static int binary_smbd_main(const char *binary_name,
339                                 int argc,
340                                 const char *argv[])
341 {
342         bool opt_daemon = false;
343         bool opt_interactive = false;
344         bool opt_no_process_group = false;
345         int opt;
346         poptContext pc;
347 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
348         STATIC_service_MODULES_PROTO;
349         init_module_fn static_init[] = { STATIC_service_MODULES };
350         init_module_fn *shared_init;
351         uint16_t stdin_event_flags;
352         NTSTATUS status;
353         const char *model = "standard";
354         int max_runtime = 0;
355         struct stat st;
356         enum {
357                 OPT_DAEMON = 1000,
358                 OPT_INTERACTIVE,
359                 OPT_PROCESS_MODEL,
360                 OPT_SHOW_BUILD,
361                 OPT_NO_PROCESS_GROUP,
362         };
363         struct poptOption long_options[] = {
364                 POPT_AUTOHELP
365                 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON,
366                  "Become a daemon (default)", NULL },
367                 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE,
368                  "Run interactive (not a daemon)", NULL},
369                 {"model", 'M', POPT_ARG_STRING, NULL, OPT_PROCESS_MODEL,
370                  "Select process model", "MODEL"},
371                 {"maximum-runtime",0, POPT_ARG_INT, &max_runtime, 0,
372                  "set maximum runtime of the server process, "
373                         "till autotermination", "seconds"},
374                 {"show-build", 'b', POPT_ARG_NONE, NULL, OPT_SHOW_BUILD,
375                         "show build info", NULL },
376                 {"no-process-group", '\0', POPT_ARG_NONE, NULL,
377                   OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
378                 POPT_COMMON_SAMBA
379                 POPT_COMMON_VERSION
380                 { NULL }
381         };
382         struct server_state *state = NULL;
383         struct tevent_signal *se = NULL;
384
385         pc = poptGetContext(binary_name, argc, argv, long_options, 0);
386         while((opt = poptGetNextOpt(pc)) != -1) {
387                 switch(opt) {
388                 case OPT_DAEMON:
389                         opt_daemon = true;
390                         break;
391                 case OPT_INTERACTIVE:
392                         opt_interactive = true;
393                         break;
394                 case OPT_PROCESS_MODEL:
395                         model = poptGetOptArg(pc);
396                         break;
397                 case OPT_SHOW_BUILD:
398                         show_build();
399                         break;
400                 case OPT_NO_PROCESS_GROUP:
401                         opt_no_process_group = true;
402                         break;
403                 default:
404                         fprintf(stderr, "\nInvalid option %s: %s\n\n",
405                                   poptBadOption(pc, 0), poptStrerror(opt));
406                         poptPrintUsage(pc, stderr, 0);
407                         return 1;
408                 }
409         }
410
411         if (opt_daemon && opt_interactive) {
412                 fprintf(stderr,"\nERROR: "
413                         "Option -i|--interactive is "
414                         "not allowed together with -D|--daemon\n\n");
415                 poptPrintUsage(pc, stderr, 0);
416                 return 1;
417         } else if (!opt_interactive) {
418                 /* default is --daemon */
419                 opt_daemon = true;
420         }
421
422         poptFreeContext(pc);
423
424         talloc_enable_null_tracking();
425
426         setup_logging(binary_name, opt_interactive?DEBUG_STDOUT:DEBUG_FILE);
427         setup_signals();
428
429         /* we want total control over the permissions on created files,
430            so set our umask to 0 */
431         umask(0);
432
433         DEBUG(0,("%s version %s started.\n",
434                 binary_name,
435                 SAMBA_VERSION_STRING));
436         DEBUGADD(0,("Copyright Andrew Tridgell and the Samba Team"
437                 " 1992-2017\n"));
438
439         if (sizeof(uint16_t) < 2 ||
440                         sizeof(uint32_t) < 4 ||
441                         sizeof(uint64_t) < 8) {
442                 DEBUG(0,("ERROR: Samba is not configured correctly "
443                         "for the word size on your machine\n"));
444                 DEBUGADD(0,("sizeof(uint16_t) = %u, sizeof(uint32_t) %u, "
445                         "sizeof(uint64_t) = %u\n",
446                         (unsigned int)sizeof(uint16_t),
447                         (unsigned int)sizeof(uint32_t),
448                         (unsigned int)sizeof(uint64_t)));
449                 return 1;
450         }
451
452         if (opt_daemon) {
453                 DEBUG(3,("Becoming a daemon.\n"));
454                 become_daemon(true, false, false);
455         }
456
457         /* Create the memory context to hang everything off. */
458         state = talloc_zero(NULL, struct server_state);
459         if (state == NULL) {
460                 exit_daemon("Samba cannot create server state", ENOMEM);
461         };
462         state->binary_name = binary_name;
463
464         cleanup_tmp_files(cmdline_lp_ctx);
465
466         if (!directory_exist(lpcfg_lock_directory(cmdline_lp_ctx))) {
467                 mkdir(lpcfg_lock_directory(cmdline_lp_ctx), 0755);
468         }
469
470         pidfile_create(lpcfg_pid_directory(cmdline_lp_ctx), binary_name);
471
472         if (lpcfg_server_role(cmdline_lp_ctx) == ROLE_ACTIVE_DIRECTORY_DC) {
473                 if (!open_schannel_session_store(state,
474                                 cmdline_lp_ctx)) {
475                         TALLOC_FREE(state);
476                         exit_daemon("Samba cannot open schannel store "
477                                 "for secured NETLOGON operations.", EACCES);
478                 }
479         }
480
481         /* make sure we won't go through nss_winbind */
482         if (!winbind_off()) {
483                 TALLOC_FREE(state);
484                 exit_daemon("Samba failed to disable recusive "
485                         "winbindd calls.", EACCES);
486         }
487
488         gensec_init(); /* FIXME: */
489
490         process_model_init(cmdline_lp_ctx);
491
492         shared_init = load_samba_modules(NULL, "service");
493
494         run_init_functions(NULL, static_init);
495         run_init_functions(NULL, shared_init);
496
497         talloc_free(shared_init);
498
499         /* the event context is the top level structure in smbd. Everything else
500            should hang off that */
501         state->event_ctx = s4_event_context_init(state);
502
503         if (state->event_ctx == NULL) {
504                 TALLOC_FREE(state);
505                 exit_daemon("Initializing event context failed", EACCES);
506         }
507
508         talloc_set_destructor(state->event_ctx, event_ctx_destructor);
509
510         if (opt_interactive) {
511                 /* terminate when stdin goes away */
512                 stdin_event_flags = TEVENT_FD_READ;
513         } else {
514                 /* stay alive forever */
515                 stdin_event_flags = 0;
516         }
517
518 #if HAVE_SETPGID
519         /*
520          * If we're interactive we want to set our own process group for
521          * signal management, unless --no-process-group specified.
522          */
523         if (opt_interactive && !opt_no_process_group)
524                 setpgid((pid_t)0, (pid_t)0);
525 #endif
526
527         /* catch EOF on stdin */
528 #ifdef SIGTTIN
529         signal(SIGTTIN, SIG_IGN);
530 #endif
531
532         if (fstat(0, &st) != 0) {
533                 TALLOC_FREE(state);
534                 exit_daemon("Samba failed to set standard input handler",
535                                 ENOTTY);
536         }
537
538         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
539                 struct tevent_fd *fde = tevent_add_fd(state->event_ctx,
540                                 state->event_ctx,
541                                 0,
542                                 stdin_event_flags,
543                                 server_stdin_handler,
544                                 state);
545                 if (fde == NULL) {
546                         TALLOC_FREE(state);
547                         exit_daemon("Initializing stdin failed", ENOMEM);
548                 }
549         }
550
551         if (max_runtime) {
552                 struct tevent_timer *te;
553                 DEBUG(0,("%s PID %d was called with maxruntime %d - "
554                         "current ts %llu\n",
555                         binary_name, (int)getpid(),
556                         max_runtime, (unsigned long long) time(NULL)));
557                 te = tevent_add_timer(state->event_ctx, state->event_ctx,
558                                  timeval_current_ofs(max_runtime, 0),
559                                  max_runtime_handler,
560                                  state);
561                 if (te == NULL) {
562                         TALLOC_FREE(state);
563                         exit_daemon("Maxruntime handler failed", ENOMEM);
564                 }
565         }
566
567         se = tevent_add_signal(state->event_ctx,
568                                 state->event_ctx,
569                                 SIGTERM,
570                                 0,
571                                 sigterm_signal_handler,
572                                 state);
573         if (se == NULL) {
574                 TALLOC_FREE(state);
575                 exit_daemon("Initialize SIGTERM handler failed", ENOMEM);
576         }
577
578         if (lpcfg_server_role(cmdline_lp_ctx) != ROLE_ACTIVE_DIRECTORY_DC
579             && !lpcfg_parm_bool(cmdline_lp_ctx, NULL,
580                         "server role check", "inhibit", false)
581             && !str_list_check_ci(lpcfg_server_services(cmdline_lp_ctx), "smb")
582             && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
583                         "remote")
584             && !str_list_check_ci(lpcfg_dcerpc_endpoint_servers(cmdline_lp_ctx),
585                         "mapiproxy")) {
586                 DEBUG(0, ("At this time the 'samba' binary should only be used "
587                         "for either:\n"));
588                 DEBUGADD(0, ("'server role = active directory domain "
589                         "controller' or to access the ntvfs file server "
590                         "with 'server services = +smb' or the rpc proxy "
591                         "with 'dcerpc endpoint servers = remote'\n"));
592                 DEBUGADD(0, ("You should start smbd/nmbd/winbindd instead for "
593                         "domain member and standalone file server tasks\n"));
594                 exit_daemon("Samba detected misconfigured 'server role' "
595                         "and exited. Check logs for details", EINVAL);
596         };
597
598         prime_ldb_databases(state->event_ctx);
599
600         status = setup_parent_messaging(state, cmdline_lp_ctx);
601         if (!NT_STATUS_IS_OK(status)) {
602                 TALLOC_FREE(state);
603                 exit_daemon("Samba failed to setup parent messaging",
604                         NT_STATUS_V(status));
605         }
606
607         DEBUG(0,("%s: using '%s' process model\n", binary_name, model));
608
609         status = server_service_startup(state->event_ctx, cmdline_lp_ctx, model,
610                                         lpcfg_server_services(cmdline_lp_ctx));
611         if (!NT_STATUS_IS_OK(status)) {
612                 TALLOC_FREE(state);
613                 exit_daemon("Samba failed to start services",
614                         NT_STATUS_V(status));
615         }
616
617         if (opt_daemon) {
618                 daemon_ready("samba");
619         }
620
621         /* wait for events - this is where smbd sits for most of its
622            life */
623         tevent_loop_wait(state->event_ctx);
624
625         /* as everything hangs off this state->event context, freeing state
626            will initiate a clean shutdown of all services */
627         TALLOC_FREE(state);
628
629         return 0;
630 }
631
632 int main(int argc, const char *argv[])
633 {
634         return binary_smbd_main("samba", argc, argv);
635 }