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