s3:rpc_server: Reinitialize dcesrv_context in external mdssd daemon
[samba.git] / source3 / smbd / server.c
1 /*
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Andrew Tridgell                1992-1998
5    Copyright (C) Martin Pool                    2002
6    Copyright (C) Jelmer Vernooij                2002-2003
7    Copyright (C) Volker Lendecke                1993-2007
8    Copyright (C) Jeremy Allison                 1993-2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
27 #include "popt_common.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "registry/reg_init_full.h"
31 #include "libcli/auth/schannel.h"
32 #include "secrets.h"
33 #include "../lib/util/memcache.h"
34 #include "ctdbd_conn.h"
35 #include "util_cluster.h"
36 #include "printing/queue_process.h"
37 #include "rpc_server/rpc_service_setup.h"
38 #include "rpc_server/rpc_config.h"
39 #include "passdb.h"
40 #include "auth.h"
41 #include "messages.h"
42 #include "messages_ctdb.h"
43 #include "smbprofile.h"
44 #include "lib/id_cache.h"
45 #include "lib/param/param.h"
46 #include "lib/background.h"
47 #include "../lib/util/pidfile.h"
48 #include "lib/smbd_shim.h"
49 #include "scavenger.h"
50 #include "locking/leases_db.h"
51 #include "smbd/notifyd/notifyd.h"
52 #include "smbd/smbd_cleanupd.h"
53 #include "lib/util/sys_rw.h"
54 #include "cleanupdb.h"
55 #include "g_lock.h"
56 #include "rpc_server/epmd.h"
57 #include "rpc_server/lsasd.h"
58 #include "rpc_server/fssd.h"
59 #include "rpc_server/mdssd.h"
60
61 #ifdef CLUSTER_SUPPORT
62 #include "ctdb_protocol.h"
63 #endif
64
65 struct smbd_open_socket;
66 struct smbd_child_pid;
67
68 struct smbd_parent_context {
69         bool interactive;
70
71         struct tevent_context *ev_ctx;
72         struct messaging_context *msg_ctx;
73         struct dcesrv_context *dce_ctx;
74
75         /* the list of listening sockets */
76         struct smbd_open_socket *sockets;
77
78         /* the list of current child processes */
79         struct smbd_child_pid *children;
80         size_t num_children;
81
82         struct server_id cleanupd;
83         struct server_id notifyd;
84
85         struct tevent_timer *cleanup_te;
86 };
87
88 struct smbd_open_socket {
89         struct smbd_open_socket *prev, *next;
90         struct smbd_parent_context *parent;
91         int fd;
92         struct tevent_fd *fde;
93 };
94
95 struct smbd_child_pid {
96         struct smbd_child_pid *prev, *next;
97         pid_t pid;
98 };
99
100 /*******************************************************************
101  What to do when smb.conf is updated.
102  ********************************************************************/
103
104 static void smbd_parent_conf_updated(struct messaging_context *msg,
105                                      void *private_data,
106                                      uint32_t msg_type,
107                                      struct server_id server_id,
108                                      DATA_BLOB *data)
109 {
110         struct tevent_context *ev_ctx =
111                 talloc_get_type_abort(private_data, struct tevent_context);
112         bool ok;
113
114         DEBUG(10,("smbd_parent_conf_updated: Got message saying smb.conf was "
115                   "updated. Reloading.\n"));
116         change_to_root_user();
117         reload_services(NULL, NULL, false);
118         printing_subsystem_update(ev_ctx, msg, false);
119
120         ok = reinit_guest_session_info(NULL);
121         if (!ok) {
122                 DBG_ERR("Failed to reinit guest info\n");
123         }
124 }
125
126 /*******************************************************************
127  Delete a statcache entry.
128  ********************************************************************/
129
130 static void smb_stat_cache_delete(struct messaging_context *msg,
131                                   void *private_data,
132                                   uint32_t msg_tnype,
133                                   struct server_id server_id,
134                                   DATA_BLOB *data)
135 {
136         const char *name = (const char *)data->data;
137         DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
138         stat_cache_delete(name);
139 }
140
141 /****************************************************************************
142   Send a SIGTERM to our process group.
143 *****************************************************************************/
144
145 static void  killkids(void)
146 {
147         if(am_parent) kill(0,SIGTERM);
148 }
149
150 static void msg_exit_server(struct messaging_context *msg,
151                             void *private_data,
152                             uint32_t msg_type,
153                             struct server_id server_id,
154                             DATA_BLOB *data)
155 {
156         DEBUG(3, ("got a SHUTDOWN message\n"));
157         exit_server_cleanly(NULL);
158 }
159
160 #ifdef DEVELOPER
161 static void msg_inject_fault(struct messaging_context *msg,
162                              void *private_data,
163                              uint32_t msg_type,
164                              struct server_id src,
165                              DATA_BLOB *data)
166 {
167         int sig;
168         struct server_id_buf tmp;
169
170         if (data->length != sizeof(sig)) {
171                 DEBUG(0, ("Process %s sent bogus signal injection request\n",
172                           server_id_str_buf(src, &tmp)));
173                 return;
174         }
175
176         sig = *(int *)data->data;
177         if (sig == -1) {
178                 exit_server("internal error injected");
179                 return;
180         }
181
182 #ifdef HAVE_STRSIGNAL
183         DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
184                   server_id_str_buf(src, &tmp), sig, strsignal(sig)));
185 #else
186         DEBUG(0, ("Process %s requested injection of signal %d\n",
187                   server_id_str_buf(src, &tmp), sig));
188 #endif
189
190         kill(getpid(), sig);
191 }
192 #endif /* DEVELOPER */
193
194 #if defined(DEVELOPER) || defined(ENABLE_SELFTEST)
195 /*
196  * Sleep for the specified number of seconds.
197  */
198 static void msg_sleep(struct messaging_context *msg,
199                       void *private_data,
200                       uint32_t msg_type,
201                       struct server_id src,
202                       DATA_BLOB *data)
203 {
204         unsigned int seconds;
205         struct server_id_buf tmp;
206
207         if (data->length != sizeof(seconds)) {
208                 DBG_ERR("Process %s sent bogus sleep request\n",
209                         server_id_str_buf(src, &tmp));
210                 return;
211         }
212
213         seconds = *(unsigned int *)data->data;
214         DBG_ERR("Process %s request a sleep of %u seconds\n",
215                 server_id_str_buf(src, &tmp),
216                 seconds);
217         sleep(seconds);
218         DBG_ERR("Restarting after %u second sleep requested by process %s\n",
219                 seconds,
220                 server_id_str_buf(src, &tmp));
221 }
222 #endif /* DEVELOPER */
223
224 static NTSTATUS messaging_send_to_children(struct messaging_context *msg_ctx,
225                                            uint32_t msg_type, DATA_BLOB* data)
226 {
227         NTSTATUS status;
228         struct smbd_parent_context *parent = am_parent;
229         struct smbd_child_pid *child;
230
231         if (parent == NULL) {
232                 return NT_STATUS_INTERNAL_ERROR;
233         }
234
235         for (child = parent->children; child != NULL; child = child->next) {
236                 status = messaging_send(parent->msg_ctx,
237                                         pid_to_procid(child->pid),
238                                         msg_type, data);
239                 if (!NT_STATUS_IS_OK(status)) {
240                         DBG_DEBUG("messaging_send(%d) failed: %s\n",
241                                   (int)child->pid, nt_errstr(status));
242                 }
243         }
244         return NT_STATUS_OK;
245 }
246
247 static void smb_parent_send_to_children(struct messaging_context *ctx,
248                                         void* data,
249                                         uint32_t msg_type,
250                                         struct server_id srv_id,
251                                         DATA_BLOB* msg_data)
252 {
253         messaging_send_to_children(ctx, msg_type, msg_data);
254 }
255
256 /*
257  * Parent smbd process sets its own debug level first and then
258  * sends a message to all the smbd children to adjust their debug
259  * level to that of the parent.
260  */
261
262 static void smbd_msg_debug(struct messaging_context *msg_ctx,
263                            void *private_data,
264                            uint32_t msg_type,
265                            struct server_id server_id,
266                            DATA_BLOB *data)
267 {
268         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
269
270         messaging_send_to_children(msg_ctx, MSG_DEBUG, data);
271 }
272
273 static void smbd_parent_id_cache_kill(struct messaging_context *msg_ctx,
274                                       void *private_data,
275                                       uint32_t msg_type,
276                                       struct server_id server_id,
277                                       DATA_BLOB* data)
278 {
279         const char *msg = (data && data->data)
280                 ? (const char *)data->data : "<NULL>";
281         struct id_cache_ref id;
282
283         if (!id_cache_ref_parse(msg, &id)) {
284                 DEBUG(0, ("Invalid ?ID: %s\n", msg));
285                 return;
286         }
287
288         id_cache_delete_from_cache(&id);
289
290         messaging_send_to_children(msg_ctx, msg_type, data);
291 }
292
293 static void smbd_parent_id_cache_delete(struct messaging_context *ctx,
294                                         void* data,
295                                         uint32_t msg_type,
296                                         struct server_id srv_id,
297                                         DATA_BLOB* msg_data)
298 {
299         id_cache_delete_message(ctx, data, msg_type, srv_id, msg_data);
300
301         messaging_send_to_children(ctx, msg_type, msg_data);
302 }
303
304 static void add_child_pid(struct smbd_parent_context *parent,
305                           pid_t pid)
306 {
307         struct smbd_child_pid *child;
308
309         child = talloc_zero(parent, struct smbd_child_pid);
310         if (child == NULL) {
311                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
312                 return;
313         }
314         child->pid = pid;
315         DLIST_ADD(parent->children, child);
316         parent->num_children += 1;
317 }
318
319 static void smb_tell_num_children(struct messaging_context *ctx, void *data,
320                                   uint32_t msg_type, struct server_id srv_id,
321                                   DATA_BLOB *msg_data)
322 {
323         uint8_t buf[sizeof(uint32_t)];
324
325         if (am_parent) {
326                 SIVAL(buf, 0, am_parent->num_children);
327                 messaging_send_buf(ctx, srv_id, MSG_SMB_NUM_CHILDREN,
328                                    buf, sizeof(buf));
329         }
330 }
331
332 static void notifyd_stopped(struct tevent_req *req);
333
334 static struct tevent_req *notifyd_req(struct messaging_context *msg_ctx,
335                                       struct tevent_context *ev)
336 {
337         struct tevent_req *req;
338         sys_notify_watch_fn sys_notify_watch = NULL;
339         struct sys_notify_context *sys_notify_ctx = NULL;
340         struct ctdbd_connection *ctdbd_conn = NULL;
341
342         if (lp_kernel_change_notify()) {
343
344 #ifdef HAVE_INOTIFY
345                 if (lp_parm_bool(-1, "notify", "inotify", true)) {
346                         sys_notify_watch = inotify_watch;
347                 }
348 #endif
349
350 #ifdef HAVE_FAM
351                 if (lp_parm_bool(-1, "notify", "fam",
352                                  (sys_notify_watch == NULL))) {
353                         sys_notify_watch = fam_watch;
354                 }
355 #endif
356         }
357
358         if (sys_notify_watch != NULL) {
359                 sys_notify_ctx = sys_notify_context_create(msg_ctx, ev);
360                 if (sys_notify_ctx == NULL) {
361                         return NULL;
362                 }
363         }
364
365         if (lp_clustering()) {
366                 ctdbd_conn = messaging_ctdb_connection();
367         }
368
369         req = notifyd_send(msg_ctx, ev, msg_ctx, ctdbd_conn,
370                            sys_notify_watch, sys_notify_ctx);
371         if (req == NULL) {
372                 TALLOC_FREE(sys_notify_ctx);
373                 return NULL;
374         }
375         tevent_req_set_callback(req, notifyd_stopped, msg_ctx);
376
377         return req;
378 }
379
380 static void notifyd_stopped(struct tevent_req *req)
381 {
382         int ret;
383
384         ret = notifyd_recv(req);
385         TALLOC_FREE(req);
386         DEBUG(1, ("notifyd stopped: %s\n", strerror(ret)));
387 }
388
389 static void notifyd_sig_hup_handler(struct tevent_context *ev,
390                                     struct tevent_signal *se,
391                                     int signum,
392                                     int count,
393                                     void *siginfo,
394                                     void *pvt)
395 {
396         DBG_NOTICE("notifyd: Reloading services after SIGHUP\n");
397         reload_services(NULL, NULL, false);
398 }
399
400 static bool smbd_notifyd_init(struct messaging_context *msg, bool interactive,
401                               struct server_id *ppid)
402 {
403         struct tevent_context *ev = messaging_tevent_context(msg);
404         struct tevent_req *req;
405         pid_t pid;
406         NTSTATUS status;
407         bool ok;
408         struct tevent_signal *se;
409
410         if (interactive) {
411                 req = notifyd_req(msg, ev);
412                 return (req != NULL);
413         }
414
415         pid = fork();
416         if (pid == -1) {
417                 DEBUG(1, ("%s: fork failed: %s\n", __func__,
418                           strerror(errno)));
419                 return false;
420         }
421
422         if (pid != 0) {
423                 if (am_parent != NULL) {
424                         add_child_pid(am_parent, pid);
425                 }
426                 *ppid = pid_to_procid(pid);
427                 return true;
428         }
429
430         status = smbd_reinit_after_fork(msg, ev, true, "smbd-notifyd");
431         if (!NT_STATUS_IS_OK(status)) {
432                 DEBUG(1, ("%s: reinit_after_fork failed: %s\n",
433                           __func__, nt_errstr(status)));
434                 exit(1);
435         }
436
437         reopen_logs();
438
439         /* Set up sighup handler for notifyd */
440         se = tevent_add_signal(ev,
441                                ev,
442                                SIGHUP, 0,
443                                notifyd_sig_hup_handler,
444                                NULL);
445         if (!se) {
446                 DEBUG(0, ("failed to setup notifyd SIGHUP handler\n"));
447                 exit(1);
448         }
449
450         req = notifyd_req(msg, ev);
451         if (req == NULL) {
452                 exit(1);
453         }
454         tevent_req_set_callback(req, notifyd_stopped, msg);
455
456         /* Block those signals that we are not handling */
457         BlockSignals(True, SIGUSR1);
458
459         messaging_send(msg, pid_to_procid(getppid()), MSG_SMB_NOTIFY_STARTED,
460                        NULL);
461
462         ok = tevent_req_poll(req, ev);
463         if (!ok) {
464                 DBG_WARNING("tevent_req_poll returned %s\n", strerror(errno));
465                 exit(1);
466         }
467         exit(0);
468 }
469
470 static void notifyd_init_trigger(struct tevent_req *req);
471
472 struct notifyd_init_state {
473         bool ok;
474         struct tevent_context *ev;
475         struct messaging_context *msg;
476         struct server_id *ppid;
477 };
478
479 static struct tevent_req *notifyd_init_send(struct tevent_context *ev,
480                                             TALLOC_CTX *mem_ctx,
481                                             struct messaging_context *msg,
482                                             struct server_id *ppid)
483 {
484         struct tevent_req *req = NULL;
485         struct tevent_req *subreq = NULL;
486         struct notifyd_init_state *state = NULL;
487
488         req = tevent_req_create(mem_ctx, &state, struct notifyd_init_state);
489         if (req == NULL) {
490                 return NULL;
491         }
492
493         *state = (struct notifyd_init_state) {
494                 .msg = msg,
495                 .ev = ev,
496                 .ppid = ppid
497         };
498
499         subreq = tevent_wakeup_send(state, ev, tevent_timeval_current_ofs(1, 0));
500         if (tevent_req_nomem(subreq, req)) {
501                 return tevent_req_post(req, ev);
502         }
503
504         tevent_req_set_callback(subreq, notifyd_init_trigger, req);
505         return req;
506 }
507
508 static void notifyd_init_trigger(struct tevent_req *subreq)
509 {
510         struct tevent_req *req = tevent_req_callback_data(
511                 subreq, struct tevent_req);
512         struct notifyd_init_state *state = tevent_req_data(
513                 req, struct notifyd_init_state);
514         bool ok;
515
516         DBG_NOTICE("Triggering notifyd startup\n");
517
518         ok = tevent_wakeup_recv(subreq);
519         TALLOC_FREE(subreq);
520         if (!ok) {
521                 tevent_req_error(req, ENOMEM);
522                 return;
523         }
524
525         state->ok = smbd_notifyd_init(state->msg, false, state->ppid);
526         if (state->ok) {
527                 DBG_WARNING("notifyd restarted\n");
528                 tevent_req_done(req);
529                 return;
530         }
531
532         DBG_NOTICE("notifyd startup failed, rescheduling\n");
533
534         subreq = tevent_wakeup_send(state, state->ev,
535                                     tevent_timeval_current_ofs(1, 0));
536         if (tevent_req_nomem(subreq, req)) {
537                 DBG_ERR("scheduling notifyd restart failed, giving up\n");
538                 return;
539         }
540
541         tevent_req_set_callback(subreq, notifyd_init_trigger, req);
542         return;
543 }
544
545 static bool notifyd_init_recv(struct tevent_req *req)
546 {
547         struct notifyd_init_state *state = tevent_req_data(
548                 req, struct notifyd_init_state);
549
550         return state->ok;
551 }
552
553 static void notifyd_started(struct tevent_req *req)
554 {
555         bool ok;
556
557         ok = notifyd_init_recv(req);
558         TALLOC_FREE(req);
559         if (!ok) {
560                 DBG_ERR("Failed to restart notifyd, giving up\n");
561                 return;
562         }
563 }
564
565 static void cleanupd_stopped(struct tevent_req *req);
566
567 static bool cleanupd_init(struct messaging_context *msg, bool interactive,
568                           struct server_id *ppid)
569 {
570         struct tevent_context *ev = messaging_tevent_context(msg);
571         struct server_id parent_id = messaging_server_id(msg);
572         struct tevent_req *req;
573         pid_t pid;
574         NTSTATUS status;
575         ssize_t rwret;
576         int ret;
577         bool ok;
578         char c;
579         int up_pipe[2];
580
581         if (interactive) {
582                 req = smbd_cleanupd_send(msg, ev, msg, parent_id.pid);
583                 *ppid = messaging_server_id(msg);
584                 return (req != NULL);
585         }
586
587         ret = pipe(up_pipe);
588         if (ret == -1) {
589                 DBG_WARNING("pipe failed: %s\n", strerror(errno));
590                 return false;
591         }
592
593         pid = fork();
594         if (pid == -1) {
595                 DBG_WARNING("fork failed: %s\n", strerror(errno));
596                 close(up_pipe[0]);
597                 close(up_pipe[1]);
598                 return false;
599         }
600
601         if (pid != 0) {
602
603                 close(up_pipe[1]);
604                 rwret = sys_read(up_pipe[0], &c, 1);
605                 close(up_pipe[0]);
606
607                 if (rwret == -1) {
608                         DBG_WARNING("sys_read failed: %s\n", strerror(errno));
609                         return false;
610                 }
611                 if (rwret == 0) {
612                         DBG_WARNING("cleanupd could not start\n");
613                         return false;
614                 }
615                 if (c != 0) {
616                         DBG_WARNING("cleanupd returned %d\n", (int)c);
617                         return false;
618                 }
619
620                 DBG_DEBUG("Started cleanupd pid=%d\n", (int)pid);
621
622                 if (am_parent != NULL) {
623                         add_child_pid(am_parent, pid);
624                 }
625
626                 *ppid = pid_to_procid(pid);
627                 return true;
628         }
629
630         close(up_pipe[0]);
631
632         status = smbd_reinit_after_fork(msg, ev, true, "cleanupd");
633         if (!NT_STATUS_IS_OK(status)) {
634                 DBG_WARNING("reinit_after_fork failed: %s\n",
635                             nt_errstr(status));
636                 c = 1;
637                 sys_write(up_pipe[1], &c, 1);
638
639                 exit(1);
640         }
641
642         req = smbd_cleanupd_send(msg, ev, msg, parent_id.pid);
643         if (req == NULL) {
644                 DBG_WARNING("smbd_cleanupd_send failed\n");
645                 c = 2;
646                 sys_write(up_pipe[1], &c, 1);
647
648                 exit(1);
649         }
650
651         tevent_req_set_callback(req, cleanupd_stopped, msg);
652
653         c = 0;
654         rwret = sys_write(up_pipe[1], &c, 1);
655         close(up_pipe[1]);
656
657         if (rwret == -1) {
658                 DBG_WARNING("sys_write failed: %s\n", strerror(errno));
659                 exit(1);
660         }
661         if (rwret != 1) {
662                 DBG_WARNING("sys_write could not write result\n");
663                 exit(1);
664         }
665
666         ok = tevent_req_poll(req, ev);
667         if (!ok) {
668                 DBG_WARNING("tevent_req_poll returned %s\n", strerror(errno));
669         }
670         exit(0);
671 }
672
673 static void cleanupd_stopped(struct tevent_req *req)
674 {
675         NTSTATUS status;
676
677         status = smbd_cleanupd_recv(req);
678         DBG_WARNING("cleanupd stopped: %s\n", nt_errstr(status));
679 }
680
681 static void cleanupd_init_trigger(struct tevent_req *req);
682
683 struct cleanup_init_state {
684         bool ok;
685         struct tevent_context *ev;
686         struct messaging_context *msg;
687         struct server_id *ppid;
688 };
689
690 static struct tevent_req *cleanupd_init_send(struct tevent_context *ev,
691                                              TALLOC_CTX *mem_ctx,
692                                              struct messaging_context *msg,
693                                              struct server_id *ppid)
694 {
695         struct tevent_req *req = NULL;
696         struct tevent_req *subreq = NULL;
697         struct cleanup_init_state *state = NULL;
698
699         req = tevent_req_create(mem_ctx, &state, struct cleanup_init_state);
700         if (req == NULL) {
701                 return NULL;
702         }
703
704         *state = (struct cleanup_init_state) {
705                 .msg = msg,
706                 .ev = ev,
707                 .ppid = ppid
708         };
709
710         subreq = tevent_wakeup_send(state, ev, tevent_timeval_current_ofs(0, 0));
711         if (tevent_req_nomem(subreq, req)) {
712                 return tevent_req_post(req, ev);
713         }
714
715         tevent_req_set_callback(subreq, cleanupd_init_trigger, req);
716         return req;
717 }
718
719 static void cleanupd_init_trigger(struct tevent_req *subreq)
720 {
721         struct tevent_req *req = tevent_req_callback_data(
722                 subreq, struct tevent_req);
723         struct cleanup_init_state *state = tevent_req_data(
724                 req, struct cleanup_init_state);
725         bool ok;
726
727         DBG_NOTICE("Triggering cleanupd startup\n");
728
729         ok = tevent_wakeup_recv(subreq);
730         TALLOC_FREE(subreq);
731         if (!ok) {
732                 tevent_req_error(req, ENOMEM);
733                 return;
734         }
735
736         state->ok = cleanupd_init(state->msg, false, state->ppid);
737         if (state->ok) {
738                 DBG_WARNING("cleanupd restarted\n");
739                 tevent_req_done(req);
740                 return;
741         }
742
743         DBG_NOTICE("cleanupd startup failed, rescheduling\n");
744
745         subreq = tevent_wakeup_send(state, state->ev,
746                                     tevent_timeval_current_ofs(1, 0));
747         if (tevent_req_nomem(subreq, req)) {
748                 DBG_ERR("scheduling cleanupd restart failed, giving up\n");
749                 return;
750         }
751
752         tevent_req_set_callback(subreq, cleanupd_init_trigger, req);
753         return;
754 }
755
756 static bool cleanupd_init_recv(struct tevent_req *req)
757 {
758         struct cleanup_init_state *state = tevent_req_data(
759                 req, struct cleanup_init_state);
760
761         return state->ok;
762 }
763
764 static void cleanupd_started(struct tevent_req *req)
765 {
766         bool ok;
767         NTSTATUS status;
768         struct smbd_parent_context *parent = tevent_req_callback_data(
769                 req, struct smbd_parent_context);
770
771         ok = cleanupd_init_recv(req);
772         TALLOC_FREE(req);
773         if (!ok) {
774                 DBG_ERR("Failed to restart cleanupd, giving up\n");
775                 return;
776         }
777
778         status = messaging_send(parent->msg_ctx,
779                                 parent->cleanupd,
780                                 MSG_SMB_NOTIFY_CLEANUP,
781                                 &data_blob_null);
782         if (!NT_STATUS_IS_OK(status)) {
783                 DBG_ERR("messaging_send returned %s\n",
784                         nt_errstr(status));
785         }
786 }
787
788 static void remove_child_pid(struct smbd_parent_context *parent,
789                              pid_t pid,
790                              bool unclean_shutdown)
791 {
792         struct smbd_child_pid *child;
793         NTSTATUS status;
794         bool ok;
795
796         for (child = parent->children; child != NULL; child = child->next) {
797                 if (child->pid == pid) {
798                         struct smbd_child_pid *tmp = child;
799                         DLIST_REMOVE(parent->children, child);
800                         TALLOC_FREE(tmp);
801                         parent->num_children -= 1;
802                         break;
803                 }
804         }
805
806         if (child == NULL) {
807                 /* not all forked child processes are added to the children list */
808                 DEBUG(2, ("Could not find child %d -- ignoring\n", (int)pid));
809                 return;
810         }
811
812         if (pid == procid_to_pid(&parent->cleanupd)) {
813                 struct tevent_req *req;
814
815                 server_id_set_disconnected(&parent->cleanupd);
816
817                 DBG_WARNING("Restarting cleanupd\n");
818                 req = cleanupd_init_send(messaging_tevent_context(parent->msg_ctx),
819                                          parent,
820                                          parent->msg_ctx,
821                                          &parent->cleanupd);
822                 if (req == NULL) {
823                         DBG_ERR("Failed to restart cleanupd\n");
824                         return;
825                 }
826                 tevent_req_set_callback(req, cleanupd_started, parent);
827                 return;
828         }
829
830         if (pid == procid_to_pid(&parent->notifyd)) {
831                 struct tevent_req *req;
832                 struct tevent_context *ev = messaging_tevent_context(
833                         parent->msg_ctx);
834
835                 server_id_set_disconnected(&parent->notifyd);
836
837                 DBG_WARNING("Restarting notifyd\n");
838                 req = notifyd_init_send(ev,
839                                         parent,
840                                         parent->msg_ctx,
841                                         &parent->notifyd);
842                 if (req == NULL) {
843                         DBG_ERR("Failed to restart notifyd\n");
844                         return;
845                 }
846                 tevent_req_set_callback(req, notifyd_started, parent);
847                 return;
848         }
849
850         ok = cleanupdb_store_child(pid, unclean_shutdown);
851         if (!ok) {
852                 DBG_ERR("cleanupdb_store_child failed\n");
853                 return;
854         }
855
856         if (!server_id_is_disconnected(&parent->cleanupd)) {
857                 status = messaging_send(parent->msg_ctx,
858                                         parent->cleanupd,
859                                         MSG_SMB_NOTIFY_CLEANUP,
860                                         &data_blob_null);
861                 if (!NT_STATUS_IS_OK(status)) {
862                         DBG_ERR("messaging_send returned %s\n",
863                                 nt_errstr(status));
864                 }
865         }
866 }
867
868 /****************************************************************************
869  Have we reached the process limit ?
870 ****************************************************************************/
871
872 static bool allowable_number_of_smbd_processes(struct smbd_parent_context *parent)
873 {
874         int max_processes = lp_max_smbd_processes();
875
876         if (!max_processes)
877                 return True;
878
879         return parent->num_children < max_processes;
880 }
881
882 static void smbd_sig_chld_handler(struct tevent_context *ev,
883                                   struct tevent_signal *se,
884                                   int signum,
885                                   int count,
886                                   void *siginfo,
887                                   void *private_data)
888 {
889         pid_t pid;
890         int status;
891         struct smbd_parent_context *parent =
892                 talloc_get_type_abort(private_data,
893                 struct smbd_parent_context);
894
895         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
896                 bool unclean_shutdown = False;
897
898                 /* If the child terminated normally, assume
899                    it was an unclean shutdown unless the
900                    status is 0
901                 */
902                 if (WIFEXITED(status)) {
903                         unclean_shutdown = WEXITSTATUS(status);
904                 }
905                 /* If the child terminated due to a signal
906                    we always assume it was unclean.
907                 */
908                 if (WIFSIGNALED(status)) {
909                         unclean_shutdown = True;
910                 }
911                 remove_child_pid(parent, pid, unclean_shutdown);
912         }
913 }
914
915 static void smbd_setup_sig_chld_handler(struct smbd_parent_context *parent)
916 {
917         struct tevent_signal *se;
918
919         se = tevent_add_signal(parent->ev_ctx,
920                                parent, /* mem_ctx */
921                                SIGCHLD, 0,
922                                smbd_sig_chld_handler,
923                                parent);
924         if (!se) {
925                 exit_server("failed to setup SIGCHLD handler");
926         }
927 }
928
929 static void smbd_open_socket_close_fn(struct tevent_context *ev,
930                                       struct tevent_fd *fde,
931                                       int fd,
932                                       void *private_data)
933 {
934         /* this might be the socket_wrapper swrap_close() */
935         close(fd);
936 }
937
938 static void smbd_accept_connection(struct tevent_context *ev,
939                                    struct tevent_fd *fde,
940                                    uint16_t flags,
941                                    void *private_data)
942 {
943         struct smbd_open_socket *s = talloc_get_type_abort(private_data,
944                                      struct smbd_open_socket);
945         struct messaging_context *msg_ctx = s->parent->msg_ctx;
946         struct dcesrv_context *dce_ctx = s->parent->dce_ctx;
947         struct sockaddr_storage addr;
948         socklen_t in_addrlen = sizeof(addr);
949         int fd;
950         pid_t pid = 0;
951
952         fd = accept(s->fd, (struct sockaddr *)(void *)&addr,&in_addrlen);
953         if (fd == -1 && errno == EINTR)
954                 return;
955
956         if (fd == -1) {
957                 DEBUG(0,("accept: %s\n",
958                          strerror(errno)));
959                 return;
960         }
961         smb_set_close_on_exec(fd);
962
963         if (s->parent->interactive) {
964                 reinit_after_fork(msg_ctx, ev, true, NULL);
965                 smbd_process(ev, msg_ctx, dce_ctx, fd, true);
966                 exit_server_cleanly("end of interactive mode");
967                 return;
968         }
969
970         if (!allowable_number_of_smbd_processes(s->parent)) {
971                 close(fd);
972                 return;
973         }
974
975         pid = fork();
976         if (pid == 0) {
977                 NTSTATUS status = NT_STATUS_OK;
978
979                 /*
980                  * Can't use TALLOC_FREE here. Nulling out the argument to it
981                  * would overwrite memory we've just freed.
982                  */
983                 talloc_free(s->parent);
984                 s = NULL;
985
986                 /* Stop zombies, the parent explicitly handles
987                  * them, counting worker smbds. */
988                 CatchChild();
989
990                 status = smbd_reinit_after_fork(msg_ctx, ev, true, NULL);
991                 if (!NT_STATUS_IS_OK(status)) {
992                         if (NT_STATUS_EQUAL(status,
993                                             NT_STATUS_TOO_MANY_OPENED_FILES)) {
994                                 DEBUG(0,("child process cannot initialize "
995                                          "because too many files are open\n"));
996                                 goto exit;
997                         }
998                         if (lp_clustering() &&
999                             (NT_STATUS_EQUAL(
1000                                     status, NT_STATUS_INTERNAL_DB_ERROR) ||
1001                              NT_STATUS_EQUAL(
1002                                     status, NT_STATUS_CONNECTION_REFUSED))) {
1003                                 DEBUG(1, ("child process cannot initialize "
1004                                           "because connection to CTDB "
1005                                           "has failed: %s\n",
1006                                           nt_errstr(status)));
1007                                 goto exit;
1008                         }
1009
1010                         DEBUG(0,("reinit_after_fork() failed\n"));
1011                         smb_panic("reinit_after_fork() failed");
1012                 }
1013
1014                 smbd_process(ev, msg_ctx, dce_ctx, fd, false);
1015          exit:
1016                 exit_server_cleanly("end of child");
1017                 return;
1018         }
1019
1020         if (pid < 0) {
1021                 DEBUG(0,("smbd_accept_connection: fork() failed: %s\n",
1022                          strerror(errno)));
1023         }
1024
1025         /* The parent doesn't need this socket */
1026         close(fd);
1027
1028         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
1029                 Clear the closed fd info out of server_fd --
1030                 and more importantly, out of client_fd in
1031                 util_sock.c, to avoid a possible
1032                 getpeername failure if we reopen the logs
1033                 and use %I in the filename.
1034         */
1035
1036         if (pid != 0) {
1037                 add_child_pid(s->parent, pid);
1038         }
1039
1040         /* Force parent to check log size after
1041          * spawning child.  Fix from
1042          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
1043          * parent smbd will log to logserver.smb.  It
1044          * writes only two messages for each child
1045          * started/finished. But each child writes,
1046          * say, 50 messages also in logserver.smb,
1047          * beginning with the debug_count of the
1048          * parent, before the child opens its own log
1049          * file logserver.client. In a worst case
1050          * scenario the size of logserver.smb would be
1051          * checked after about 50*50=2500 messages
1052          * (ca. 100kb).
1053          * */
1054         force_check_log_size();
1055 }
1056
1057 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
1058                                  struct tevent_context *ev_ctx,
1059                                  const struct sockaddr_storage *ifss,
1060                                  uint16_t port)
1061 {
1062         struct smbd_open_socket *s;
1063
1064         s = talloc(parent, struct smbd_open_socket);
1065         if (!s) {
1066                 return false;
1067         }
1068
1069         s->parent = parent;
1070         s->fd = open_socket_in(SOCK_STREAM,
1071                                port,
1072                                parent->sockets == NULL ? 0 : 2,
1073                                ifss,
1074                                true);
1075         if (s->fd == -1) {
1076                 DEBUG(0,("smbd_open_one_socket: open_socket_in: "
1077                         "%s\n", strerror(errno)));
1078                 TALLOC_FREE(s);
1079                 /*
1080                  * We ignore an error here, as we've done before
1081                  */
1082                 return true;
1083         }
1084
1085         /* ready to listen */
1086         set_socket_options(s->fd, "SO_KEEPALIVE");
1087         set_socket_options(s->fd, lp_socket_options());
1088
1089         /* Set server socket to
1090          * non-blocking for the accept. */
1091         set_blocking(s->fd, False);
1092
1093         if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
1094                 DEBUG(0,("smbd_open_one_socket: listen: "
1095                         "%s\n", strerror(errno)));
1096                         close(s->fd);
1097                 TALLOC_FREE(s);
1098                 return false;
1099         }
1100
1101         s->fde = tevent_add_fd(ev_ctx,
1102                                s,
1103                                s->fd, TEVENT_FD_READ,
1104                                smbd_accept_connection,
1105                                s);
1106         if (!s->fde) {
1107                 DEBUG(0,("smbd_open_one_socket: "
1108                          "tevent_add_fd: %s\n",
1109                          strerror(errno)));
1110                 close(s->fd);
1111                 TALLOC_FREE(s);
1112                 return false;
1113         }
1114         tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
1115
1116         DLIST_ADD_END(parent->sockets, s);
1117
1118         return true;
1119 }
1120
1121 /****************************************************************************
1122  Open the socket communication.
1123 ****************************************************************************/
1124
1125 static bool open_sockets_smbd(struct smbd_parent_context *parent,
1126                               struct tevent_context *ev_ctx,
1127                               struct messaging_context *msg_ctx,
1128                               const char *smb_ports)
1129 {
1130         int num_interfaces = iface_count();
1131         int i,j;
1132         const char **ports;
1133         unsigned dns_port = 0;
1134
1135 #ifdef HAVE_ATEXIT
1136         atexit(killkids);
1137 #endif
1138
1139         /* Stop zombies */
1140         smbd_setup_sig_chld_handler(parent);
1141
1142         ports = lp_smb_ports();
1143
1144         /* use a reasonable default set of ports - listing on 445 and 139 */
1145         if (smb_ports) {
1146                 char **l;
1147                 l = str_list_make_v3(talloc_tos(), smb_ports, NULL);
1148                 ports = discard_const_p(const char *, l);
1149         }
1150
1151         for (j = 0; ports && ports[j]; j++) {
1152                 unsigned port = atoi(ports[j]);
1153
1154                 if (port == 0 || port > 0xffff) {
1155                         exit_server_cleanly("Invalid port in the config or on "
1156                                             "the commandline specified!");
1157                 }
1158         }
1159
1160         if (lp_interfaces() && lp_bind_interfaces_only()) {
1161                 /* We have been given an interfaces line, and been
1162                    told to only bind to those interfaces. Create a
1163                    socket per interface and bind to only these.
1164                 */
1165
1166                 /* Now open a listen socket for each of the
1167                    interfaces. */
1168                 for(i = 0; i < num_interfaces; i++) {
1169                         const struct sockaddr_storage *ifss =
1170                                         iface_n_sockaddr_storage(i);
1171                         if (ifss == NULL) {
1172                                 DEBUG(0,("open_sockets_smbd: "
1173                                         "interface %d has NULL IP address !\n",
1174                                         i));
1175                                 continue;
1176                         }
1177
1178                         for (j = 0; ports && ports[j]; j++) {
1179                                 unsigned port = atoi(ports[j]);
1180
1181                                 /* Keep the first port for mDNS service
1182                                  * registration.
1183                                  */
1184                                 if (dns_port == 0) {
1185                                         dns_port = port;
1186                                 }
1187
1188                                 if (!smbd_open_one_socket(parent,
1189                                                           ev_ctx,
1190                                                           ifss,
1191                                                           port)) {
1192                                         return false;
1193                                 }
1194                         }
1195                 }
1196         } else {
1197                 /* Just bind to 0.0.0.0 - accept connections
1198                    from anywhere. */
1199
1200                 const char *sock_addr;
1201                 char *sock_tok;
1202                 const char *sock_ptr;
1203
1204 #ifdef HAVE_IPV6
1205                 sock_addr = "::,0.0.0.0";
1206 #else
1207                 sock_addr = "0.0.0.0";
1208 #endif
1209
1210                 for (sock_ptr=sock_addr;
1211                      next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
1212                         for (j = 0; ports && ports[j]; j++) {
1213                                 struct sockaddr_storage ss;
1214                                 unsigned port = atoi(ports[j]);
1215
1216                                 /* Keep the first port for mDNS service
1217                                  * registration.
1218                                  */
1219                                 if (dns_port == 0) {
1220                                         dns_port = port;
1221                                 }
1222
1223                                 /* open an incoming socket */
1224                                 if (!interpret_string_addr(&ss, sock_tok,
1225                                                 AI_NUMERICHOST|AI_PASSIVE)) {
1226                                         continue;
1227                                 }
1228
1229                                 /*
1230                                  * If we fail to open any sockets
1231                                  * in this loop the parent-sockets == NULL
1232                                  * case below will prevent us from starting.
1233                                  */
1234
1235                                 (void)smbd_open_one_socket(parent,
1236                                                   ev_ctx,
1237                                                   &ss,
1238                                                   port);
1239                         }
1240                 }
1241         }
1242
1243         if (parent->sockets == NULL) {
1244                 DEBUG(0,("open_sockets_smbd: No "
1245                         "sockets available to bind to.\n"));
1246                 return false;
1247         }
1248
1249         /* Listen to messages */
1250
1251         messaging_register(msg_ctx, NULL, MSG_SHUTDOWN, msg_exit_server);
1252         messaging_register(msg_ctx, ev_ctx, MSG_SMB_CONF_UPDATED,
1253                            smbd_parent_conf_updated);
1254         messaging_register(msg_ctx, NULL, MSG_SMB_STAT_CACHE_DELETE,
1255                            smb_stat_cache_delete);
1256         messaging_register(msg_ctx, NULL, MSG_DEBUG, smbd_msg_debug);
1257         messaging_register(msg_ctx, NULL, MSG_SMB_FORCE_TDIS,
1258                            smb_parent_send_to_children);
1259         messaging_register(msg_ctx, NULL, MSG_SMB_FORCE_TDIS_DENIED,
1260                            smb_parent_send_to_children);
1261         messaging_register(msg_ctx, NULL, MSG_SMB_KILL_CLIENT_IP,
1262                            smb_parent_send_to_children);
1263         messaging_register(msg_ctx, NULL, MSG_SMB_TELL_NUM_CHILDREN,
1264                            smb_tell_num_children);
1265
1266         messaging_register(msg_ctx, NULL,
1267                            ID_CACHE_DELETE, smbd_parent_id_cache_delete);
1268         messaging_register(msg_ctx, NULL,
1269                            ID_CACHE_KILL, smbd_parent_id_cache_kill);
1270         messaging_register(msg_ctx, NULL, MSG_SMB_NOTIFY_STARTED,
1271                            smb_parent_send_to_children);
1272
1273 #ifdef DEVELOPER
1274         messaging_register(msg_ctx, NULL, MSG_SMB_INJECT_FAULT,
1275                            msg_inject_fault);
1276 #endif
1277
1278 #if defined(DEVELOPER) || defined(ENABLE_SELFTEST)
1279         messaging_register(msg_ctx, NULL, MSG_SMB_SLEEP, msg_sleep);
1280 #endif
1281
1282         if (lp_multicast_dns_register() && (dns_port != 0)) {
1283 #ifdef WITH_DNSSD_SUPPORT
1284                 smbd_setup_mdns_registration(ev_ctx,
1285                                              parent, dns_port);
1286 #endif
1287 #ifdef WITH_AVAHI_SUPPORT
1288                 void *avahi_conn;
1289
1290                 avahi_conn = avahi_start_register(ev_ctx,
1291                                                   ev_ctx,
1292                                                   dns_port);
1293                 if (avahi_conn == NULL) {
1294                         DEBUG(10, ("avahi_start_register failed\n"));
1295                 }
1296 #endif
1297         }
1298
1299         return true;
1300 }
1301
1302
1303 /*
1304   handle stdin becoming readable when we are in --foreground mode
1305  */
1306 static void smbd_stdin_handler(struct tevent_context *ev,
1307                                struct tevent_fd *fde,
1308                                uint16_t flags,
1309                                void *private_data)
1310 {
1311         char c;
1312         if (read(0, &c, 1) != 1) {
1313                 /* we have reached EOF on stdin, which means the
1314                    parent has exited. Shutdown the server */
1315                 exit_server_cleanly("EOF on stdin");
1316         }
1317 }
1318
1319 struct smbd_parent_tevent_trace_state {
1320         TALLOC_CTX *frame;
1321 };
1322
1323 static void smbd_parent_tevent_trace_callback(enum tevent_trace_point point,
1324                                               void *private_data)
1325 {
1326         struct smbd_parent_tevent_trace_state *state =
1327                 (struct smbd_parent_tevent_trace_state *)private_data;
1328
1329         switch (point) {
1330         case TEVENT_TRACE_BEFORE_WAIT:
1331                 break;
1332         case TEVENT_TRACE_AFTER_WAIT:
1333                 break;
1334         case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1335                 TALLOC_FREE(state->frame);
1336                 state->frame = talloc_stackframe();
1337                 break;
1338         case TEVENT_TRACE_AFTER_LOOP_ONCE:
1339                 TALLOC_FREE(state->frame);
1340                 break;
1341         }
1342
1343         errno = 0;
1344 }
1345
1346 static void smbd_parent_loop(struct tevent_context *ev_ctx,
1347                              struct smbd_parent_context *parent)
1348 {
1349         struct smbd_parent_tevent_trace_state trace_state = {
1350                 .frame = NULL,
1351         };
1352         int ret = 0;
1353
1354         tevent_set_trace_callback(ev_ctx, smbd_parent_tevent_trace_callback,
1355                                   &trace_state);
1356
1357         /* now accept incoming connections - forking a new process
1358            for each incoming connection */
1359         DEBUG(2,("waiting for connections\n"));
1360
1361         ret = tevent_loop_wait(ev_ctx);
1362         if (ret != 0) {
1363                 DEBUG(0, ("tevent_loop_wait failed: %d, %s, exiting\n",
1364                           ret, strerror(errno)));
1365         }
1366
1367         TALLOC_FREE(trace_state.frame);
1368
1369 /* NOTREACHED   return True; */
1370 }
1371
1372
1373 /****************************************************************************
1374  Initialise connect, service and file structs.
1375 ****************************************************************************/
1376
1377 static bool init_structs(void )
1378 {
1379         /*
1380          * Set the machine NETBIOS name if not already
1381          * set from the config file.
1382          */
1383
1384         if (!init_names())
1385                 return False;
1386
1387         if (!secrets_init())
1388                 return False;
1389
1390         return True;
1391 }
1392
1393 static void smbd_parent_sig_term_handler(struct tevent_context *ev,
1394                                          struct tevent_signal *se,
1395                                          int signum,
1396                                          int count,
1397                                          void *siginfo,
1398                                          void *private_data)
1399 {
1400         exit_server_cleanly("termination signal");
1401 }
1402
1403 static void smbd_parent_sig_hup_handler(struct tevent_context *ev,
1404                                         struct tevent_signal *se,
1405                                         int signum,
1406                                         int count,
1407                                         void *siginfo,
1408                                         void *private_data)
1409 {
1410         struct smbd_parent_context *parent =
1411                 talloc_get_type_abort(private_data,
1412                 struct smbd_parent_context);
1413
1414         change_to_root_user();
1415         DEBUG(1,("parent: Reloading services after SIGHUP\n"));
1416         reload_services(NULL, NULL, false);
1417
1418         printing_subsystem_update(parent->ev_ctx, parent->msg_ctx, true);
1419 }
1420
1421 struct smbd_claim_version_state {
1422         TALLOC_CTX *mem_ctx;
1423         char *version;
1424 };
1425
1426 static void smbd_claim_version_parser(struct server_id exclusive,
1427                                       size_t num_shared,
1428                                       struct server_id *shared,
1429                                       const uint8_t *data,
1430                                       size_t datalen,
1431                                       void *private_data)
1432 {
1433         struct smbd_claim_version_state *state = private_data;
1434
1435         if (datalen == 0) {
1436                 state->version = NULL;
1437                 return;
1438         }
1439         if (data[datalen-1] != '\0') {
1440                 DBG_WARNING("Invalid samba version\n");
1441                 dump_data(DBGLVL_WARNING, data, datalen);
1442                 state->version = NULL;
1443                 return;
1444         }
1445         state->version = talloc_strdup(state->mem_ctx, (const char *)data);
1446 }
1447
1448 static NTSTATUS smbd_claim_version(struct messaging_context *msg,
1449                                    const char *version)
1450 {
1451         const char *name = "samba_version_string";
1452         const TDB_DATA key = string_term_tdb_data(name);
1453         struct smbd_claim_version_state state;
1454         struct g_lock_ctx *ctx;
1455         NTSTATUS status;
1456
1457         ctx = g_lock_ctx_init(msg, msg);
1458         if (ctx == NULL) {
1459                 DBG_WARNING("g_lock_ctx_init failed\n");
1460                 return NT_STATUS_UNSUCCESSFUL;
1461         }
1462
1463         status = g_lock_lock(
1464                 ctx, key, G_LOCK_READ, (struct timeval) { .tv_sec = 60 });
1465         if (!NT_STATUS_IS_OK(status)) {
1466                 DBG_WARNING("g_lock_lock(G_LOCK_READ) failed: %s\n",
1467                             nt_errstr(status));
1468                 TALLOC_FREE(ctx);
1469                 return status;
1470         }
1471
1472         state = (struct smbd_claim_version_state) { .mem_ctx = ctx };
1473
1474         status = g_lock_dump(ctx, key, smbd_claim_version_parser, &state);
1475         if (!NT_STATUS_IS_OK(status) &&
1476             !NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1477                 DBG_ERR("Could not read samba_version_string\n");
1478                 g_lock_unlock(ctx, key);
1479                 TALLOC_FREE(ctx);
1480                 return status;
1481         }
1482
1483         if ((state.version != NULL) && (strcmp(version, state.version) == 0)) {
1484                 /*
1485                  * Leave the read lock for us around. Someone else already
1486                  * set the version correctly
1487                  */
1488                 TALLOC_FREE(ctx);
1489                 return NT_STATUS_OK;
1490         }
1491
1492         status = g_lock_lock(
1493                 ctx, key, G_LOCK_UPGRADE, (struct timeval) { .tv_sec = 60 });
1494         if (!NT_STATUS_IS_OK(status)) {
1495                 DBG_WARNING("g_lock_lock(G_LOCK_WRITE) failed: %s\n",
1496                             nt_errstr(status));
1497                 DBG_ERR("smbd %s already running, refusing to start "
1498                         "version %s\n", state.version, version);
1499                 TALLOC_FREE(ctx);
1500                 return NT_STATUS_SXS_VERSION_CONFLICT;
1501         }
1502
1503         status = g_lock_write_data(
1504                 ctx, key, (const uint8_t *)version, strlen(version)+1);
1505         if (!NT_STATUS_IS_OK(status)) {
1506                 DBG_WARNING("g_lock_write_data failed: %s\n",
1507                             nt_errstr(status));
1508                 TALLOC_FREE(ctx);
1509                 return status;
1510         }
1511
1512         status = g_lock_lock(
1513                 ctx, key, G_LOCK_DOWNGRADE, (struct timeval) { .tv_sec = 60 });
1514         if (!NT_STATUS_IS_OK(status)) {
1515                 DBG_WARNING("g_lock_lock(G_LOCK_READ) failed: %s\n",
1516                             nt_errstr(status));
1517                 TALLOC_FREE(ctx);
1518                 return status;
1519         }
1520
1521         /*
1522          * Leave "ctx" dangling so that g_lock.tdb keeps opened.
1523          */
1524         return NT_STATUS_OK;
1525 }
1526
1527 /****************************************************************************
1528  main program.
1529 ****************************************************************************/
1530
1531 /* Declare prototype for build_options() to avoid having to run it through
1532    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
1533    prototype generation system is too complicated. */
1534
1535 extern void build_options(bool screen);
1536
1537  int main(int argc,const char *argv[])
1538 {
1539         /* shall I run as a daemon */
1540         bool is_daemon = false;
1541         bool interactive = false;
1542         bool Fork = true;
1543         bool no_process_group = false;
1544         bool log_stdout = false;
1545         char *ports = NULL;
1546         char *profile_level = NULL;
1547         int opt;
1548         poptContext pc;
1549         bool print_build_options = False;
1550         struct server_id main_server_id = {0};
1551         enum {
1552                 OPT_DAEMON = 1000,
1553                 OPT_INTERACTIVE,
1554                 OPT_FORK,
1555                 OPT_NO_PROCESS_GROUP,
1556                 OPT_LOG_STDOUT
1557         };
1558         struct poptOption long_options[] = {
1559                 POPT_AUTOHELP
1560                 {
1561                         .longName   = "daemon",
1562                         .shortName  = 'D',
1563                         .argInfo    = POPT_ARG_NONE,
1564                         .arg        = NULL,
1565                         .val        = OPT_DAEMON,
1566                         .descrip    = "Become a daemon (default)" ,
1567                 },
1568                 {
1569                         .longName   = "interactive",
1570                         .shortName  = 'i',
1571                         .argInfo    = POPT_ARG_NONE,
1572                         .arg        = NULL,
1573                         .val        = OPT_INTERACTIVE,
1574                         .descrip    = "Run interactive (not a daemon) and log to stdout",
1575                 },
1576                 {
1577                         .longName   = "foreground",
1578                         .shortName  = 'F',
1579                         .argInfo    = POPT_ARG_NONE,
1580                         .arg        = NULL,
1581                         .val        = OPT_FORK,
1582                         .descrip    = "Run daemon in foreground (for daemontools, etc.)",
1583                 },
1584                 {
1585                         .longName   = "no-process-group",
1586                         .shortName  = '\0',
1587                         .argInfo    = POPT_ARG_NONE,
1588                         .arg        = NULL,
1589                         .val        = OPT_NO_PROCESS_GROUP,
1590                         .descrip    = "Don't create a new process group" ,
1591                 },
1592                 {
1593                         .longName   = "log-stdout",
1594                         .shortName  = 'S',
1595                         .argInfo    = POPT_ARG_NONE,
1596                         .arg        = NULL,
1597                         .val        = OPT_LOG_STDOUT,
1598                         .descrip    = "Log to stdout" ,
1599                 },
1600                 {
1601                         .longName   = "build-options",
1602                         .shortName  = 'b',
1603                         .argInfo    = POPT_ARG_NONE,
1604                         .arg        = NULL,
1605                         .val        = 'b',
1606                         .descrip    = "Print build options" ,
1607                 },
1608                 {
1609                         .longName   = "port",
1610                         .shortName  = 'p',
1611                         .argInfo    = POPT_ARG_STRING,
1612                         .arg        = &ports,
1613                         .val        = 0,
1614                         .descrip    = "Listen on the specified ports",
1615                 },
1616                 {
1617                         .longName   = "profiling-level",
1618                         .shortName  = 'P',
1619                         .argInfo    = POPT_ARG_STRING,
1620                         .arg        = &profile_level,
1621                         .val        = 0,
1622                         .descrip    = "Set profiling level","PROFILE_LEVEL",
1623                 },
1624                 POPT_COMMON_SAMBA
1625                 POPT_TABLEEND
1626         };
1627         struct smbd_parent_context *parent = NULL;
1628         TALLOC_CTX *frame;
1629         NTSTATUS status;
1630         struct tevent_context *ev_ctx;
1631         struct messaging_context *msg_ctx;
1632         struct dcesrv_context *dce_ctx = NULL;
1633         struct server_id server_id;
1634         struct tevent_signal *se;
1635         int profiling_level;
1636         char *np_dir = NULL;
1637         const struct loadparm_substitution *lp_sub =
1638                 loadparm_s3_global_substitution();
1639         static const struct smbd_shim smbd_shim_fns =
1640         {
1641                 .send_stat_cache_delete_message = smbd_send_stat_cache_delete_message,
1642                 .change_to_root_user = smbd_change_to_root_user,
1643                 .become_authenticated_pipe_user = smbd_become_authenticated_pipe_user,
1644                 .unbecome_authenticated_pipe_user = smbd_unbecome_authenticated_pipe_user,
1645
1646                 .contend_level2_oplocks_begin = smbd_contend_level2_oplocks_begin,
1647                 .contend_level2_oplocks_end = smbd_contend_level2_oplocks_end,
1648
1649                 .become_root = smbd_become_root,
1650                 .unbecome_root = smbd_unbecome_root,
1651
1652                 .exit_server = smbd_exit_server,
1653                 .exit_server_cleanly = smbd_exit_server_cleanly,
1654         };
1655
1656         /*
1657          * Do this before any other talloc operation
1658          */
1659         talloc_enable_null_tracking();
1660         frame = talloc_stackframe();
1661
1662         setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
1663
1664         smb_init_locale();
1665
1666         set_smbd_shim(&smbd_shim_fns);
1667
1668         smbd_init_globals();
1669
1670         TimeInit();
1671
1672 #ifdef HAVE_SET_AUTH_PARAMETERS
1673         set_auth_parameters(argc,argv);
1674 #endif
1675
1676         pc = poptGetContext("smbd", argc, argv, long_options, 0);
1677         while((opt = poptGetNextOpt(pc)) != -1) {
1678                 switch (opt)  {
1679                 case OPT_DAEMON:
1680                         is_daemon = true;
1681                         break;
1682                 case OPT_INTERACTIVE:
1683                         interactive = true;
1684                         break;
1685                 case OPT_FORK:
1686                         Fork = false;
1687                         break;
1688                 case OPT_NO_PROCESS_GROUP:
1689                         no_process_group = true;
1690                         break;
1691                 case OPT_LOG_STDOUT:
1692                         log_stdout = true;
1693                         break;
1694                 case 'b':
1695                         print_build_options = True;
1696                         break;
1697                 default:
1698                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1699                                   poptBadOption(pc, 0), poptStrerror(opt));
1700                         poptPrintUsage(pc, stderr, 0);
1701                         exit(1);
1702                 }
1703         }
1704         poptFreeContext(pc);
1705
1706         if (interactive) {
1707                 Fork = False;
1708                 log_stdout = True;
1709         }
1710
1711         if (log_stdout) {
1712                 setup_logging(argv[0], DEBUG_STDOUT);
1713         } else {
1714                 setup_logging(argv[0], DEBUG_FILE);
1715         }
1716
1717         if (print_build_options) {
1718                 build_options(True); /* Display output to screen as well as debug */
1719                 exit(0);
1720         }
1721
1722 #ifdef HAVE_SETLUID
1723         /* needed for SecureWare on SCO */
1724         setluid(0);
1725 #endif
1726
1727         set_remote_machine_name("smbd", False);
1728
1729         if (interactive && (DEBUGLEVEL >= 9)) {
1730                 talloc_enable_leak_report();
1731         }
1732
1733         if (log_stdout && Fork) {
1734                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1735                 exit(1);
1736         }
1737
1738         /*
1739          * We want to die early if we can't open /dev/urandom
1740          */
1741         generate_random_buffer(NULL, 0);
1742
1743         /* get initial effective uid and gid */
1744         sec_init();
1745
1746         /* make absolutely sure we run as root - to handle cases where people
1747            are crazy enough to have it setuid */
1748         gain_root_privilege();
1749         gain_root_group_privilege();
1750
1751         fault_setup();
1752         dump_core_setup("smbd", lp_logfile(talloc_tos(), lp_sub));
1753
1754         /* we are never interested in SIGPIPE */
1755         BlockSignals(True,SIGPIPE);
1756
1757 #if defined(SIGFPE)
1758         /* we are never interested in SIGFPE */
1759         BlockSignals(True,SIGFPE);
1760 #endif
1761
1762 #if defined(SIGUSR2)
1763         /* We are no longer interested in USR2 */
1764         BlockSignals(True,SIGUSR2);
1765 #endif
1766
1767         /* POSIX demands that signals are inherited. If the invoking process has
1768          * these signals masked, we will have problems, as we won't recieve them. */
1769         BlockSignals(False, SIGHUP);
1770         BlockSignals(False, SIGUSR1);
1771         BlockSignals(False, SIGTERM);
1772
1773         /* Ensure we leave no zombies until we
1774          * correctly set up child handling below. */
1775
1776         CatchChild();
1777
1778         /* we want total control over the permissions on created files,
1779            so set our umask to 0 */
1780         umask(0);
1781
1782         reopen_logs();
1783
1784         DEBUG(0,("smbd version %s started.\n", samba_version_string()));
1785         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1786
1787         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1788                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1789
1790         /* Output the build options to the debug log */ 
1791         build_options(False);
1792
1793         if (sizeof(uint16_t) < 2 || sizeof(uint32_t) < 4) {
1794                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1795                 exit(1);
1796         }
1797
1798         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1799                 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
1800                 exit(1);
1801         }
1802
1803         /*
1804          * This calls unshare(CLONE_FS); on linux
1805          * in order to check if the running kernel/container
1806          * environment supports it.
1807          */
1808         per_thread_cwd_check();
1809
1810         if (!cluster_probe_ok()) {
1811                 exit(1);
1812         }
1813
1814         /* Init the security context and global current_user */
1815         init_sec_ctx();
1816
1817         /*
1818          * Initialize the event context. The event context needs to be
1819          * initialized before the messaging context, cause the messaging
1820          * context holds an event context.
1821          */
1822         ev_ctx = global_event_context();
1823         if (ev_ctx == NULL) {
1824                 exit(1);
1825         }
1826
1827         /*
1828          * Init the messaging context
1829          * FIXME: This should only call messaging_init()
1830          */
1831         msg_ctx = global_messaging_context();
1832         if (msg_ctx == NULL) {
1833                 exit(1);
1834         }
1835
1836         dce_ctx = global_dcesrv_context();
1837         if (dce_ctx == NULL) {
1838                 exit(1);
1839         }
1840
1841         /*
1842          * Reloading of the printers will not work here as we don't have a
1843          * server info and rpc services set up. It will be called later.
1844          */
1845         if (!reload_services(NULL, NULL, false)) {
1846                 exit(1);
1847         }
1848
1849         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
1850             && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
1851                 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running smbd standalone. \n"));
1852                 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting smbd if required\n"));
1853                 exit(1);
1854         }
1855
1856         /* ...NOTE... Log files are working from this point! */
1857
1858         DEBUG(3,("loaded services\n"));
1859
1860         init_structs();
1861
1862         if (!profile_setup(msg_ctx, False)) {
1863                 DEBUG(0,("ERROR: failed to setup profiling\n"));
1864                 return -1;
1865         }
1866
1867         if (profile_level != NULL) {
1868                 profiling_level = atoi(profile_level);
1869         } else {
1870                 profiling_level = lp_smbd_profiling_level();
1871         }
1872         main_server_id = messaging_server_id(msg_ctx);
1873         set_profile_level(profiling_level, &main_server_id);
1874
1875         if (!is_daemon && !is_a_socket(0)) {
1876                 if (!interactive) {
1877                         DEBUG(3, ("Standard input is not a socket, "
1878                                   "assuming -D option\n"));
1879                 }
1880
1881                 /*
1882                  * Setting is_daemon here prevents us from eventually calling
1883                  * the open_sockets_inetd()
1884                  */
1885
1886                 is_daemon = True;
1887         }
1888
1889         if (is_daemon && !interactive) {
1890                 DEBUG(3, ("Becoming a daemon.\n"));
1891                 become_daemon(Fork, no_process_group, log_stdout);
1892         }
1893
1894 #ifdef HAVE_SETPGID
1895         /*
1896          * If we're interactive we want to set our own process group for
1897          * signal management.
1898          */
1899         if (interactive && !no_process_group)
1900                 setpgid( (pid_t)0, (pid_t)0);
1901 #endif
1902
1903         if (!directory_exist(lp_lock_directory()))
1904                 mkdir(lp_lock_directory(), 0755);
1905
1906         if (!directory_exist(lp_pid_directory()))
1907                 mkdir(lp_pid_directory(), 0755);
1908
1909         if (is_daemon)
1910                 pidfile_create(lp_pid_directory(), "smbd");
1911
1912         status = reinit_after_fork(msg_ctx, ev_ctx, false, NULL);
1913         if (!NT_STATUS_IS_OK(status)) {
1914                 exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
1915         }
1916
1917         if (!interactive) {
1918                 /*
1919                  * Do not initialize the parent-child-pipe before becoming a
1920                  * daemon: this is used to detect a died parent in the child
1921                  * process.
1922                  */
1923                 status = init_before_fork();
1924                 if (!NT_STATUS_IS_OK(status)) {
1925                         exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
1926                 }
1927         }
1928
1929         parent = talloc_zero(ev_ctx, struct smbd_parent_context);
1930         if (!parent) {
1931                 exit_server("talloc(struct smbd_parent_context) failed");
1932         }
1933         parent->interactive = interactive;
1934         parent->ev_ctx = ev_ctx;
1935         parent->msg_ctx = msg_ctx;
1936         parent->dce_ctx = dce_ctx;
1937         am_parent = parent;
1938
1939         se = tevent_add_signal(parent->ev_ctx,
1940                                parent,
1941                                SIGTERM, 0,
1942                                smbd_parent_sig_term_handler,
1943                                parent);
1944         if (!se) {
1945                 exit_server("failed to setup SIGTERM handler");
1946         }
1947         se = tevent_add_signal(parent->ev_ctx,
1948                                parent,
1949                                SIGHUP, 0,
1950                                smbd_parent_sig_hup_handler,
1951                                parent);
1952         if (!se) {
1953                 exit_server("failed to setup SIGHUP handler");
1954         }
1955
1956         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1957
1958         if (smbd_memcache() == NULL) {
1959                 exit_daemon("no memcache available", EACCES);
1960         }
1961
1962         memcache_set_global(smbd_memcache());
1963
1964         /* Initialise the password backed before the global_sam_sid
1965            to ensure that we fetch from ldap before we make a domain sid up */
1966
1967         if(!initialize_password_db(false, ev_ctx))
1968                 exit(1);
1969
1970         if (!secrets_init()) {
1971                 exit_daemon("smbd can not open secrets.tdb", EACCES);
1972         }
1973
1974         if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
1975                 struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_helpers());
1976                 if (!open_schannel_session_store(NULL, lp_ctx)) {
1977                         exit_daemon("ERROR: Samba cannot open schannel store for secured NETLOGON operations.", EACCES);
1978                 }
1979                 TALLOC_FREE(lp_ctx);
1980         }
1981
1982         if(!get_global_sam_sid()) {
1983                 exit_daemon("Samba cannot create a SAM SID", EACCES);
1984         }
1985
1986         server_id = messaging_server_id(msg_ctx);
1987         status = smbXsrv_version_global_init(&server_id);
1988         if (!NT_STATUS_IS_OK(status)) {
1989                 exit_daemon("Samba cannot init server context", EACCES);
1990         }
1991
1992         status = smbXsrv_client_global_init();
1993         if (!NT_STATUS_IS_OK(status)) {
1994                 exit_daemon("Samba cannot init clients context", EACCES);
1995         }
1996
1997         status = smbXsrv_session_global_init(msg_ctx);
1998         if (!NT_STATUS_IS_OK(status)) {
1999                 exit_daemon("Samba cannot init session context", EACCES);
2000         }
2001
2002         status = smbXsrv_tcon_global_init();
2003         if (!NT_STATUS_IS_OK(status)) {
2004                 exit_daemon("Samba cannot init tcon context", EACCES);
2005         }
2006
2007         if (!locking_init())
2008                 exit_daemon("Samba cannot init locking", EACCES);
2009
2010         if (!leases_db_init(false)) {
2011                 exit_daemon("Samba cannot init leases", EACCES);
2012         }
2013
2014         if (!smbd_notifyd_init(msg_ctx, interactive, &parent->notifyd)) {
2015                 exit_daemon("Samba cannot init notification", EACCES);
2016         }
2017
2018         if (!cleanupd_init(msg_ctx, interactive, &parent->cleanupd)) {
2019                 exit_daemon("Samba cannot init the cleanupd", EACCES);
2020         }
2021
2022         if (!messaging_parent_dgm_cleanup_init(msg_ctx)) {
2023                 exit(1);
2024         }
2025
2026         if (!smbd_scavenger_init(NULL, msg_ctx, ev_ctx)) {
2027                 exit_daemon("Samba cannot init scavenging", EACCES);
2028         }
2029
2030         if (!W_ERROR_IS_OK(registry_init_full()))
2031                 exit_daemon("Samba cannot init registry", EACCES);
2032
2033         /* Open the share_info.tdb here, so we don't have to open
2034            after the fork on every single connection.  This is a small
2035            performance improvment and reduces the total number of system
2036            fds used. */
2037         status = share_info_db_init();
2038         if (!NT_STATUS_IS_OK(status)) {
2039                 exit_daemon("ERROR: failed to load share info db.", EACCES);
2040         }
2041
2042         status = init_system_session_info(NULL);
2043         if (!NT_STATUS_IS_OK(status)) {
2044                 DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
2045                           nt_errstr(status)));
2046                 return -1;
2047         }
2048
2049         if (!init_guest_session_info(NULL)) {
2050                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
2051                 return -1;
2052         }
2053
2054         if (!file_init_global()) {
2055                 DEBUG(0, ("ERROR: file_init_global() failed\n"));
2056                 return -1;
2057         }
2058         status = smbXsrv_open_global_init();
2059         if (!NT_STATUS_IS_OK(status)) {
2060                 exit_daemon("Samba cannot init global open", map_errno_from_nt_status(status));
2061         }
2062
2063         if (lp_clustering() && !lp_allow_unsafe_cluster_upgrade()) {
2064                 status = smbd_claim_version(msg_ctx, samba_version_string());
2065                 if (!NT_STATUS_IS_OK(status)) {
2066                         DBG_ERR("Could not claim version: %s\n",
2067                                     nt_errstr(status));
2068                         return -1;
2069                 }
2070         }
2071
2072         /* This MUST be done before start_epmd() because otherwise
2073          * start_epmd() forks and races against dcesrv_ep_setup() to
2074          * call directory_create_or_exist() */
2075         if (!directory_create_or_exist(lp_ncalrpc_dir(), 0755)) {
2076                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
2077                           lp_ncalrpc_dir(), strerror(errno)));
2078                 return -1;
2079         }
2080
2081         np_dir = talloc_asprintf(talloc_tos(), "%s/np", lp_ncalrpc_dir());
2082         if (!np_dir) {
2083                 DEBUG(0, ("%s: Out of memory\n", __location__));
2084                 return -1;
2085         }
2086
2087         if (!directory_create_or_exist_strict(np_dir, geteuid(), 0700)) {
2088                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
2089                           np_dir, strerror(errno)));
2090                 return -1;
2091         }
2092
2093         status = dcesrv_init(ev_ctx, ev_ctx, msg_ctx, dce_ctx);
2094         if (!NT_STATUS_IS_OK(status)) {
2095                 DBG_ERR("Failed to setup RPC server: %s\n", nt_errstr(status));
2096                 exit_daemon("Samba cannot setup ep pipe", EACCES);
2097         }
2098
2099         if (is_daemon && !interactive) {
2100                 daemon_ready("smbd");
2101         }
2102
2103         /* only start other daemons if we are running as a daemon
2104          * -- bad things will happen if smbd is launched via inetd
2105          *  and we fork a copy of ourselves here */
2106         if (is_daemon && !interactive) {
2107
2108                 if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
2109                         start_epmd(ev_ctx, msg_ctx, dce_ctx);
2110                 }
2111
2112                 if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
2113                         start_lsasd(ev_ctx, msg_ctx);
2114                 }
2115
2116                 if (rpc_fss_daemon() == RPC_DAEMON_FORK) {
2117                         start_fssd(ev_ctx, msg_ctx, dce_ctx);
2118                 }
2119
2120                 if (!lp__disable_spoolss() &&
2121                     (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2122                         bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);
2123
2124                         if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
2125                                 exit_daemon("Samba failed to init printing subsystem", EACCES);
2126                         }
2127                 }
2128
2129 #ifdef WITH_SPOTLIGHT
2130                 if ((rpc_mdssvc_mode() == RPC_SERVICE_MODE_EXTERNAL) &&
2131                     (rpc_mdssd_daemon() == RPC_DAEMON_FORK)) {
2132                         start_mdssd(ev_ctx, msg_ctx, dce_ctx);
2133                 }
2134 #endif
2135         } else if (!lp__disable_spoolss() &&
2136                    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2137                 if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
2138                         exit(1);
2139                 }
2140         }
2141
2142         if (!is_daemon) {
2143                 int sock;
2144
2145                 /* inetd mode */
2146                 TALLOC_FREE(frame);
2147
2148                 /* Started from inetd. fd 0 is the socket. */
2149                 /* We will abort gracefully when the client or remote system
2150                    goes away */
2151                 sock = dup(0);
2152
2153                 /* close stdin, stdout (if not logging to it), but not stderr */
2154                 close_low_fds(true, !debug_get_output_is_stdout(), false);
2155
2156 #ifdef HAVE_ATEXIT
2157                 atexit(killkids);
2158 #endif
2159
2160                 /* Stop zombies */
2161                 smbd_setup_sig_chld_handler(parent);
2162
2163                 smbd_process(ev_ctx, msg_ctx, dce_ctx, sock, true);
2164
2165                 exit_server_cleanly(NULL);
2166                 return(0);
2167         }
2168
2169         if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
2170                 exit_server("open_sockets_smbd() failed");
2171
2172         /* do a printer update now that all messaging has been set up,
2173          * before we allow clients to start connecting */
2174         if (!lp__disable_spoolss() &&
2175             (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2176                 printing_subsystem_update(ev_ctx, msg_ctx, false);
2177         }
2178
2179         TALLOC_FREE(frame);
2180         /* make sure we always have a valid stackframe */
2181         frame = talloc_stackframe();
2182
2183         if (!Fork) {
2184                 /* if we are running in the foreground then look for
2185                    EOF on stdin, and exit if it happens. This allows
2186                    us to die if the parent process dies
2187                    Only do this on a pipe or socket, no other device.
2188                 */
2189                 struct stat st;
2190                 if (fstat(0, &st) != 0) {
2191                         return false;
2192                 }
2193                 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
2194                         tevent_add_fd(ev_ctx,
2195                                         parent,
2196                                         0,
2197                                         TEVENT_FD_READ,
2198                                         smbd_stdin_handler,
2199                                         NULL);
2200                 }
2201         }
2202
2203         smbd_parent_loop(ev_ctx, parent);
2204
2205         exit_server_cleanly(NULL);
2206         TALLOC_FREE(frame);
2207         return(0);
2208 }