s3: libsmb: Correctly do lifecycle management on cli->smb1.tcon and cli->smb2.tcon.
[Samba.git] / source3 / smbd / server.c
blob4883c4ec510b544b04be6a6a3af85e1a91a35fc6
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
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.
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.
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/>.
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 "serverid.h"
40 #include "passdb.h"
41 #include "auth.h"
42 #include "messages.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"
58 #ifdef CLUSTER_SUPPORT
59 #include "ctdb_protocol.h"
60 #endif
62 struct smbd_open_socket;
63 struct smbd_child_pid;
65 struct smbd_parent_context {
66 bool interactive;
68 struct tevent_context *ev_ctx;
69 struct messaging_context *msg_ctx;
71 /* the list of listening sockets */
72 struct smbd_open_socket *sockets;
74 /* the list of current child processes */
75 struct smbd_child_pid *children;
76 size_t num_children;
78 struct server_id cleanupd;
79 struct server_id notifyd;
81 struct tevent_timer *cleanup_te;
84 struct smbd_open_socket {
85 struct smbd_open_socket *prev, *next;
86 struct smbd_parent_context *parent;
87 int fd;
88 struct tevent_fd *fde;
91 struct smbd_child_pid {
92 struct smbd_child_pid *prev, *next;
93 pid_t pid;
96 extern void start_epmd(struct tevent_context *ev_ctx,
97 struct messaging_context *msg_ctx);
99 extern void start_lsasd(struct tevent_context *ev_ctx,
100 struct messaging_context *msg_ctx);
102 extern void start_fssd(struct tevent_context *ev_ctx,
103 struct messaging_context *msg_ctx);
105 extern void start_mdssd(struct tevent_context *ev_ctx,
106 struct messaging_context *msg_ctx);
108 /*******************************************************************
109 What to do when smb.conf is updated.
110 ********************************************************************/
112 static void smbd_parent_conf_updated(struct messaging_context *msg,
113 void *private_data,
114 uint32_t msg_type,
115 struct server_id server_id,
116 DATA_BLOB *data)
118 struct tevent_context *ev_ctx =
119 talloc_get_type_abort(private_data, struct tevent_context);
121 DEBUG(10,("smbd_parent_conf_updated: Got message saying smb.conf was "
122 "updated. Reloading.\n"));
123 change_to_root_user();
124 reload_services(NULL, NULL, false);
125 printing_subsystem_update(ev_ctx, msg, false);
128 /*******************************************************************
129 Delete a statcache entry.
130 ********************************************************************/
132 static void smb_stat_cache_delete(struct messaging_context *msg,
133 void *private_data,
134 uint32_t msg_tnype,
135 struct server_id server_id,
136 DATA_BLOB *data)
138 const char *name = (const char *)data->data;
139 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
140 stat_cache_delete(name);
143 /****************************************************************************
144 Send a SIGTERM to our process group.
145 *****************************************************************************/
147 static void killkids(void)
149 if(am_parent) kill(0,SIGTERM);
152 static void msg_exit_server(struct messaging_context *msg,
153 void *private_data,
154 uint32_t msg_type,
155 struct server_id server_id,
156 DATA_BLOB *data)
158 DEBUG(3, ("got a SHUTDOWN message\n"));
159 exit_server_cleanly(NULL);
162 #ifdef DEVELOPER
163 static void msg_inject_fault(struct messaging_context *msg,
164 void *private_data,
165 uint32_t msg_type,
166 struct server_id src,
167 DATA_BLOB *data)
169 int sig;
170 struct server_id_buf tmp;
172 if (data->length != sizeof(sig)) {
173 DEBUG(0, ("Process %s sent bogus signal injection request\n",
174 server_id_str_buf(src, &tmp)));
175 return;
178 sig = *(int *)data->data;
179 if (sig == -1) {
180 exit_server("internal error injected");
181 return;
184 #if HAVE_STRSIGNAL
185 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
186 server_id_str_buf(src, &tmp), sig, strsignal(sig)));
187 #else
188 DEBUG(0, ("Process %s requested injection of signal %d\n",
189 server_id_str_buf(src, &tmp), sig));
190 #endif
192 kill(getpid(), sig);
194 #endif /* DEVELOPER */
196 static NTSTATUS messaging_send_to_children(struct messaging_context *msg_ctx,
197 uint32_t msg_type, DATA_BLOB* data)
199 NTSTATUS status;
200 struct smbd_parent_context *parent = am_parent;
201 struct smbd_child_pid *child;
203 if (parent == NULL) {
204 return NT_STATUS_INTERNAL_ERROR;
207 for (child = parent->children; child != NULL; child = child->next) {
208 status = messaging_send(parent->msg_ctx,
209 pid_to_procid(child->pid),
210 msg_type, data);
211 if (!NT_STATUS_IS_OK(status)) {
212 DBG_DEBUG("messaging_send(%d) failed: %s\n",
213 (int)child->pid, nt_errstr(status));
216 return NT_STATUS_OK;
219 static void smb_parent_send_to_children(struct messaging_context *ctx,
220 void* data,
221 uint32_t msg_type,
222 struct server_id srv_id,
223 DATA_BLOB* msg_data)
225 messaging_send_to_children(ctx, msg_type, msg_data);
229 * Parent smbd process sets its own debug level first and then
230 * sends a message to all the smbd children to adjust their debug
231 * level to that of the parent.
234 static void smbd_msg_debug(struct messaging_context *msg_ctx,
235 void *private_data,
236 uint32_t msg_type,
237 struct server_id server_id,
238 DATA_BLOB *data)
240 debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
242 messaging_send_to_children(msg_ctx, MSG_DEBUG, data);
245 static void smbd_parent_id_cache_kill(struct messaging_context *msg_ctx,
246 void *private_data,
247 uint32_t msg_type,
248 struct server_id server_id,
249 DATA_BLOB* data)
251 const char *msg = (data && data->data)
252 ? (const char *)data->data : "<NULL>";
253 struct id_cache_ref id;
255 if (!id_cache_ref_parse(msg, &id)) {
256 DEBUG(0, ("Invalid ?ID: %s\n", msg));
257 return;
260 id_cache_delete_from_cache(&id);
262 messaging_send_to_children(msg_ctx, msg_type, data);
265 static void smbd_parent_id_cache_delete(struct messaging_context *ctx,
266 void* data,
267 uint32_t msg_type,
268 struct server_id srv_id,
269 DATA_BLOB* msg_data)
271 id_cache_delete_message(ctx, data, msg_type, srv_id, msg_data);
273 messaging_send_to_children(ctx, msg_type, msg_data);
276 #ifdef CLUSTER_SUPPORT
277 static int smbd_parent_ctdb_reconfigured(
278 uint32_t src_vnn, uint32_t dst_vnn, uint64_t dst_srvid,
279 const uint8_t *msg, size_t msglen, void *private_data)
281 struct messaging_context *msg_ctx = talloc_get_type_abort(
282 private_data, struct messaging_context);
284 DEBUG(10, ("Got %s message\n", (dst_srvid == CTDB_SRVID_RECONFIGURE)
285 ? "cluster reconfigure" : "SAMBA_NOTIFY"));
288 * Someone from the family died, validate our locks
291 if (am_parent) {
292 messaging_send_buf(msg_ctx, am_parent->cleanupd,
293 MSG_SMB_BRL_VALIDATE, NULL, 0);
296 return 0;
298 #endif
300 static void add_child_pid(struct smbd_parent_context *parent,
301 pid_t pid)
303 struct smbd_child_pid *child;
305 child = talloc_zero(parent, struct smbd_child_pid);
306 if (child == NULL) {
307 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
308 return;
310 child->pid = pid;
311 DLIST_ADD(parent->children, child);
312 parent->num_children += 1;
315 static void smb_tell_num_children(struct messaging_context *ctx, void *data,
316 uint32_t msg_type, struct server_id srv_id,
317 DATA_BLOB *msg_data)
319 uint8_t buf[sizeof(uint32_t)];
321 if (am_parent) {
322 SIVAL(buf, 0, am_parent->num_children);
323 messaging_send_buf(ctx, srv_id, MSG_SMB_NUM_CHILDREN,
324 buf, sizeof(buf));
328 static void notifyd_stopped(struct tevent_req *req);
330 static struct tevent_req *notifyd_req(struct messaging_context *msg_ctx,
331 struct tevent_context *ev)
333 struct tevent_req *req;
334 sys_notify_watch_fn sys_notify_watch = NULL;
335 struct sys_notify_context *sys_notify_ctx = NULL;
337 if (lp_kernel_change_notify()) {
339 #ifdef HAVE_INOTIFY
340 if (lp_parm_bool(-1, "notify", "inotify", true)) {
341 sys_notify_watch = inotify_watch;
343 #endif
345 #ifdef HAVE_FAM
346 if (lp_parm_bool(-1, "notify", "fam",
347 (sys_notify_watch == NULL))) {
348 sys_notify_watch = fam_watch;
350 #endif
353 if (sys_notify_watch != NULL) {
354 sys_notify_ctx = sys_notify_context_create(msg_ctx, ev);
355 if (sys_notify_ctx == NULL) {
356 return NULL;
360 req = notifyd_send(msg_ctx, ev, msg_ctx,
361 messaging_ctdbd_connection(),
362 sys_notify_watch, sys_notify_ctx);
363 if (req == NULL) {
364 TALLOC_FREE(sys_notify_ctx);
365 return NULL;
367 tevent_req_set_callback(req, notifyd_stopped, msg_ctx);
369 return req;
372 static void notifyd_stopped(struct tevent_req *req)
374 int ret;
376 ret = notifyd_recv(req);
377 TALLOC_FREE(req);
378 DEBUG(1, ("notifyd stopped: %s\n", strerror(ret)));
381 static bool smbd_notifyd_init(struct messaging_context *msg, bool interactive,
382 struct server_id *ppid)
384 struct tevent_context *ev = messaging_tevent_context(msg);
385 struct tevent_req *req;
386 pid_t pid;
387 NTSTATUS status;
389 if (interactive) {
390 req = notifyd_req(msg, ev);
391 return (req != NULL);
394 pid = fork();
395 if (pid == -1) {
396 DEBUG(1, ("%s: fork failed: %s\n", __func__,
397 strerror(errno)));
398 return false;
401 if (pid != 0) {
402 if (am_parent != 0) {
403 add_child_pid(am_parent, pid);
405 *ppid = pid_to_procid(pid);
406 return true;
409 status = smbd_reinit_after_fork(msg, ev, true, "smbd-notifyd");
410 if (!NT_STATUS_IS_OK(status)) {
411 DEBUG(1, ("%s: reinit_after_fork failed: %s\n",
412 __func__, nt_errstr(status)));
413 exit(1);
416 req = notifyd_req(msg, ev);
417 if (req == NULL) {
418 exit(1);
420 tevent_req_set_callback(req, notifyd_stopped, msg);
422 /* Block those signals that we are not handling */
423 BlockSignals(True, SIGHUP);
424 BlockSignals(True, SIGUSR1);
426 messaging_send(msg, pid_to_procid(getppid()), MSG_SMB_NOTIFY_STARTED,
427 NULL);
429 return tevent_req_poll(req, ev);
432 static void notifyd_init_trigger(struct tevent_req *req);
434 struct notifyd_init_state {
435 bool ok;
436 struct tevent_context *ev;
437 struct messaging_context *msg;
438 struct server_id *ppid;
441 static struct tevent_req *notifyd_init_send(struct tevent_context *ev,
442 TALLOC_CTX *mem_ctx,
443 struct messaging_context *msg,
444 struct server_id *ppid)
446 struct tevent_req *req = NULL;
447 struct tevent_req *subreq = NULL;
448 struct notifyd_init_state *state = NULL;
450 req = tevent_req_create(mem_ctx, &state, struct notifyd_init_state);
451 if (req == NULL) {
452 return NULL;
455 *state = (struct notifyd_init_state) {
456 .msg = msg,
457 .ev = ev,
458 .ppid = ppid
461 subreq = tevent_wakeup_send(state, ev, tevent_timeval_current_ofs(1, 0));
462 if (tevent_req_nomem(subreq, req)) {
463 return tevent_req_post(req, ev);
466 tevent_req_set_callback(subreq, notifyd_init_trigger, req);
467 return req;
470 static void notifyd_init_trigger(struct tevent_req *subreq)
472 struct tevent_req *req = tevent_req_callback_data(
473 subreq, struct tevent_req);
474 struct notifyd_init_state *state = tevent_req_data(
475 req, struct notifyd_init_state);
476 bool ok;
478 DBG_NOTICE("Triggering notifyd startup\n");
480 ok = tevent_wakeup_recv(subreq);
481 TALLOC_FREE(subreq);
482 if (!ok) {
483 tevent_req_error(req, ENOMEM);
484 return;
487 state->ok = smbd_notifyd_init(state->msg, false, state->ppid);
488 if (state->ok) {
489 DBG_WARNING("notifyd restarted\n");
490 tevent_req_done(req);
491 return;
494 DBG_NOTICE("notifyd startup failed, rescheduling\n");
496 subreq = tevent_wakeup_send(state, state->ev,
497 tevent_timeval_current_ofs(1, 0));
498 if (tevent_req_nomem(subreq, req)) {
499 DBG_ERR("scheduling notifyd restart failed, giving up\n");
500 return;
503 tevent_req_set_callback(subreq, notifyd_init_trigger, req);
504 return;
507 static bool notifyd_init_recv(struct tevent_req *req)
509 struct notifyd_init_state *state = tevent_req_data(
510 req, struct notifyd_init_state);
512 return state->ok;
515 static void notifyd_started(struct tevent_req *req)
517 bool ok;
519 ok = notifyd_init_recv(req);
520 TALLOC_FREE(req);
521 if (!ok) {
522 DBG_ERR("Failed to restart notifyd, giving up\n");
523 return;
527 static void cleanupd_stopped(struct tevent_req *req);
529 static bool cleanupd_init(struct messaging_context *msg, bool interactive,
530 struct server_id *ppid)
532 struct tevent_context *ev = messaging_tevent_context(msg);
533 struct server_id parent_id = messaging_server_id(msg);
534 struct tevent_req *req;
535 pid_t pid;
536 NTSTATUS status;
537 ssize_t rwret;
538 int ret;
539 bool ok;
540 char c;
541 int up_pipe[2];
543 if (interactive) {
544 req = smbd_cleanupd_send(msg, ev, msg, parent_id.pid);
545 *ppid = messaging_server_id(msg);
546 return (req != NULL);
549 ret = pipe(up_pipe);
550 if (ret == -1) {
551 DBG_WARNING("pipe failed: %s\n", strerror(errno));
552 return false;
555 pid = fork();
556 if (pid == -1) {
557 DBG_WARNING("fork failed: %s\n", strerror(errno));
558 close(up_pipe[0]);
559 close(up_pipe[1]);
560 return false;
563 if (pid != 0) {
565 close(up_pipe[1]);
566 rwret = sys_read(up_pipe[0], &c, 1);
567 close(up_pipe[0]);
569 if (rwret == -1) {
570 DBG_WARNING("sys_read failed: %s\n", strerror(errno));
571 return false;
573 if (rwret == 0) {
574 DBG_WARNING("cleanupd could not start\n");
575 return false;
577 if (c != 0) {
578 DBG_WARNING("cleanupd returned %d\n", (int)c);
579 return false;
582 DBG_DEBUG("Started cleanupd pid=%d\n", (int)pid);
584 if (am_parent != NULL) {
585 add_child_pid(am_parent, pid);
588 *ppid = pid_to_procid(pid);
589 return true;
592 close(up_pipe[0]);
594 status = smbd_reinit_after_fork(msg, ev, true, "cleanupd");
595 if (!NT_STATUS_IS_OK(status)) {
596 DBG_WARNING("reinit_after_fork failed: %s\n",
597 nt_errstr(status));
598 c = 1;
599 sys_write(up_pipe[1], &c, 1);
601 exit(1);
604 req = smbd_cleanupd_send(msg, ev, msg, parent_id.pid);
605 if (req == NULL) {
606 DBG_WARNING("smbd_cleanupd_send failed\n");
607 c = 2;
608 sys_write(up_pipe[1], &c, 1);
610 exit(1);
613 tevent_req_set_callback(req, cleanupd_stopped, msg);
615 c = 0;
616 rwret = sys_write(up_pipe[1], &c, 1);
617 close(up_pipe[1]);
619 if (rwret == -1) {
620 DBG_WARNING("sys_write failed: %s\n", strerror(errno));
621 exit(1);
623 if (rwret != 1) {
624 DBG_WARNING("sys_write could not write result\n");
625 exit(1);
628 ok = tevent_req_poll(req, ev);
629 if (!ok) {
630 DBG_WARNING("tevent_req_poll returned %s\n", strerror(errno));
632 exit(0);
635 static void cleanupd_stopped(struct tevent_req *req)
637 NTSTATUS status;
639 status = smbd_cleanupd_recv(req);
640 DBG_WARNING("cleanupd stopped: %s\n", nt_errstr(status));
643 static void cleanupd_init_trigger(struct tevent_req *req);
645 struct cleanup_init_state {
646 bool ok;
647 struct tevent_context *ev;
648 struct messaging_context *msg;
649 struct server_id *ppid;
652 static struct tevent_req *cleanupd_init_send(struct tevent_context *ev,
653 TALLOC_CTX *mem_ctx,
654 struct messaging_context *msg,
655 struct server_id *ppid)
657 struct tevent_req *req = NULL;
658 struct tevent_req *subreq = NULL;
659 struct cleanup_init_state *state = NULL;
661 req = tevent_req_create(mem_ctx, &state, struct cleanup_init_state);
662 if (req == NULL) {
663 return NULL;
666 *state = (struct cleanup_init_state) {
667 .msg = msg,
668 .ev = ev,
669 .ppid = ppid
672 subreq = tevent_wakeup_send(state, ev, tevent_timeval_current_ofs(0, 0));
673 if (tevent_req_nomem(subreq, req)) {
674 return tevent_req_post(req, ev);
677 tevent_req_set_callback(subreq, cleanupd_init_trigger, req);
678 return req;
681 static void cleanupd_init_trigger(struct tevent_req *subreq)
683 struct tevent_req *req = tevent_req_callback_data(
684 subreq, struct tevent_req);
685 struct cleanup_init_state *state = tevent_req_data(
686 req, struct cleanup_init_state);
687 bool ok;
689 DBG_NOTICE("Triggering cleanupd startup\n");
691 ok = tevent_wakeup_recv(subreq);
692 TALLOC_FREE(subreq);
693 if (!ok) {
694 tevent_req_error(req, ENOMEM);
695 return;
698 state->ok = cleanupd_init(state->msg, false, state->ppid);
699 if (state->ok) {
700 DBG_WARNING("cleanupd restarted\n");
701 tevent_req_done(req);
702 return;
705 DBG_NOTICE("cleanupd startup failed, rescheduling\n");
707 subreq = tevent_wakeup_send(state, state->ev,
708 tevent_timeval_current_ofs(1, 0));
709 if (tevent_req_nomem(subreq, req)) {
710 DBG_ERR("scheduling cleanupd restart failed, giving up\n");
711 return;
714 tevent_req_set_callback(subreq, cleanupd_init_trigger, req);
715 return;
718 static bool cleanupd_init_recv(struct tevent_req *req)
720 struct cleanup_init_state *state = tevent_req_data(
721 req, struct cleanup_init_state);
723 return state->ok;
727 at most every smbd:cleanuptime seconds (default 20), we scan the BRL
728 and locking database for entries to cleanup. As a side effect this
729 also cleans up dead entries in the connections database (due to the
730 traversal in message_send_all()
732 Using a timer for this prevents a flood of traversals when a large
733 number of clients disconnect at the same time (perhaps due to a
734 network outage).
737 static void cleanup_timeout_fn(struct tevent_context *event_ctx,
738 struct tevent_timer *te,
739 struct timeval now,
740 void *private_data)
742 struct smbd_parent_context *parent =
743 talloc_get_type_abort(private_data,
744 struct smbd_parent_context);
746 parent->cleanup_te = NULL;
748 messaging_send_buf(parent->msg_ctx, parent->cleanupd,
749 MSG_SMB_UNLOCK, NULL, 0);
752 static void cleanupd_started(struct tevent_req *req)
754 bool ok;
755 NTSTATUS status;
756 struct smbd_parent_context *parent = tevent_req_callback_data(
757 req, struct smbd_parent_context);
759 ok = cleanupd_init_recv(req);
760 TALLOC_FREE(req);
761 if (!ok) {
762 DBG_ERR("Failed to restart cleanupd, giving up\n");
763 return;
766 status = messaging_send(parent->msg_ctx,
767 parent->cleanupd,
768 MSG_SMB_NOTIFY_CLEANUP,
769 &data_blob_null);
770 if (!NT_STATUS_IS_OK(status)) {
771 DBG_ERR("messaging_send returned %s\n",
772 nt_errstr(status));
776 static void remove_child_pid(struct smbd_parent_context *parent,
777 pid_t pid,
778 bool unclean_shutdown)
780 struct smbd_child_pid *child;
781 NTSTATUS status;
782 bool ok;
784 for (child = parent->children; child != NULL; child = child->next) {
785 if (child->pid == pid) {
786 struct smbd_child_pid *tmp = child;
787 DLIST_REMOVE(parent->children, child);
788 TALLOC_FREE(tmp);
789 parent->num_children -= 1;
790 break;
794 if (child == NULL) {
795 /* not all forked child processes are added to the children list */
796 DEBUG(2, ("Could not find child %d -- ignoring\n", (int)pid));
797 return;
800 if (pid == procid_to_pid(&parent->cleanupd)) {
801 struct tevent_req *req;
803 server_id_set_disconnected(&parent->cleanupd);
805 DBG_WARNING("Restarting cleanupd\n");
806 req = cleanupd_init_send(messaging_tevent_context(parent->msg_ctx),
807 parent,
808 parent->msg_ctx,
809 &parent->cleanupd);
810 if (req == NULL) {
811 DBG_ERR("Failed to restart cleanupd\n");
812 return;
814 tevent_req_set_callback(req, cleanupd_started, parent);
815 return;
818 if (pid == procid_to_pid(&parent->notifyd)) {
819 struct tevent_req *req;
820 struct tevent_context *ev = messaging_tevent_context(
821 parent->msg_ctx);
823 server_id_set_disconnected(&parent->notifyd);
825 DBG_WARNING("Restarting notifyd\n");
826 req = notifyd_init_send(ev,
827 parent,
828 parent->msg_ctx,
829 &parent->notifyd);
830 if (req == NULL) {
831 DBG_ERR("Failed to restart notifyd\n");
832 return;
834 tevent_req_set_callback(req, notifyd_started, parent);
835 return;
838 ok = cleanupdb_store_child(pid, unclean_shutdown);
839 if (!ok) {
840 DBG_ERR("cleanupdb_store_child failed\n");
841 return;
844 if (!server_id_is_disconnected(&parent->cleanupd)) {
845 status = messaging_send(parent->msg_ctx,
846 parent->cleanupd,
847 MSG_SMB_NOTIFY_CLEANUP,
848 &data_blob_null);
849 if (!NT_STATUS_IS_OK(status)) {
850 DBG_ERR("messaging_send returned %s\n",
851 nt_errstr(status));
855 if (unclean_shutdown) {
856 /* a child terminated uncleanly so tickle all
857 processes to see if they can grab any of the
858 pending locks
860 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n",
861 (unsigned int)pid));
862 if (parent->cleanup_te == NULL) {
863 /* call the cleanup timer, but not too often */
864 int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
865 parent->cleanup_te = tevent_add_timer(parent->ev_ctx,
866 parent,
867 timeval_current_ofs(cleanup_time, 0),
868 cleanup_timeout_fn,
869 parent);
870 DEBUG(1,("Scheduled cleanup of brl and lock database after unclean shutdown\n"));
875 /****************************************************************************
876 Have we reached the process limit ?
877 ****************************************************************************/
879 static bool allowable_number_of_smbd_processes(struct smbd_parent_context *parent)
881 int max_processes = lp_max_smbd_processes();
883 if (!max_processes)
884 return True;
886 return parent->num_children < max_processes;
889 static void smbd_sig_chld_handler(struct tevent_context *ev,
890 struct tevent_signal *se,
891 int signum,
892 int count,
893 void *siginfo,
894 void *private_data)
896 pid_t pid;
897 int status;
898 struct smbd_parent_context *parent =
899 talloc_get_type_abort(private_data,
900 struct smbd_parent_context);
902 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
903 bool unclean_shutdown = False;
905 /* If the child terminated normally, assume
906 it was an unclean shutdown unless the
907 status is 0
909 if (WIFEXITED(status)) {
910 unclean_shutdown = WEXITSTATUS(status);
912 /* If the child terminated due to a signal
913 we always assume it was unclean.
915 if (WIFSIGNALED(status)) {
916 unclean_shutdown = True;
918 remove_child_pid(parent, pid, unclean_shutdown);
922 static void smbd_setup_sig_chld_handler(struct smbd_parent_context *parent)
924 struct tevent_signal *se;
926 se = tevent_add_signal(parent->ev_ctx,
927 parent, /* mem_ctx */
928 SIGCHLD, 0,
929 smbd_sig_chld_handler,
930 parent);
931 if (!se) {
932 exit_server("failed to setup SIGCHLD handler");
936 static void smbd_open_socket_close_fn(struct tevent_context *ev,
937 struct tevent_fd *fde,
938 int fd,
939 void *private_data)
941 /* this might be the socket_wrapper swrap_close() */
942 close(fd);
945 static void smbd_accept_connection(struct tevent_context *ev,
946 struct tevent_fd *fde,
947 uint16_t flags,
948 void *private_data)
950 struct smbd_open_socket *s = talloc_get_type_abort(private_data,
951 struct smbd_open_socket);
952 struct messaging_context *msg_ctx = s->parent->msg_ctx;
953 struct sockaddr_storage addr;
954 socklen_t in_addrlen = sizeof(addr);
955 int fd;
956 pid_t pid = 0;
958 fd = accept(s->fd, (struct sockaddr *)(void *)&addr,&in_addrlen);
959 if (fd == -1 && errno == EINTR)
960 return;
962 if (fd == -1) {
963 DEBUG(0,("accept: %s\n",
964 strerror(errno)));
965 return;
968 if (s->parent->interactive) {
969 reinit_after_fork(msg_ctx, ev, true, NULL);
970 smbd_process(ev, msg_ctx, fd, true);
971 exit_server_cleanly("end of interactive mode");
972 return;
975 if (!allowable_number_of_smbd_processes(s->parent)) {
976 close(fd);
977 return;
980 pid = fork();
981 if (pid == 0) {
982 NTSTATUS status = NT_STATUS_OK;
985 * Can't use TALLOC_FREE here. Nulling out the argument to it
986 * would overwrite memory we've just freed.
988 talloc_free(s->parent);
989 s = NULL;
991 /* Stop zombies, the parent explicitly handles
992 * them, counting worker smbds. */
993 CatchChild();
995 status = smbd_reinit_after_fork(msg_ctx, ev, true, NULL);
996 if (!NT_STATUS_IS_OK(status)) {
997 if (NT_STATUS_EQUAL(status,
998 NT_STATUS_TOO_MANY_OPENED_FILES)) {
999 DEBUG(0,("child process cannot initialize "
1000 "because too many files are open\n"));
1001 goto exit;
1003 if (lp_clustering() &&
1004 (NT_STATUS_EQUAL(
1005 status, NT_STATUS_INTERNAL_DB_ERROR) ||
1006 NT_STATUS_EQUAL(
1007 status, NT_STATUS_CONNECTION_REFUSED))) {
1008 DEBUG(1, ("child process cannot initialize "
1009 "because connection to CTDB "
1010 "has failed: %s\n",
1011 nt_errstr(status)));
1012 goto exit;
1015 DEBUG(0,("reinit_after_fork() failed\n"));
1016 smb_panic("reinit_after_fork() failed");
1019 smbd_process(ev, msg_ctx, fd, false);
1020 exit:
1021 exit_server_cleanly("end of child");
1022 return;
1025 if (pid < 0) {
1026 DEBUG(0,("smbd_accept_connection: fork() failed: %s\n",
1027 strerror(errno)));
1030 /* The parent doesn't need this socket */
1031 close(fd);
1033 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
1034 Clear the closed fd info out of server_fd --
1035 and more importantly, out of client_fd in
1036 util_sock.c, to avoid a possible
1037 getpeername failure if we reopen the logs
1038 and use %I in the filename.
1041 if (pid != 0) {
1042 add_child_pid(s->parent, pid);
1045 /* Force parent to check log size after
1046 * spawning child. Fix from
1047 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
1048 * parent smbd will log to logserver.smb. It
1049 * writes only two messages for each child
1050 * started/finished. But each child writes,
1051 * say, 50 messages also in logserver.smb,
1052 * begining with the debug_count of the
1053 * parent, before the child opens its own log
1054 * file logserver.client. In a worst case
1055 * scenario the size of logserver.smb would be
1056 * checked after about 50*50=2500 messages
1057 * (ca. 100kb).
1058 * */
1059 force_check_log_size();
1062 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
1063 struct tevent_context *ev_ctx,
1064 const struct sockaddr_storage *ifss,
1065 uint16_t port)
1067 struct smbd_open_socket *s;
1069 s = talloc(parent, struct smbd_open_socket);
1070 if (!s) {
1071 return false;
1074 s->parent = parent;
1075 s->fd = open_socket_in(SOCK_STREAM,
1076 port,
1077 parent->sockets == NULL ? 0 : 2,
1078 ifss,
1079 true);
1080 if (s->fd == -1) {
1081 DEBUG(0,("smbd_open_one_socket: open_socket_in: "
1082 "%s\n", strerror(errno)));
1083 TALLOC_FREE(s);
1085 * We ignore an error here, as we've done before
1087 return true;
1090 /* ready to listen */
1091 set_socket_options(s->fd, "SO_KEEPALIVE");
1092 set_socket_options(s->fd, lp_socket_options());
1094 /* Set server socket to
1095 * non-blocking for the accept. */
1096 set_blocking(s->fd, False);
1098 if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
1099 DEBUG(0,("smbd_open_one_socket: listen: "
1100 "%s\n", strerror(errno)));
1101 close(s->fd);
1102 TALLOC_FREE(s);
1103 return false;
1106 s->fde = tevent_add_fd(ev_ctx,
1108 s->fd, TEVENT_FD_READ,
1109 smbd_accept_connection,
1111 if (!s->fde) {
1112 DEBUG(0,("smbd_open_one_socket: "
1113 "tevent_add_fd: %s\n",
1114 strerror(errno)));
1115 close(s->fd);
1116 TALLOC_FREE(s);
1117 return false;
1119 tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
1121 DLIST_ADD_END(parent->sockets, s);
1123 return true;
1126 /****************************************************************************
1127 Open the socket communication.
1128 ****************************************************************************/
1130 static bool open_sockets_smbd(struct smbd_parent_context *parent,
1131 struct tevent_context *ev_ctx,
1132 struct messaging_context *msg_ctx,
1133 const char *smb_ports)
1135 int num_interfaces = iface_count();
1136 int i,j;
1137 const char **ports;
1138 unsigned dns_port = 0;
1140 #ifdef HAVE_ATEXIT
1141 atexit(killkids);
1142 #endif
1144 /* Stop zombies */
1145 smbd_setup_sig_chld_handler(parent);
1147 ports = lp_smb_ports();
1149 /* use a reasonable default set of ports - listing on 445 and 139 */
1150 if (smb_ports) {
1151 char **l;
1152 l = str_list_make_v3(talloc_tos(), smb_ports, NULL);
1153 ports = discard_const_p(const char *, l);
1156 for (j = 0; ports && ports[j]; j++) {
1157 unsigned port = atoi(ports[j]);
1159 if (port == 0 || port > 0xffff) {
1160 exit_server_cleanly("Invalid port in the config or on "
1161 "the commandline specified!");
1165 if (lp_interfaces() && lp_bind_interfaces_only()) {
1166 /* We have been given an interfaces line, and been
1167 told to only bind to those interfaces. Create a
1168 socket per interface and bind to only these.
1171 /* Now open a listen socket for each of the
1172 interfaces. */
1173 for(i = 0; i < num_interfaces; i++) {
1174 const struct sockaddr_storage *ifss =
1175 iface_n_sockaddr_storage(i);
1176 if (ifss == NULL) {
1177 DEBUG(0,("open_sockets_smbd: "
1178 "interface %d has NULL IP address !\n",
1179 i));
1180 continue;
1183 for (j = 0; ports && ports[j]; j++) {
1184 unsigned port = atoi(ports[j]);
1186 /* Keep the first port for mDNS service
1187 * registration.
1189 if (dns_port == 0) {
1190 dns_port = port;
1193 if (!smbd_open_one_socket(parent,
1194 ev_ctx,
1195 ifss,
1196 port)) {
1197 return false;
1201 } else {
1202 /* Just bind to 0.0.0.0 - accept connections
1203 from anywhere. */
1205 const char *sock_addr;
1206 char *sock_tok;
1207 const char *sock_ptr;
1209 #if HAVE_IPV6
1210 sock_addr = "::,0.0.0.0";
1211 #else
1212 sock_addr = "0.0.0.0";
1213 #endif
1215 for (sock_ptr=sock_addr;
1216 next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
1217 for (j = 0; ports && ports[j]; j++) {
1218 struct sockaddr_storage ss;
1219 unsigned port = atoi(ports[j]);
1221 /* Keep the first port for mDNS service
1222 * registration.
1224 if (dns_port == 0) {
1225 dns_port = port;
1228 /* open an incoming socket */
1229 if (!interpret_string_addr(&ss, sock_tok,
1230 AI_NUMERICHOST|AI_PASSIVE)) {
1231 continue;
1235 * If we fail to open any sockets
1236 * in this loop the parent-sockets == NULL
1237 * case below will prevent us from starting.
1240 (void)smbd_open_one_socket(parent,
1241 ev_ctx,
1242 &ss,
1243 port);
1248 if (parent->sockets == NULL) {
1249 DEBUG(0,("open_sockets_smbd: No "
1250 "sockets available to bind to.\n"));
1251 return false;
1254 /* Setup the main smbd so that we can get messages. Note that
1255 do this after starting listening. This is needed as when in
1256 clustered mode, ctdb won't allow us to start doing database
1257 operations until it has gone thru a full startup, which
1258 includes checking to see that smbd is listening. */
1260 if (!serverid_register(messaging_server_id(msg_ctx),
1261 FLAG_MSG_GENERAL|FLAG_MSG_SMBD
1262 |FLAG_MSG_PRINT_GENERAL
1263 |FLAG_MSG_DBWRAP)) {
1264 DEBUG(0, ("open_sockets_smbd: Failed to register "
1265 "myself in serverid.tdb\n"));
1266 return false;
1269 /* Listen to messages */
1271 messaging_register(msg_ctx, NULL, MSG_SHUTDOWN, msg_exit_server);
1272 messaging_register(msg_ctx, ev_ctx, MSG_SMB_CONF_UPDATED,
1273 smbd_parent_conf_updated);
1274 messaging_register(msg_ctx, NULL, MSG_SMB_STAT_CACHE_DELETE,
1275 smb_stat_cache_delete);
1276 messaging_register(msg_ctx, NULL, MSG_DEBUG, smbd_msg_debug);
1277 messaging_register(msg_ctx, NULL, MSG_SMB_FORCE_TDIS,
1278 smb_parent_send_to_children);
1279 messaging_register(msg_ctx, NULL, MSG_SMB_KILL_CLIENT_IP,
1280 smb_parent_send_to_children);
1281 messaging_register(msg_ctx, NULL, MSG_SMB_TELL_NUM_CHILDREN,
1282 smb_tell_num_children);
1284 messaging_register(msg_ctx, NULL,
1285 ID_CACHE_DELETE, smbd_parent_id_cache_delete);
1286 messaging_register(msg_ctx, NULL,
1287 ID_CACHE_KILL, smbd_parent_id_cache_kill);
1288 messaging_register(msg_ctx, NULL, MSG_SMB_NOTIFY_STARTED,
1289 smb_parent_send_to_children);
1291 #ifdef CLUSTER_SUPPORT
1292 if (lp_clustering()) {
1293 struct ctdbd_connection *conn = messaging_ctdbd_connection();
1295 register_with_ctdbd(conn, CTDB_SRVID_RECONFIGURE,
1296 smbd_parent_ctdb_reconfigured, msg_ctx);
1297 register_with_ctdbd(conn, CTDB_SRVID_SAMBA_NOTIFY,
1298 smbd_parent_ctdb_reconfigured, msg_ctx);
1300 #endif
1302 #ifdef DEVELOPER
1303 messaging_register(msg_ctx, NULL, MSG_SMB_INJECT_FAULT,
1304 msg_inject_fault);
1305 #endif
1307 if (lp_multicast_dns_register() && (dns_port != 0)) {
1308 #ifdef WITH_DNSSD_SUPPORT
1309 smbd_setup_mdns_registration(ev_ctx,
1310 parent, dns_port);
1311 #endif
1312 #ifdef WITH_AVAHI_SUPPORT
1313 void *avahi_conn;
1315 avahi_conn = avahi_start_register(ev_ctx,
1316 ev_ctx,
1317 dns_port);
1318 if (avahi_conn == NULL) {
1319 DEBUG(10, ("avahi_start_register failed\n"));
1321 #endif
1324 return true;
1329 handle stdin becoming readable when we are in --foreground mode
1331 static void smbd_stdin_handler(struct tevent_context *ev,
1332 struct tevent_fd *fde,
1333 uint16_t flags,
1334 void *private_data)
1336 char c;
1337 if (read(0, &c, 1) != 1) {
1338 /* we have reached EOF on stdin, which means the
1339 parent has exited. Shutdown the server */
1340 exit_server_cleanly("EOF on stdin");
1344 struct smbd_parent_tevent_trace_state {
1345 TALLOC_CTX *frame;
1348 static void smbd_parent_tevent_trace_callback(enum tevent_trace_point point,
1349 void *private_data)
1351 struct smbd_parent_tevent_trace_state *state =
1352 (struct smbd_parent_tevent_trace_state *)private_data;
1354 switch (point) {
1355 case TEVENT_TRACE_BEFORE_WAIT:
1356 break;
1357 case TEVENT_TRACE_AFTER_WAIT:
1358 break;
1359 case TEVENT_TRACE_BEFORE_LOOP_ONCE:
1360 TALLOC_FREE(state->frame);
1361 state->frame = talloc_stackframe();
1362 break;
1363 case TEVENT_TRACE_AFTER_LOOP_ONCE:
1364 TALLOC_FREE(state->frame);
1365 break;
1368 errno = 0;
1371 static void smbd_parent_loop(struct tevent_context *ev_ctx,
1372 struct smbd_parent_context *parent)
1374 struct smbd_parent_tevent_trace_state trace_state = {
1375 .frame = NULL,
1377 int ret = 0;
1379 tevent_set_trace_callback(ev_ctx, smbd_parent_tevent_trace_callback,
1380 &trace_state);
1382 /* now accept incoming connections - forking a new process
1383 for each incoming connection */
1384 DEBUG(2,("waiting for connections\n"));
1386 ret = tevent_loop_wait(ev_ctx);
1387 if (ret != 0) {
1388 DEBUG(0, ("tevent_loop_wait failed: %d, %s, exiting\n",
1389 ret, strerror(errno)));
1392 TALLOC_FREE(trace_state.frame);
1394 /* NOTREACHED return True; */
1398 /****************************************************************************
1399 Initialise connect, service and file structs.
1400 ****************************************************************************/
1402 static bool init_structs(void )
1405 * Set the machine NETBIOS name if not already
1406 * set from the config file.
1409 if (!init_names())
1410 return False;
1412 if (!secrets_init())
1413 return False;
1415 return True;
1418 static void smbd_parent_sig_term_handler(struct tevent_context *ev,
1419 struct tevent_signal *se,
1420 int signum,
1421 int count,
1422 void *siginfo,
1423 void *private_data)
1425 exit_server_cleanly("termination signal");
1428 static void smbd_parent_sig_hup_handler(struct tevent_context *ev,
1429 struct tevent_signal *se,
1430 int signum,
1431 int count,
1432 void *siginfo,
1433 void *private_data)
1435 struct smbd_parent_context *parent =
1436 talloc_get_type_abort(private_data,
1437 struct smbd_parent_context);
1439 change_to_root_user();
1440 DEBUG(1,("parent: Reloading services after SIGHUP\n"));
1441 reload_services(NULL, NULL, false);
1443 printing_subsystem_update(parent->ev_ctx, parent->msg_ctx, true);
1446 struct smbd_claim_version_state {
1447 TALLOC_CTX *mem_ctx;
1448 char *version;
1451 static void smbd_claim_version_parser(const struct g_lock_rec *locks,
1452 size_t num_locks,
1453 const uint8_t *data,
1454 size_t datalen,
1455 void *private_data)
1457 struct smbd_claim_version_state *state = private_data;
1459 if (datalen == 0) {
1460 state->version = NULL;
1461 return;
1463 if (data[datalen-1] != '\0') {
1464 DBG_WARNING("Invalid samba version\n");
1465 dump_data(DBGLVL_WARNING, data, datalen);
1466 state->version = NULL;
1467 return;
1469 state->version = talloc_strdup(state->mem_ctx, (const char *)data);
1472 static NTSTATUS smbd_claim_version(struct messaging_context *msg,
1473 const char *version)
1475 const char *name = "samba_version_string";
1476 struct smbd_claim_version_state state;
1477 struct g_lock_ctx *ctx;
1478 NTSTATUS status;
1480 ctx = g_lock_ctx_init(msg, msg);
1481 if (ctx == NULL) {
1482 DBG_WARNING("g_lock_ctx_init failed\n");
1483 return NT_STATUS_UNSUCCESSFUL;
1486 status = g_lock_lock(ctx, name, G_LOCK_READ,
1487 (struct timeval) { .tv_sec = 60 });
1488 if (!NT_STATUS_IS_OK(status)) {
1489 DBG_WARNING("g_lock_lock(G_LOCK_READ) failed: %s\n",
1490 nt_errstr(status));
1491 TALLOC_FREE(ctx);
1492 return status;
1495 state = (struct smbd_claim_version_state) { .mem_ctx = ctx };
1497 status = g_lock_dump(ctx, name, smbd_claim_version_parser, &state);
1498 if (!NT_STATUS_IS_OK(status) &&
1499 !NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1500 DBG_ERR("Could not read samba_version_string\n");
1501 g_lock_unlock(ctx, name);
1502 TALLOC_FREE(ctx);
1503 return status;
1506 if ((state.version != NULL) && (strcmp(version, state.version) == 0)) {
1508 * Leave the read lock for us around. Someone else already
1509 * set the version correctly
1511 TALLOC_FREE(ctx);
1512 return NT_STATUS_OK;
1515 status = g_lock_lock(ctx, name, G_LOCK_WRITE,
1516 (struct timeval) { .tv_sec = 60 });
1517 if (!NT_STATUS_IS_OK(status)) {
1518 DBG_WARNING("g_lock_lock(G_LOCK_WRITE) failed: %s\n",
1519 nt_errstr(status));
1520 DBG_ERR("smbd %s already running, refusing to start "
1521 "version %s\n", state.version, version);
1522 TALLOC_FREE(ctx);
1523 return NT_STATUS_SXS_VERSION_CONFLICT;
1526 status = g_lock_write_data(ctx, name, (const uint8_t *)version,
1527 strlen(version)+1);
1528 if (!NT_STATUS_IS_OK(status)) {
1529 DBG_WARNING("g_lock_write_data failed: %s\n",
1530 nt_errstr(status));
1531 TALLOC_FREE(ctx);
1532 return status;
1535 status = g_lock_lock(ctx, name, G_LOCK_READ,
1536 (struct timeval) { .tv_sec = 60 });
1537 if (!NT_STATUS_IS_OK(status)) {
1538 DBG_WARNING("g_lock_lock(G_LOCK_READ) failed: %s\n",
1539 nt_errstr(status));
1540 TALLOC_FREE(ctx);
1541 return status;
1545 * Leave "ctx" dangling so that g_lock.tdb keeps opened.
1547 return NT_STATUS_OK;
1550 /****************************************************************************
1551 main program.
1552 ****************************************************************************/
1554 /* Declare prototype for build_options() to avoid having to run it through
1555 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1556 prototype generation system is too complicated. */
1558 extern void build_options(bool screen);
1560 int main(int argc,const char *argv[])
1562 /* shall I run as a daemon */
1563 bool is_daemon = false;
1564 bool interactive = false;
1565 bool Fork = true;
1566 bool no_process_group = false;
1567 bool log_stdout = false;
1568 char *ports = NULL;
1569 char *profile_level = NULL;
1570 int opt;
1571 poptContext pc;
1572 bool print_build_options = False;
1573 struct server_id main_server_id = {0};
1574 enum {
1575 OPT_DAEMON = 1000,
1576 OPT_INTERACTIVE,
1577 OPT_FORK,
1578 OPT_NO_PROCESS_GROUP,
1579 OPT_LOG_STDOUT
1581 struct poptOption long_options[] = {
1582 POPT_AUTOHELP
1583 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1584 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1585 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1586 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1587 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1588 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1589 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1590 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1591 POPT_COMMON_SAMBA
1592 POPT_TABLEEND
1594 struct smbd_parent_context *parent = NULL;
1595 TALLOC_CTX *frame;
1596 NTSTATUS status;
1597 struct tevent_context *ev_ctx;
1598 struct messaging_context *msg_ctx;
1599 struct server_id server_id;
1600 struct tevent_signal *se;
1601 int profiling_level;
1602 char *np_dir = NULL;
1603 static const struct smbd_shim smbd_shim_fns =
1605 .cancel_pending_lock_requests_by_fid = smbd_cancel_pending_lock_requests_by_fid,
1606 .send_stat_cache_delete_message = smbd_send_stat_cache_delete_message,
1607 .change_to_root_user = smbd_change_to_root_user,
1608 .become_authenticated_pipe_user = smbd_become_authenticated_pipe_user,
1609 .unbecome_authenticated_pipe_user = smbd_unbecome_authenticated_pipe_user,
1611 .contend_level2_oplocks_begin = smbd_contend_level2_oplocks_begin,
1612 .contend_level2_oplocks_end = smbd_contend_level2_oplocks_end,
1614 .become_root = smbd_become_root,
1615 .unbecome_root = smbd_unbecome_root,
1617 .exit_server = smbd_exit_server,
1618 .exit_server_cleanly = smbd_exit_server_cleanly,
1622 * Do this before any other talloc operation
1624 talloc_enable_null_tracking();
1625 frame = talloc_stackframe();
1627 setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
1629 smb_init_locale();
1631 set_smbd_shim(&smbd_shim_fns);
1633 smbd_init_globals();
1635 TimeInit();
1637 #ifdef HAVE_SET_AUTH_PARAMETERS
1638 set_auth_parameters(argc,argv);
1639 #endif
1641 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1642 while((opt = poptGetNextOpt(pc)) != -1) {
1643 switch (opt) {
1644 case OPT_DAEMON:
1645 is_daemon = true;
1646 break;
1647 case OPT_INTERACTIVE:
1648 interactive = true;
1649 break;
1650 case OPT_FORK:
1651 Fork = false;
1652 break;
1653 case OPT_NO_PROCESS_GROUP:
1654 no_process_group = true;
1655 break;
1656 case OPT_LOG_STDOUT:
1657 log_stdout = true;
1658 break;
1659 case 'b':
1660 print_build_options = True;
1661 break;
1662 default:
1663 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1664 poptBadOption(pc, 0), poptStrerror(opt));
1665 poptPrintUsage(pc, stderr, 0);
1666 exit(1);
1669 poptFreeContext(pc);
1671 if (interactive) {
1672 Fork = False;
1673 log_stdout = True;
1676 if (log_stdout) {
1677 setup_logging(argv[0], DEBUG_STDOUT);
1678 } else {
1679 setup_logging(argv[0], DEBUG_FILE);
1682 if (print_build_options) {
1683 build_options(True); /* Display output to screen as well as debug */
1684 exit(0);
1687 #ifdef HAVE_SETLUID
1688 /* needed for SecureWare on SCO */
1689 setluid(0);
1690 #endif
1692 set_remote_machine_name("smbd", False);
1694 if (interactive && (DEBUGLEVEL >= 9)) {
1695 talloc_enable_leak_report();
1698 if (log_stdout && Fork) {
1699 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1700 exit(1);
1704 * We want to die early if we can't open /dev/urandom
1706 generate_random_buffer(NULL, 0);
1708 /* get initial effective uid and gid */
1709 sec_init();
1711 /* make absolutely sure we run as root - to handle cases where people
1712 are crazy enough to have it setuid */
1713 gain_root_privilege();
1714 gain_root_group_privilege();
1716 fault_setup();
1717 dump_core_setup("smbd", lp_logfile(talloc_tos()));
1719 /* we are never interested in SIGPIPE */
1720 BlockSignals(True,SIGPIPE);
1722 #if defined(SIGFPE)
1723 /* we are never interested in SIGFPE */
1724 BlockSignals(True,SIGFPE);
1725 #endif
1727 #if defined(SIGUSR2)
1728 /* We are no longer interested in USR2 */
1729 BlockSignals(True,SIGUSR2);
1730 #endif
1732 /* POSIX demands that signals are inherited. If the invoking process has
1733 * these signals masked, we will have problems, as we won't recieve them. */
1734 BlockSignals(False, SIGHUP);
1735 BlockSignals(False, SIGUSR1);
1736 BlockSignals(False, SIGTERM);
1738 /* Ensure we leave no zombies until we
1739 * correctly set up child handling below. */
1741 CatchChild();
1743 /* we want total control over the permissions on created files,
1744 so set our umask to 0 */
1745 umask(0);
1747 reopen_logs();
1749 DEBUG(0,("smbd version %s started.\n", samba_version_string()));
1750 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1752 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1753 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1755 /* Output the build options to the debug log */
1756 build_options(False);
1758 if (sizeof(uint16_t) < 2 || sizeof(uint32_t) < 4) {
1759 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1760 exit(1);
1763 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1764 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
1765 exit(1);
1768 if (!cluster_probe_ok()) {
1769 exit(1);
1772 /* Init the security context and global current_user */
1773 init_sec_ctx();
1776 * Initialize the event context. The event context needs to be
1777 * initialized before the messaging context, cause the messaging
1778 * context holds an event context.
1780 ev_ctx = server_event_context();
1781 if (ev_ctx == NULL) {
1782 exit(1);
1786 * Init the messaging context
1787 * FIXME: This should only call messaging_init()
1789 msg_ctx = server_messaging_context();
1790 if (msg_ctx == NULL) {
1791 exit(1);
1795 * Reloading of the printers will not work here as we don't have a
1796 * server info and rpc services set up. It will be called later.
1798 if (!reload_services(NULL, NULL, false)) {
1799 exit(1);
1802 if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
1803 && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
1804 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running smbd standalone. \n"));
1805 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting smbd if required\n"));
1806 exit(1);
1809 /* ...NOTE... Log files are working from this point! */
1811 DEBUG(3,("loaded services\n"));
1813 init_structs();
1815 if (!profile_setup(msg_ctx, False)) {
1816 DEBUG(0,("ERROR: failed to setup profiling\n"));
1817 return -1;
1820 if (profile_level != NULL) {
1821 profiling_level = atoi(profile_level);
1822 } else {
1823 profiling_level = lp_smbd_profiling_level();
1825 main_server_id = messaging_server_id(msg_ctx);
1826 set_profile_level(profiling_level, &main_server_id);
1828 if (!is_daemon && !is_a_socket(0)) {
1829 if (!interactive) {
1830 DEBUG(3, ("Standard input is not a socket, "
1831 "assuming -D option\n"));
1835 * Setting is_daemon here prevents us from eventually calling
1836 * the open_sockets_inetd()
1839 is_daemon = True;
1842 if (is_daemon && !interactive) {
1843 DEBUG(3, ("Becoming a daemon.\n"));
1844 become_daemon(Fork, no_process_group, log_stdout);
1847 #if HAVE_SETPGID
1849 * If we're interactive we want to set our own process group for
1850 * signal management.
1852 if (interactive && !no_process_group)
1853 setpgid( (pid_t)0, (pid_t)0);
1854 #endif
1856 if (!directory_exist(lp_lock_directory()))
1857 mkdir(lp_lock_directory(), 0755);
1859 if (!directory_exist(lp_pid_directory()))
1860 mkdir(lp_pid_directory(), 0755);
1862 if (is_daemon)
1863 pidfile_create(lp_pid_directory(), "smbd");
1865 status = reinit_after_fork(msg_ctx, ev_ctx, false, NULL);
1866 if (!NT_STATUS_IS_OK(status)) {
1867 exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
1870 if (!interactive) {
1872 * Do not initialize the parent-child-pipe before becoming a
1873 * daemon: this is used to detect a died parent in the child
1874 * process.
1876 status = init_before_fork();
1877 if (!NT_STATUS_IS_OK(status)) {
1878 exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
1882 parent = talloc_zero(ev_ctx, struct smbd_parent_context);
1883 if (!parent) {
1884 exit_server("talloc(struct smbd_parent_context) failed");
1886 parent->interactive = interactive;
1887 parent->ev_ctx = ev_ctx;
1888 parent->msg_ctx = msg_ctx;
1889 am_parent = parent;
1891 se = tevent_add_signal(parent->ev_ctx,
1892 parent,
1893 SIGTERM, 0,
1894 smbd_parent_sig_term_handler,
1895 parent);
1896 if (!se) {
1897 exit_server("failed to setup SIGTERM handler");
1899 se = tevent_add_signal(parent->ev_ctx,
1900 parent,
1901 SIGHUP, 0,
1902 smbd_parent_sig_hup_handler,
1903 parent);
1904 if (!se) {
1905 exit_server("failed to setup SIGHUP handler");
1908 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1910 if (smbd_memcache() == NULL) {
1911 exit_daemon("no memcache available", EACCES);
1914 memcache_set_global(smbd_memcache());
1916 /* Initialise the password backed before the global_sam_sid
1917 to ensure that we fetch from ldap before we make a domain sid up */
1919 if(!initialize_password_db(false, ev_ctx))
1920 exit(1);
1922 if (!secrets_init()) {
1923 exit_daemon("smbd can not open secrets.tdb", EACCES);
1926 if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
1927 struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_helpers());
1928 if (!open_schannel_session_store(NULL, lp_ctx)) {
1929 exit_daemon("ERROR: Samba cannot open schannel store for secured NETLOGON operations.", EACCES);
1931 TALLOC_FREE(lp_ctx);
1934 if(!get_global_sam_sid()) {
1935 exit_daemon("Samba cannot create a SAM SID", EACCES);
1938 server_id = messaging_server_id(msg_ctx);
1939 status = smbXsrv_version_global_init(&server_id);
1940 if (!NT_STATUS_IS_OK(status)) {
1941 exit_daemon("Samba cannot init server context", EACCES);
1944 status = smbXsrv_session_global_init(msg_ctx);
1945 if (!NT_STATUS_IS_OK(status)) {
1946 exit_daemon("Samba cannot init session context", EACCES);
1949 status = smbXsrv_tcon_global_init();
1950 if (!NT_STATUS_IS_OK(status)) {
1951 exit_daemon("Samba cannot init tcon context", EACCES);
1954 if (!locking_init())
1955 exit_daemon("Samba cannot init locking", EACCES);
1957 if (!leases_db_init(false)) {
1958 exit_daemon("Samba cannot init leases", EACCES);
1961 if (!smbd_notifyd_init(msg_ctx, interactive, &parent->notifyd)) {
1962 exit_daemon("Samba cannot init notification", EACCES);
1965 if (!cleanupd_init(msg_ctx, interactive, &parent->cleanupd)) {
1966 exit_daemon("Samba cannot init the cleanupd", EACCES);
1969 if (!messaging_parent_dgm_cleanup_init(msg_ctx)) {
1970 exit(1);
1973 if (!smbd_scavenger_init(NULL, msg_ctx, ev_ctx)) {
1974 exit_daemon("Samba cannot init scavenging", EACCES);
1977 if (!serverid_parent_init(ev_ctx)) {
1978 exit_daemon("Samba cannot init server id", EACCES);
1981 if (!W_ERROR_IS_OK(registry_init_full()))
1982 exit_daemon("Samba cannot init registry", EACCES);
1984 /* Open the share_info.tdb here, so we don't have to open
1985 after the fork on every single connection. This is a small
1986 performance improvment and reduces the total number of system
1987 fds used. */
1988 if (!share_info_db_init()) {
1989 exit_daemon("ERROR: failed to load share info db.", EACCES);
1992 status = init_system_session_info();
1993 if (!NT_STATUS_IS_OK(status)) {
1994 DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
1995 nt_errstr(status)));
1996 return -1;
1999 if (!init_guest_info()) {
2000 DEBUG(0,("ERROR: failed to setup guest info.\n"));
2001 return -1;
2004 if (!file_init_global()) {
2005 DEBUG(0, ("ERROR: file_init_global() failed\n"));
2006 return -1;
2008 status = smbXsrv_open_global_init();
2009 if (!NT_STATUS_IS_OK(status)) {
2010 exit_daemon("Samba cannot init global open", map_errno_from_nt_status(status));
2013 if (lp_clustering() && !lp_allow_unsafe_cluster_upgrade()) {
2014 status = smbd_claim_version(msg_ctx, samba_version_string());
2015 if (!NT_STATUS_IS_OK(status)) {
2016 DBG_WARNING("Could not claim version: %s\n",
2017 nt_errstr(status));
2018 return -1;
2022 /* This MUST be done before start_epmd() because otherwise
2023 * start_epmd() forks and races against dcesrv_ep_setup() to
2024 * call directory_create_or_exist() */
2025 if (!directory_create_or_exist(lp_ncalrpc_dir(), 0755)) {
2026 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
2027 lp_ncalrpc_dir(), strerror(errno)));
2028 return -1;
2031 np_dir = talloc_asprintf(talloc_tos(), "%s/np", lp_ncalrpc_dir());
2032 if (!np_dir) {
2033 DEBUG(0, ("%s: Out of memory\n", __location__));
2034 return -1;
2037 if (!directory_create_or_exist_strict(np_dir, geteuid(), 0700)) {
2038 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
2039 np_dir, strerror(errno)));
2040 return -1;
2043 if (is_daemon && !interactive) {
2044 if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
2045 start_epmd(ev_ctx, msg_ctx);
2049 if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
2050 exit_daemon("Samba cannot setup ep pipe", EACCES);
2053 if (is_daemon && !interactive) {
2054 daemon_ready("smbd");
2057 /* only start other daemons if we are running as a daemon
2058 * -- bad things will happen if smbd is launched via inetd
2059 * and we fork a copy of ourselves here */
2060 if (is_daemon && !interactive) {
2062 if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
2063 start_lsasd(ev_ctx, msg_ctx);
2066 if (rpc_fss_daemon() == RPC_DAEMON_FORK) {
2067 start_fssd(ev_ctx, msg_ctx);
2070 if (!lp__disable_spoolss() &&
2071 (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2072 bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);
2074 if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
2075 exit_daemon("Samba failed to init printing subsystem", EACCES);
2079 #ifdef WITH_SPOTLIGHT
2080 if ((rpc_mdssvc_mode() == RPC_SERVICE_MODE_EXTERNAL) &&
2081 (rpc_mdssd_daemon() == RPC_DAEMON_FORK)) {
2082 start_mdssd(ev_ctx, msg_ctx);
2084 #endif
2085 } else if (!lp__disable_spoolss() &&
2086 (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2087 if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
2088 exit(1);
2092 if (!is_daemon) {
2093 int sock;
2095 /* inetd mode */
2096 TALLOC_FREE(frame);
2098 /* Started from inetd. fd 0 is the socket. */
2099 /* We will abort gracefully when the client or remote system
2100 goes away */
2101 sock = dup(0);
2103 /* close stdin, stdout (if not logging to it), but not stderr */
2104 close_low_fds(true, !debug_get_output_is_stdout(), false);
2106 #ifdef HAVE_ATEXIT
2107 atexit(killkids);
2108 #endif
2110 /* Stop zombies */
2111 smbd_setup_sig_chld_handler(parent);
2113 smbd_process(ev_ctx, msg_ctx, sock, true);
2115 exit_server_cleanly(NULL);
2116 return(0);
2119 if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
2120 exit_server("open_sockets_smbd() failed");
2122 /* do a printer update now that all messaging has been set up,
2123 * before we allow clients to start connecting */
2124 if (!lp__disable_spoolss() &&
2125 (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
2126 printing_subsystem_update(ev_ctx, msg_ctx, false);
2129 TALLOC_FREE(frame);
2130 /* make sure we always have a valid stackframe */
2131 frame = talloc_stackframe();
2133 if (!Fork) {
2134 /* if we are running in the foreground then look for
2135 EOF on stdin, and exit if it happens. This allows
2136 us to die if the parent process dies
2137 Only do this on a pipe or socket, no other device.
2139 struct stat st;
2140 if (fstat(0, &st) != 0) {
2141 return false;
2143 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
2144 tevent_add_fd(ev_ctx,
2145 parent,
2147 TEVENT_FD_READ,
2148 smbd_stdin_handler,
2149 NULL);
2153 smbd_parent_loop(ev_ctx, parent);
2155 exit_server_cleanly(NULL);
2156 TALLOC_FREE(frame);
2157 return(0);