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