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