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