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