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