Revert "s3:messages: allow messaging_filtered_read_send() to use wrapper tevent_context"
[samba.git] / source3 / winbindd / winbindd_dual.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind child daemons
5
6    Copyright (C) Andrew Tridgell 2002
7    Copyright (C) Volker Lendecke 2004,2005
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  * We fork a child per domain to be able to act non-blocking in the main
25  * winbind daemon. A domain controller thousands of miles away being being
26  * slow replying with a 10.000 user list should not hold up netlogon calls
27  * that can be handled locally.
28  */
29
30 #include "includes.h"
31 #include "winbindd.h"
32 #include "rpc_client/rpc_client.h"
33 #include "nsswitch/wb_reqtrans.h"
34 #include "secrets.h"
35 #include "../lib/util/select.h"
36 #include "../libcli/security/security.h"
37 #include "system/select.h"
38 #include "messages.h"
39 #include "../lib/util/tevent_unix.h"
40 #include "lib/param/loadparm.h"
41 #include "lib/util/sys_rw.h"
42 #include "lib/util/sys_rw_data.h"
43 #include "passdb.h"
44
45 #undef DBGC_CLASS
46 #define DBGC_CLASS DBGC_WINBIND
47
48 extern bool override_logfile;
49
50 static void forall_domain_children(bool (*fn)(struct winbindd_child *c,
51                                               void *private_data),
52                                    void *private_data)
53 {
54         struct winbindd_domain *d;
55
56         for (d = domain_list(); d != NULL; d = d->next) {
57                 int i;
58
59                 for (i = 0; i < lp_winbind_max_domain_connections(); i++) {
60                         struct winbindd_child *c = &d->children[i];
61                         bool ok;
62
63                         if (c->pid == 0) {
64                                 continue;
65                         }
66
67                         ok = fn(c, private_data);
68                         if (!ok) {
69                                 return;
70                         }
71                 }
72         }
73 }
74
75 static void forall_children(bool (*fn)(struct winbindd_child *c,
76                                        void *private_data),
77                             void *private_data)
78 {
79         struct winbindd_child *c;
80         bool ok;
81
82         c = idmap_child();
83         if (c->pid != 0) {
84                 ok = fn(c, private_data);
85                 if (!ok) {
86                         return;
87                 }
88         }
89
90         c = locator_child();
91         if (c->pid != 0) {
92                 ok = fn(c, private_data);
93                 if (!ok) {
94                         return;
95                 }
96         }
97
98         forall_domain_children(fn, private_data);
99 }
100
101 /* Read some data from a client connection */
102
103 static NTSTATUS child_read_request(int sock, struct winbindd_request *wreq)
104 {
105         NTSTATUS status;
106
107         status = read_data_ntstatus(sock, (char *)wreq, sizeof(*wreq));
108         if (!NT_STATUS_IS_OK(status)) {
109                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
110                           nt_errstr(status)));
111                 return status;
112         }
113
114         if (wreq->extra_len == 0) {
115                 wreq->extra_data.data = NULL;
116                 return NT_STATUS_OK;
117         }
118
119         DEBUG(10, ("Need to read %d extra bytes\n", (int)wreq->extra_len));
120
121         wreq->extra_data.data = SMB_MALLOC_ARRAY(char, wreq->extra_len + 1);
122         if (wreq->extra_data.data == NULL) {
123                 DEBUG(0, ("malloc failed\n"));
124                 return NT_STATUS_NO_MEMORY;
125         }
126
127         /* Ensure null termination */
128         wreq->extra_data.data[wreq->extra_len] = '\0';
129
130         status = read_data_ntstatus(sock, wreq->extra_data.data,
131                                     wreq->extra_len);
132         if (!NT_STATUS_IS_OK(status)) {
133                 DEBUG(0, ("Could not read extra data: %s\n",
134                           nt_errstr(status)));
135         }
136         return status;
137 }
138
139 static NTSTATUS child_write_response(int sock, struct winbindd_response *wrsp)
140 {
141         struct iovec iov[2];
142         int iov_count;
143
144         iov[0].iov_base = (void *)wrsp;
145         iov[0].iov_len = sizeof(struct winbindd_response);
146         iov_count = 1;
147
148         if (wrsp->length > sizeof(struct winbindd_response)) {
149                 iov[1].iov_base = (void *)wrsp->extra_data.data;
150                 iov[1].iov_len = wrsp->length-iov[0].iov_len;
151                 iov_count = 2;
152         }
153
154         DEBUG(10, ("Writing %d bytes to parent\n", (int)wrsp->length));
155
156         if (write_data_iov(sock, iov, iov_count) != wrsp->length) {
157                 DEBUG(0, ("Could not write result\n"));
158                 return NT_STATUS_INVALID_HANDLE;
159         }
160
161         return NT_STATUS_OK;
162 }
163
164 /*
165  * Do winbind child async request. This is not simply wb_simple_trans. We have
166  * to do the queueing ourselves because while a request is queued, the child
167  * might have crashed, and we have to re-fork it in the _trigger function.
168  */
169
170 struct wb_child_request_state {
171         struct tevent_context *ev;
172         struct tevent_req *queue_subreq;
173         struct tevent_req *subreq;
174         struct winbindd_child *child;
175         struct winbindd_request *request;
176         struct winbindd_response *response;
177 };
178
179 static bool fork_domain_child(struct winbindd_child *child);
180
181 static void wb_child_request_waited(struct tevent_req *subreq);
182 static void wb_child_request_done(struct tevent_req *subreq);
183 static void wb_child_request_orphaned(struct tevent_req *subreq);
184
185 static void wb_child_request_cleanup(struct tevent_req *req,
186                                      enum tevent_req_state req_state);
187
188 struct tevent_req *wb_child_request_send(TALLOC_CTX *mem_ctx,
189                                          struct tevent_context *ev,
190                                          struct winbindd_child *child,
191                                          struct winbindd_request *request)
192 {
193         struct tevent_req *req;
194         struct wb_child_request_state *state;
195         struct tevent_req *subreq;
196
197         req = tevent_req_create(mem_ctx, &state,
198                                 struct wb_child_request_state);
199         if (req == NULL) {
200                 return NULL;
201         }
202
203         state->ev = ev;
204         state->child = child;
205         state->request = request;
206
207         subreq = tevent_queue_wait_send(state, ev, child->queue);
208         if (tevent_req_nomem(subreq, req)) {
209                 return tevent_req_post(req, ev);
210         }
211         tevent_req_set_callback(subreq, wb_child_request_waited, req);
212         state->queue_subreq = subreq;
213
214         tevent_req_set_cleanup_fn(req, wb_child_request_cleanup);
215
216         return req;
217 }
218
219 static void wb_child_request_waited(struct tevent_req *subreq)
220 {
221         struct tevent_req *req = tevent_req_callback_data(
222                 subreq, struct tevent_req);
223         struct wb_child_request_state *state = tevent_req_data(
224                 req, struct wb_child_request_state);
225         bool ok;
226
227         ok = tevent_queue_wait_recv(subreq);
228         if (!ok) {
229                 tevent_req_oom(req);
230                 return;
231         }
232         /*
233          * We need to keep state->queue_subreq
234          * in order to block the queue.
235          */
236         subreq = NULL;
237
238         if ((state->child->sock == -1) && (!fork_domain_child(state->child))) {
239                 tevent_req_error(req, errno);
240                 return;
241         }
242
243         tevent_fd_set_flags(state->child->monitor_fde, 0);
244
245         subreq = wb_simple_trans_send(state, global_event_context(), NULL,
246                                       state->child->sock, state->request);
247         if (tevent_req_nomem(subreq, req)) {
248                 return;
249         }
250
251         state->subreq = subreq;
252         tevent_req_set_callback(subreq, wb_child_request_done, req);
253         tevent_req_set_endtime(req, state->ev, timeval_current_ofs(300, 0));
254 }
255
256 static void wb_child_request_done(struct tevent_req *subreq)
257 {
258         struct tevent_req *req = tevent_req_callback_data(
259                 subreq, struct tevent_req);
260         struct wb_child_request_state *state = tevent_req_data(
261                 req, struct wb_child_request_state);
262         int ret, err;
263
264         ret = wb_simple_trans_recv(subreq, state, &state->response, &err);
265         /* Freeing the subrequest is deferred until the cleanup function,
266          * which has to know whether a subrequest exists, and consequently
267          * decide whether to shut down the pipe to the child process.
268          */
269         if (ret == -1) {
270                 tevent_req_error(req, err);
271                 return;
272         }
273         tevent_req_done(req);
274 }
275
276 static void wb_child_request_orphaned(struct tevent_req *subreq)
277 {
278         struct winbindd_child *child =
279                 (struct winbindd_child *)tevent_req_callback_data_void(subreq);
280
281         DBG_WARNING("cleanup orphaned subreq[%p]\n", subreq);
282         TALLOC_FREE(subreq);
283
284         if (child->domain != NULL) {
285                 /*
286                  * If the child is attached to a domain,
287                  * we need to make sure the domain queue
288                  * can move forward, after the orphaned
289                  * request is done.
290                  */
291                 tevent_queue_start(child->domain->queue);
292         }
293 }
294
295 int wb_child_request_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
296                           struct winbindd_response **presponse, int *err)
297 {
298         struct wb_child_request_state *state = tevent_req_data(
299                 req, struct wb_child_request_state);
300
301         if (tevent_req_is_unix_error(req, err)) {
302                 return -1;
303         }
304         *presponse = talloc_move(mem_ctx, &state->response);
305         return 0;
306 }
307
308 static void wb_child_request_cleanup(struct tevent_req *req,
309                                      enum tevent_req_state req_state)
310 {
311         struct wb_child_request_state *state =
312             tevent_req_data(req, struct wb_child_request_state);
313
314         if (state->subreq == NULL) {
315                 /* nothing to cleanup */
316                 return;
317         }
318
319         if (req_state == TEVENT_REQ_RECEIVED) {
320                 struct tevent_req *subreq = NULL;
321
322                 /*
323                  * Our caller gave up, but we need to keep
324                  * the low level request (wb_simple_trans)
325                  * in order to maintain the parent child protocol.
326                  *
327                  * We also need to keep the child queue blocked
328                  * until we got the response from the child.
329                  */
330
331                 subreq = talloc_move(state->child->queue, &state->subreq);
332                 talloc_move(subreq, &state->queue_subreq);
333                 tevent_req_set_callback(subreq,
334                                         wb_child_request_orphaned,
335                                         state->child);
336
337                 DBG_WARNING("keep orphaned subreq[%p]\n", subreq);
338                 return;
339         }
340
341         TALLOC_FREE(state->subreq);
342         TALLOC_FREE(state->queue_subreq);
343
344         tevent_fd_set_flags(state->child->monitor_fde, TEVENT_FD_READ);
345
346         if (state->child->domain != NULL) {
347                 /*
348                  * If the child is attached to a domain,
349                  * we need to make sure the domain queue
350                  * can move forward, after the request
351                  * is done.
352                  */
353                 tevent_queue_start(state->child->domain->queue);
354         }
355
356         if (req_state == TEVENT_REQ_DONE) {
357                 /* transmitted request and got response */
358                 return;
359         }
360
361         /*
362          * Failed to transmit and receive response, or request
363          * cancelled while being serviced.
364          * The basic parent/child communication broke, close
365          * our socket
366          */
367         TALLOC_FREE(state->child->monitor_fde);
368         close(state->child->sock);
369         state->child->sock = -1;
370 }
371
372 static void child_socket_readable(struct tevent_context *ev,
373                                   struct tevent_fd *fde,
374                                   uint16_t flags,
375                                   void *private_data)
376 {
377         struct winbindd_child *child = private_data;
378
379         if ((flags & TEVENT_FD_READ) == 0) {
380                 return;
381         }
382
383         TALLOC_FREE(child->monitor_fde);
384
385         /*
386          * We're only active when there is no outstanding child
387          * request. Arriving here means the child closed its socket,
388          * it died. Do the same here.
389          */
390
391         SMB_ASSERT(child->sock != -1);
392
393         close(child->sock);
394         child->sock = -1;
395 }
396
397 static struct winbindd_child *choose_domain_child(struct winbindd_domain *domain)
398 {
399         struct winbindd_child *shortest = &domain->children[0];
400         struct winbindd_child *current;
401         int i;
402
403         for (i=0; i<lp_winbind_max_domain_connections(); i++) {
404                 size_t shortest_len, current_len;
405
406                 current = &domain->children[i];
407                 current_len = tevent_queue_length(current->queue);
408
409                 if (current_len == 0) {
410                         /* idle child */
411                         return current;
412                 }
413
414                 shortest_len = tevent_queue_length(shortest->queue);
415
416                 if (current_len < shortest_len) {
417                         shortest = current;
418                 }
419         }
420
421         return shortest;
422 }
423
424 struct dcerpc_binding_handle *dom_child_handle(struct winbindd_domain *domain)
425 {
426         return domain->binding_handle;
427 }
428
429 struct wb_domain_request_state {
430         struct tevent_context *ev;
431         struct tevent_queue_entry *queue_entry;
432         struct winbindd_domain *domain;
433         struct winbindd_child *child;
434         struct winbindd_request *request;
435         struct winbindd_request *init_req;
436         struct winbindd_response *response;
437         struct tevent_req *pending_subreq;
438 };
439
440 static void wb_domain_request_cleanup(struct tevent_req *req,
441                                       enum tevent_req_state req_state)
442 {
443         struct wb_domain_request_state *state = tevent_req_data(
444                 req, struct wb_domain_request_state);
445
446         /*
447          * If we're completely done or got a failure.
448          * we should remove ourself from the domain queue,
449          * after removing the child subreq from the child queue
450          * and give the next one in the queue the chance
451          * to check for an idle child.
452          */
453         TALLOC_FREE(state->pending_subreq);
454         TALLOC_FREE(state->queue_entry);
455         tevent_queue_start(state->domain->queue);
456 }
457
458 static void wb_domain_request_trigger(struct tevent_req *req,
459                                       void *private_data);
460 static void wb_domain_request_gotdc(struct tevent_req *subreq);
461 static void wb_domain_request_initialized(struct tevent_req *subreq);
462 static void wb_domain_request_done(struct tevent_req *subreq);
463
464 struct tevent_req *wb_domain_request_send(TALLOC_CTX *mem_ctx,
465                                           struct tevent_context *ev,
466                                           struct winbindd_domain *domain,
467                                           struct winbindd_request *request)
468 {
469         struct tevent_req *req;
470         struct wb_domain_request_state *state;
471
472         req = tevent_req_create(mem_ctx, &state,
473                                 struct wb_domain_request_state);
474         if (req == NULL) {
475                 return NULL;
476         }
477
478         state->domain = domain;
479         state->ev = ev;
480         state->request = request;
481
482         tevent_req_set_cleanup_fn(req, wb_domain_request_cleanup);
483
484         state->queue_entry = tevent_queue_add_entry(
485                         domain->queue, state->ev, req,
486                         wb_domain_request_trigger, NULL);
487         if (tevent_req_nomem(state->queue_entry, req)) {
488                 return tevent_req_post(req, ev);
489         }
490
491         return req;
492 }
493
494 static void wb_domain_request_trigger(struct tevent_req *req,
495                                       void *private_data)
496 {
497         struct wb_domain_request_state *state = tevent_req_data(
498                 req, struct wb_domain_request_state);
499         struct winbindd_domain *domain = state->domain;
500         struct tevent_req *subreq = NULL;
501         size_t shortest_queue_length;
502
503         state->child = choose_domain_child(domain);
504         shortest_queue_length = tevent_queue_length(state->child->queue);
505         if (shortest_queue_length > 0) {
506                 /*
507                  * All children are busy, we need to stop
508                  * the queue and untrigger our own queue
509                  * entry. Once a pending request
510                  * is done it calls tevent_queue_start
511                  * and we get retriggered.
512                  */
513                 state->child = NULL;
514                 tevent_queue_stop(state->domain->queue);
515                 tevent_queue_entry_untrigger(state->queue_entry);
516                 return;
517         }
518
519         if (domain->initialized) {
520                 subreq = wb_child_request_send(state, state->ev, state->child,
521                                                state->request);
522                 if (tevent_req_nomem(subreq, req)) {
523                         return;
524                 }
525                 tevent_req_set_callback(subreq, wb_domain_request_done, req);
526                 state->pending_subreq = subreq;
527
528                 /*
529                  * Once the domain is initialized and
530                  * once we placed our real request into the child queue,
531                  * we can remove ourself from the domain queue
532                  * and give the next one in the queue the chance
533                  * to check for an idle child.
534                  */
535                 TALLOC_FREE(state->queue_entry);
536                 return;
537         }
538
539         state->init_req = talloc_zero(state, struct winbindd_request);
540         if (tevent_req_nomem(state->init_req, req)) {
541                 return;
542         }
543
544         if (IS_DC || domain->primary || domain->internal) {
545                 /* The primary domain has to find the DC name itself */
546                 state->init_req->cmd = WINBINDD_INIT_CONNECTION;
547                 fstrcpy(state->init_req->domain_name, domain->name);
548                 state->init_req->data.init_conn.is_primary = domain->primary;
549                 fstrcpy(state->init_req->data.init_conn.dcname, "");
550
551                 subreq = wb_child_request_send(state, state->ev, state->child,
552                                                state->init_req);
553                 if (tevent_req_nomem(subreq, req)) {
554                         return;
555                 }
556                 tevent_req_set_callback(subreq, wb_domain_request_initialized,
557                                         req);
558                 state->pending_subreq = subreq;
559                 return;
560         }
561
562         /*
563          * This is *not* the primary domain,
564          * let's ask our DC about a DC name.
565          *
566          * We prefer getting a dns name in dc_unc,
567          * which is indicated by DS_RETURN_DNS_NAME.
568          * For NT4 domains we still get the netbios name.
569          */
570         subreq = wb_dsgetdcname_send(state, state->ev,
571                                      state->domain->name,
572                                      NULL, /* domain_guid */
573                                      NULL, /* site_name */
574                                      DS_RETURN_DNS_NAME); /* flags */
575         if (tevent_req_nomem(subreq, req)) {
576                 return;
577         }
578         tevent_req_set_callback(subreq, wb_domain_request_gotdc, req);
579         state->pending_subreq = subreq;
580         return;
581 }
582
583 static void wb_domain_request_gotdc(struct tevent_req *subreq)
584 {
585         struct tevent_req *req = tevent_req_callback_data(
586                 subreq, struct tevent_req);
587         struct wb_domain_request_state *state = tevent_req_data(
588                 req, struct wb_domain_request_state);
589         struct netr_DsRGetDCNameInfo *dcinfo = NULL;
590         NTSTATUS status;
591         const char *dcname = NULL;
592
593         state->pending_subreq = NULL;
594
595         status = wb_dsgetdcname_recv(subreq, state, &dcinfo);
596         TALLOC_FREE(subreq);
597         if (tevent_req_nterror(req, status)) {
598                 return;
599         }
600         dcname = dcinfo->dc_unc;
601         while (dcname != NULL && *dcname == '\\') {
602                 dcname++;
603         }
604         state->init_req->cmd = WINBINDD_INIT_CONNECTION;
605         fstrcpy(state->init_req->domain_name, state->domain->name);
606         state->init_req->data.init_conn.is_primary = False;
607         fstrcpy(state->init_req->data.init_conn.dcname,
608                 dcname);
609
610         TALLOC_FREE(dcinfo);
611
612         subreq = wb_child_request_send(state, state->ev, state->child,
613                                        state->init_req);
614         if (tevent_req_nomem(subreq, req)) {
615                 return;
616         }
617         tevent_req_set_callback(subreq, wb_domain_request_initialized, req);
618         state->pending_subreq = subreq;
619 }
620
621 static void wb_domain_request_initialized(struct tevent_req *subreq)
622 {
623         struct tevent_req *req = tevent_req_callback_data(
624                 subreq, struct tevent_req);
625         struct wb_domain_request_state *state = tevent_req_data(
626                 req, struct wb_domain_request_state);
627         struct winbindd_response *response;
628         int ret, err;
629
630         state->pending_subreq = NULL;
631
632         ret = wb_child_request_recv(subreq, talloc_tos(), &response, &err);
633         TALLOC_FREE(subreq);
634         if (ret == -1) {
635                 tevent_req_error(req, err);
636                 return;
637         }
638
639         if (!string_to_sid(&state->domain->sid,
640                            response->data.domain_info.sid)) {
641                 DEBUG(1,("init_child_recv: Could not convert sid %s "
642                         "from string\n", response->data.domain_info.sid));
643                 tevent_req_error(req, EINVAL);
644                 return;
645         }
646
647         talloc_free(state->domain->name);
648         state->domain->name = talloc_strdup(state->domain,
649                                             response->data.domain_info.name);
650         if (state->domain->name == NULL) {
651                 tevent_req_error(req, ENOMEM);
652                 return;
653         }
654
655         if (response->data.domain_info.alt_name[0] != '\0') {
656                 talloc_free(state->domain->alt_name);
657
658                 state->domain->alt_name = talloc_strdup(state->domain,
659                                 response->data.domain_info.alt_name);
660                 if (state->domain->alt_name == NULL) {
661                         tevent_req_error(req, ENOMEM);
662                         return;
663                 }
664         }
665
666         state->domain->native_mode = response->data.domain_info.native_mode;
667         state->domain->active_directory =
668                 response->data.domain_info.active_directory;
669         state->domain->initialized = true;
670
671         TALLOC_FREE(response);
672
673         subreq = wb_child_request_send(state, state->ev, state->child,
674                                        state->request);
675         if (tevent_req_nomem(subreq, req)) {
676                 return;
677         }
678         tevent_req_set_callback(subreq, wb_domain_request_done, req);
679         state->pending_subreq = subreq;
680
681         /*
682          * Once the domain is initialized and
683          * once we placed our real request into the child queue,
684          * we can remove ourself from the domain queue
685          * and give the next one in the queue the chance
686          * to check for an idle child.
687          */
688         TALLOC_FREE(state->queue_entry);
689 }
690
691 static void wb_domain_request_done(struct tevent_req *subreq)
692 {
693         struct tevent_req *req = tevent_req_callback_data(
694                 subreq, struct tevent_req);
695         struct wb_domain_request_state *state = tevent_req_data(
696                 req, struct wb_domain_request_state);
697         int ret, err;
698
699         state->pending_subreq = NULL;
700
701         ret = wb_child_request_recv(subreq, talloc_tos(), &state->response,
702                                     &err);
703         TALLOC_FREE(subreq);
704         if (ret == -1) {
705                 tevent_req_error(req, err);
706                 return;
707         }
708         tevent_req_done(req);
709 }
710
711 int wb_domain_request_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
712                            struct winbindd_response **presponse, int *err)
713 {
714         struct wb_domain_request_state *state = tevent_req_data(
715                 req, struct wb_domain_request_state);
716
717         if (tevent_req_is_unix_error(req, err)) {
718                 return -1;
719         }
720         *presponse = talloc_move(mem_ctx, &state->response);
721         return 0;
722 }
723
724 static void child_process_request(struct winbindd_child *child,
725                                   struct winbindd_cli_state *state)
726 {
727         struct winbindd_domain *domain = child->domain;
728         const struct winbindd_child_dispatch_table *table = child->table;
729
730         /* Free response data - we may be interrupted and receive another
731            command before being able to send this data off. */
732
733         state->response->result = WINBINDD_ERROR;
734         state->response->length = sizeof(struct winbindd_response);
735
736         /* as all requests in the child are sync, we can use talloc_tos() */
737         state->mem_ctx = talloc_tos();
738
739         /* Process command */
740
741         for (; table->name; table++) {
742                 if (state->request->cmd == table->struct_cmd) {
743                         DEBUG(10,("child_process_request: request fn %s\n",
744                                   table->name));
745                         state->response->result = table->struct_fn(domain, state);
746                         return;
747                 }
748         }
749
750         DEBUG(1, ("child_process_request: unknown request fn number %d\n",
751                   (int)state->request->cmd));
752         state->response->result = WINBINDD_ERROR;
753 }
754
755 void setup_child(struct winbindd_domain *domain, struct winbindd_child *child,
756                  const struct winbindd_child_dispatch_table *table,
757                  const char *logprefix,
758                  const char *logname)
759 {
760         if (logprefix && logname) {
761                 char *logbase = NULL;
762
763                 if (*lp_logfile(talloc_tos())) {
764                         char *end = NULL;
765
766                         if (asprintf(&logbase, "%s", lp_logfile(talloc_tos())) < 0) {
767                                 smb_panic("Internal error: asprintf failed");
768                         }
769
770                         if ((end = strrchr_m(logbase, '/'))) {
771                                 *end = '\0';
772                         }
773                 } else {
774                         if (asprintf(&logbase, "%s", get_dyn_LOGFILEBASE()) < 0) {
775                                 smb_panic("Internal error: asprintf failed");
776                         }
777                 }
778
779                 if (asprintf(&child->logfilename, "%s/%s-%s",
780                              logbase, logprefix, logname) < 0) {
781                         SAFE_FREE(logbase);
782                         smb_panic("Internal error: asprintf failed");
783                 }
784
785                 SAFE_FREE(logbase);
786         } else {
787                 smb_panic("Internal error: logprefix == NULL && "
788                           "logname == NULL");
789         }
790
791         child->pid = 0;
792         child->sock = -1;
793         child->domain = domain;
794         child->table = table;
795         child->queue = tevent_queue_create(NULL, "winbind_child");
796         SMB_ASSERT(child->queue != NULL);
797         if (domain == NULL) {
798                 child->binding_handle = wbint_binding_handle(NULL, NULL, child);
799                 SMB_ASSERT(child->binding_handle != NULL);
800         }
801 }
802
803 struct winbind_child_died_state {
804         pid_t pid;
805         struct winbindd_child *child;
806 };
807
808 static bool winbind_child_died_fn(struct winbindd_child *child,
809                                   void *private_data)
810 {
811         struct winbind_child_died_state *state = private_data;
812
813         if (child->pid == state->pid) {
814                 state->child = child;
815                 return false;
816         }
817         return true;
818 }
819
820 void winbind_child_died(pid_t pid)
821 {
822         struct winbind_child_died_state state = { .pid = pid };
823
824         forall_children(winbind_child_died_fn, &state);
825
826         if (state.child == NULL) {
827                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
828                 return;
829         }
830
831         state.child->pid = 0;
832 }
833
834 /* Ensure any negative cache entries with the netbios or realm names are removed. */
835
836 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
837 {
838         flush_negative_conn_cache_for_domain(domain->name);
839         if (domain->alt_name != NULL) {
840                 flush_negative_conn_cache_for_domain(domain->alt_name);
841         }
842 }
843
844 /* 
845  * Parent winbindd process sets its own debug level first and then
846  * sends a message to all the winbindd children to adjust their debug
847  * level to that of parents.
848  */
849
850 struct winbind_msg_relay_state {
851         struct messaging_context *msg_ctx;
852         uint32_t msg_type;
853         DATA_BLOB *data;
854 };
855
856 static bool winbind_msg_relay_fn(struct winbindd_child *child,
857                                  void *private_data)
858 {
859         struct winbind_msg_relay_state *state = private_data;
860
861         DBG_DEBUG("sending message to pid %u.\n",
862                   (unsigned int)child->pid);
863
864         messaging_send(state->msg_ctx, pid_to_procid(child->pid),
865                        state->msg_type, state->data);
866         return true;
867 }
868
869 void winbind_msg_debug(struct messaging_context *msg_ctx,
870                          void *private_data,
871                          uint32_t msg_type,
872                          struct server_id server_id,
873                          DATA_BLOB *data)
874 {
875         struct winbind_msg_relay_state state = {
876                 .msg_ctx = msg_ctx, .msg_type = msg_type, .data = data
877         };
878
879         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
880
881         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
882
883         forall_children(winbind_msg_relay_fn, &state);
884 }
885
886 void winbind_disconnect_dc_parent(struct messaging_context *msg_ctx,
887                                   void *private_data,
888                                   uint32_t msg_type,
889                                   struct server_id server_id,
890                                   DATA_BLOB *data)
891 {
892         struct winbind_msg_relay_state state = {
893                 .msg_ctx = msg_ctx, .msg_type = msg_type, .data = data
894         };
895
896         DBG_DEBUG("Got disconnect_dc message\n");
897
898         forall_children(winbind_msg_relay_fn, &state);
899 }
900
901 /* Set our domains as offline and forward the offline message to our children. */
902
903 struct winbind_msg_on_offline_state {
904         struct messaging_context *msg_ctx;
905         uint32_t msg_type;
906 };
907
908 static bool winbind_msg_on_offline_fn(struct winbindd_child *child,
909                                       void *private_data)
910 {
911         struct winbind_msg_on_offline_state *state = private_data;
912
913         if (child->domain->internal) {
914                 return true;
915         }
916
917         /*
918          * Each winbindd child should only process requests for one
919          * domain - make sure we only set it online / offline for that
920          * domain.
921          */
922         DBG_DEBUG("sending message to pid %u for domain %s.\n",
923                   (unsigned int)child->pid, child->domain->name);
924
925         messaging_send_buf(state->msg_ctx,
926                            pid_to_procid(child->pid),
927                            state->msg_type,
928                            (const uint8_t *)child->domain->name,
929                            strlen(child->domain->name)+1);
930
931         return true;
932 }
933
934 void winbind_msg_offline(struct messaging_context *msg_ctx,
935                          void *private_data,
936                          uint32_t msg_type,
937                          struct server_id server_id,
938                          DATA_BLOB *data)
939 {
940         struct winbind_msg_on_offline_state state = {
941                 .msg_ctx = msg_ctx,
942                 .msg_type = MSG_WINBIND_OFFLINE,
943         };
944         struct winbindd_domain *domain;
945
946         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
947
948         if (!lp_winbind_offline_logon()) {
949                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
950                 return;
951         }
952
953         /* Set our global state as offline. */
954         if (!set_global_winbindd_state_offline()) {
955                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
956                 return;
957         }
958
959         /* Set all our domains as offline. */
960         for (domain = domain_list(); domain; domain = domain->next) {
961                 if (domain->internal) {
962                         continue;
963                 }
964                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
965                 set_domain_offline(domain);
966         }
967
968         forall_domain_children(winbind_msg_on_offline_fn, &state);
969 }
970
971 /* Set our domains as online and forward the online message to our children. */
972
973 void winbind_msg_online(struct messaging_context *msg_ctx,
974                         void *private_data,
975                         uint32_t msg_type,
976                         struct server_id server_id,
977                         DATA_BLOB *data)
978 {
979         struct winbind_msg_on_offline_state state = {
980                 .msg_ctx = msg_ctx,
981                 .msg_type = MSG_WINBIND_ONLINE,
982         };
983         struct winbindd_domain *domain;
984
985         DEBUG(10,("winbind_msg_online: got online message.\n"));
986
987         if (!lp_winbind_offline_logon()) {
988                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
989                 return;
990         }
991
992         /* Set our global state as online. */
993         set_global_winbindd_state_online();
994
995         smb_nscd_flush_user_cache();
996         smb_nscd_flush_group_cache();
997
998         /* Set all our domains as online. */
999         for (domain = domain_list(); domain; domain = domain->next) {
1000                 if (domain->internal) {
1001                         continue;
1002                 }
1003                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
1004
1005                 winbindd_flush_negative_conn_cache(domain);
1006                 set_domain_online_request(domain);
1007
1008                 /* Send an online message to the idmap child when our
1009                    primary domain comes back online */
1010
1011                 if ( domain->primary ) {
1012                         struct winbindd_child *idmap = idmap_child();
1013
1014                         if ( idmap->pid != 0 ) {
1015                                 messaging_send_buf(msg_ctx,
1016                                                    pid_to_procid(idmap->pid), 
1017                                                    MSG_WINBIND_ONLINE,
1018                                                    (const uint8_t *)domain->name,
1019                                                    strlen(domain->name)+1);
1020                         }
1021                 }
1022         }
1023
1024         forall_domain_children(winbind_msg_on_offline_fn, &state);
1025 }
1026
1027 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
1028 {
1029         struct winbindd_domain *domain;
1030         char *buf = NULL;
1031
1032         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
1033                                    get_global_winbindd_state_offline() ? 
1034                                    "Offline":"Online")) == NULL) {
1035                 return NULL;
1036         }
1037
1038         for (domain = domain_list(); domain; domain = domain->next) {
1039                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
1040                                                   domain->name, 
1041                                                   domain->online ?
1042                                                   "Online":"Offline")) == NULL) {
1043                         return NULL;
1044                 }
1045         }
1046
1047         buf = talloc_asprintf_append_buffer(buf, "\n");
1048
1049         DEBUG(5,("collect_onlinestatus: %s", buf));
1050
1051         return buf;
1052 }
1053
1054 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
1055                               void *private_data,
1056                               uint32_t msg_type,
1057                               struct server_id server_id,
1058                               DATA_BLOB *data)
1059 {
1060         TALLOC_CTX *mem_ctx;
1061         const char *message;
1062
1063         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
1064
1065         mem_ctx = talloc_init("winbind_msg_onlinestatus");
1066         if (mem_ctx == NULL) {
1067                 return;
1068         }
1069
1070         message = collect_onlinestatus(mem_ctx);
1071         if (message == NULL) {
1072                 talloc_destroy(mem_ctx);
1073                 return;
1074         }
1075
1076         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_ONLINESTATUS,
1077                            (const uint8_t *)message, strlen(message) + 1);
1078
1079         talloc_destroy(mem_ctx);
1080 }
1081
1082 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
1083                                   void *private_data,
1084                                   uint32_t msg_type,
1085                                   struct server_id server_id,
1086                                   DATA_BLOB *data)
1087 {
1088         TALLOC_CTX *mem_ctx;
1089         const char *message = NULL;
1090         const char *domain = NULL;
1091         char *s = NULL;
1092         NTSTATUS status;
1093         struct winbindd_domain *dom = NULL;
1094
1095         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
1096
1097         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
1098         if (!mem_ctx) {
1099                 return;
1100         }
1101
1102         if (data->length > 0) {
1103                 domain = (const char *)data->data;
1104         }
1105
1106         if (domain) {
1107
1108                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
1109                         domain));
1110
1111                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
1112                                                   find_domain_from_name_noinit(domain));
1113                 if (!message) {
1114                         talloc_destroy(mem_ctx);
1115                         return;
1116                 }
1117
1118                 messaging_send_buf(msg_ctx, server_id,
1119                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
1120                                    (const uint8_t *)message, strlen(message) + 1);
1121
1122                 talloc_destroy(mem_ctx);
1123
1124                 return;
1125         }
1126
1127         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
1128
1129         for (dom = domain_list(); dom; dom=dom->next) {
1130                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
1131                 if (!message) {
1132                         talloc_destroy(mem_ctx);
1133                         return;
1134                 }
1135
1136                 s = talloc_asprintf_append(s, "%s\n", message);
1137                 if (!s) {
1138                         talloc_destroy(mem_ctx);
1139                         return;
1140                 }
1141         }
1142
1143         status = messaging_send_buf(msg_ctx, server_id,
1144                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
1145                                     (uint8_t *)s, strlen(s) + 1);
1146         if (!NT_STATUS_IS_OK(status)) {
1147                 DEBUG(0,("failed to send message: %s\n",
1148                 nt_errstr(status)));
1149         }
1150
1151         talloc_destroy(mem_ctx);
1152 }
1153
1154 static void account_lockout_policy_handler(struct tevent_context *ctx,
1155                                            struct tevent_timer *te,
1156                                            struct timeval now,
1157                                            void *private_data)
1158 {
1159         struct winbindd_child *child =
1160                 (struct winbindd_child *)private_data;
1161         TALLOC_CTX *mem_ctx = NULL;
1162         struct samr_DomInfo12 lockout_policy;
1163         NTSTATUS result;
1164
1165         DEBUG(10,("account_lockout_policy_handler called\n"));
1166
1167         TALLOC_FREE(child->lockout_policy_event);
1168
1169         if ( !winbindd_can_contact_domain( child->domain ) ) {
1170                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
1171                           "do not have an incoming trust to domain %s\n", 
1172                           child->domain->name));
1173
1174                 return;         
1175         }
1176
1177         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
1178         if (!mem_ctx) {
1179                 result = NT_STATUS_NO_MEMORY;
1180         } else {
1181                 result = wb_cache_lockout_policy(child->domain, mem_ctx,
1182                                                  &lockout_policy);
1183         }
1184         TALLOC_FREE(mem_ctx);
1185
1186         if (!NT_STATUS_IS_OK(result)) {
1187                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
1188                          nt_errstr(result)));
1189         }
1190
1191         child->lockout_policy_event = tevent_add_timer(global_event_context(), NULL,
1192                                                       timeval_current_ofs(3600, 0),
1193                                                       account_lockout_policy_handler,
1194                                                       child);
1195 }
1196
1197 static time_t get_machine_password_timeout(void)
1198 {
1199         /* until we have gpo support use lp setting */
1200         return lp_machine_password_timeout();
1201 }
1202
1203 static bool calculate_next_machine_pwd_change(const char *domain,
1204                                               struct timeval *t)
1205 {
1206         time_t pass_last_set_time;
1207         time_t timeout;
1208         time_t next_change;
1209         struct timeval tv;
1210         char *pw;
1211
1212         pw = secrets_fetch_machine_password(domain,
1213                                             &pass_last_set_time,
1214                                             NULL);
1215
1216         if (pw == NULL) {
1217                 DEBUG(0,("cannot fetch own machine password ????"));
1218                 return false;
1219         }
1220
1221         SAFE_FREE(pw);
1222
1223         timeout = get_machine_password_timeout();
1224         if (timeout == 0) {
1225                 DEBUG(10,("machine password never expires\n"));
1226                 return false;
1227         }
1228
1229         tv.tv_sec = pass_last_set_time;
1230         DEBUG(10, ("password last changed %s\n",
1231                    timeval_string(talloc_tos(), &tv, false)));
1232         tv.tv_sec += timeout;
1233         DEBUGADD(10, ("password valid until %s\n",
1234                       timeval_string(talloc_tos(), &tv, false)));
1235
1236         if (time(NULL) < (pass_last_set_time + timeout)) {
1237                 next_change = pass_last_set_time + timeout;
1238                 DEBUG(10,("machine password still valid until: %s\n",
1239                         http_timestring(talloc_tos(), next_change)));
1240                 *t = timeval_set(next_change, 0);
1241
1242                 if (lp_clustering()) {
1243                         uint8_t randbuf;
1244                         /*
1245                          * When having a cluster, we have several
1246                          * winbinds racing for the password change. In
1247                          * the machine_password_change_handler()
1248                          * function we check if someone else was
1249                          * faster when the event triggers. We add a
1250                          * 255-second random delay here, so that we
1251                          * don't run to change the password at the
1252                          * exact same moment.
1253                          */
1254                         generate_random_buffer(&randbuf, sizeof(randbuf));
1255                         DEBUG(10, ("adding %d seconds randomness\n",
1256                                    (int)randbuf));
1257                         t->tv_sec += randbuf;
1258                 }
1259                 return true;
1260         }
1261
1262         DEBUG(10,("machine password expired, needs immediate change\n"));
1263
1264         *t = timeval_zero();
1265
1266         return true;
1267 }
1268
1269 static void machine_password_change_handler(struct tevent_context *ctx,
1270                                             struct tevent_timer *te,
1271                                             struct timeval now,
1272                                             void *private_data)
1273 {
1274         struct messaging_context *msg_ctx = global_messaging_context();
1275         struct winbindd_child *child =
1276                 (struct winbindd_child *)private_data;
1277         struct rpc_pipe_client *netlogon_pipe = NULL;
1278         struct netlogon_creds_cli_context *netlogon_creds_ctx = NULL;
1279         NTSTATUS result;
1280         struct timeval next_change;
1281
1282         DEBUG(10,("machine_password_change_handler called\n"));
1283
1284         TALLOC_FREE(child->machine_password_change_event);
1285
1286         if (!calculate_next_machine_pwd_change(child->domain->name,
1287                                                &next_change)) {
1288                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1289                 return;
1290         }
1291
1292         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1293                    timeval_string(talloc_tos(), &next_change, false)));
1294
1295         if (!timeval_expired(&next_change)) {
1296                 DEBUG(10, ("Someone else has already changed the pw\n"));
1297                 goto done;
1298         }
1299
1300         if (!winbindd_can_contact_domain(child->domain)) {
1301                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
1302                           "do not have an incoming trust to domain %s\n",
1303                           child->domain->name));
1304                 return;
1305         }
1306
1307         result = cm_connect_netlogon_secure(child->domain,
1308                                             &netlogon_pipe,
1309                                             &netlogon_creds_ctx);
1310         if (!NT_STATUS_IS_OK(result)) {
1311                 DEBUG(10,("machine_password_change_handler: "
1312                         "failed to connect netlogon pipe: %s\n",
1313                          nt_errstr(result)));
1314                 return;
1315         }
1316
1317         result = trust_pw_change(netlogon_creds_ctx,
1318                                  msg_ctx,
1319                                  netlogon_pipe->binding_handle,
1320                                  child->domain->name,
1321                                  child->domain->dcname,
1322                                  false); /* force */
1323
1324         DEBUG(10, ("machine_password_change_handler: "
1325                    "trust_pw_change returned %s\n",
1326                    nt_errstr(result)));
1327
1328         if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1329                 DEBUG(3,("machine_password_change_handler: password set returned "
1330                          "ACCESS_DENIED.  Maybe the trust account "
1331                          "password was changed and we didn't know it. "
1332                          "Killing connections to domain %s\n",
1333                          child->domain->name));
1334                 invalidate_cm_connection(child->domain);
1335         }
1336
1337         if (!calculate_next_machine_pwd_change(child->domain->name,
1338                                                &next_change)) {
1339                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1340                 return;
1341         }
1342
1343         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1344                    timeval_string(talloc_tos(), &next_change, false)));
1345
1346         if (!NT_STATUS_IS_OK(result)) {
1347                 struct timeval tmp;
1348                 /*
1349                  * In case of failure, give the DC a minute to recover
1350                  */
1351                 tmp = timeval_current_ofs(60, 0);
1352                 next_change = timeval_max(&next_change, &tmp);
1353         }
1354
1355 done:
1356         child->machine_password_change_event = tevent_add_timer(global_event_context(), NULL,
1357                                                               next_change,
1358                                                               machine_password_change_handler,
1359                                                               child);
1360 }
1361
1362 /* Deal with a request to go offline. */
1363
1364 static void child_msg_offline(struct messaging_context *msg,
1365                               void *private_data,
1366                               uint32_t msg_type,
1367                               struct server_id server_id,
1368                               DATA_BLOB *data)
1369 {
1370         struct winbindd_domain *domain;
1371         struct winbindd_domain *primary_domain = NULL;
1372         const char *domainname = (const char *)data->data;
1373
1374         if (data->data == NULL || data->length == 0) {
1375                 return;
1376         }
1377
1378         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
1379
1380         if (!lp_winbind_offline_logon()) {
1381                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
1382                 return;
1383         }
1384
1385         primary_domain = find_our_domain();
1386
1387         /* Mark the requested domain offline. */
1388
1389         for (domain = domain_list(); domain; domain = domain->next) {
1390                 if (domain->internal) {
1391                         continue;
1392                 }
1393                 if (strequal(domain->name, domainname)) {
1394                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1395                         set_domain_offline(domain);
1396                         /* we are in the trusted domain, set the primary domain 
1397                          * offline too */
1398                         if (domain != primary_domain) {
1399                                 set_domain_offline(primary_domain);
1400                         }
1401                 }
1402         }
1403 }
1404
1405 /* Deal with a request to go online. */
1406
1407 static void child_msg_online(struct messaging_context *msg,
1408                              void *private_data,
1409                              uint32_t msg_type,
1410                              struct server_id server_id,
1411                              DATA_BLOB *data)
1412 {
1413         struct winbindd_domain *domain;
1414         struct winbindd_domain *primary_domain = NULL;
1415         const char *domainname = (const char *)data->data;
1416
1417         if (data->data == NULL || data->length == 0) {
1418                 return;
1419         }
1420
1421         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1422
1423         if (!lp_winbind_offline_logon()) {
1424                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1425                 return;
1426         }
1427
1428         primary_domain = find_our_domain();
1429
1430         /* Set our global state as online. */
1431         set_global_winbindd_state_online();
1432
1433         /* Try and mark everything online - delete any negative cache entries
1434            to force a reconnect now. */
1435
1436         for (domain = domain_list(); domain; domain = domain->next) {
1437                 if (domain->internal) {
1438                         continue;
1439                 }
1440                 if (strequal(domain->name, domainname)) {
1441                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1442                         winbindd_flush_negative_conn_cache(domain);
1443                         set_domain_online_request(domain);
1444
1445                         /* we can be in trusted domain, which will contact primary domain
1446                          * we have to bring primary domain online in trusted domain process
1447                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1448                          * --> contact_domain = find_our_domain()
1449                          * */
1450                         if (domain != primary_domain) {
1451                                 winbindd_flush_negative_conn_cache(primary_domain);
1452                                 set_domain_online_request(primary_domain);
1453                         }
1454                 }
1455         }
1456 }
1457
1458 struct winbindd_reinit_after_fork_state {
1459         const struct winbindd_child *myself;
1460 };
1461
1462 static bool winbindd_reinit_after_fork_fn(struct winbindd_child *child,
1463                                           void *private_data)
1464 {
1465         struct winbindd_reinit_after_fork_state *state = private_data;
1466
1467         if (child == state->myself) {
1468                 return true;
1469         }
1470
1471         /* Destroy all possible events in child list. */
1472         TALLOC_FREE(child->lockout_policy_event);
1473         TALLOC_FREE(child->machine_password_change_event);
1474
1475         /*
1476          * Children should never be able to send each other messages,
1477          * all messages must go through the parent.
1478          */
1479         child->pid = (pid_t)0;
1480
1481         /*
1482          * Close service sockets to all other children
1483          */
1484         if (child->sock != -1) {
1485                 close(child->sock);
1486                 child->sock = -1;
1487         }
1488
1489         return true;
1490 }
1491
1492 NTSTATUS winbindd_reinit_after_fork(const struct winbindd_child *myself,
1493                                     const char *logfilename)
1494 {
1495         struct winbindd_reinit_after_fork_state state = { .myself = myself };
1496         struct winbindd_domain *domain;
1497         NTSTATUS status;
1498
1499         status = reinit_after_fork(
1500                 global_messaging_context(),
1501                 global_event_context(),
1502                 true, NULL);
1503         if (!NT_STATUS_IS_OK(status)) {
1504                 DEBUG(0,("reinit_after_fork() failed\n"));
1505                 return status;
1506         }
1507         initialize_password_db(true, global_event_context());
1508
1509         close_conns_after_fork();
1510
1511         if (!override_logfile && logfilename) {
1512                 lp_set_logfile(logfilename);
1513                 reopen_logs();
1514         }
1515
1516         if (!winbindd_setup_sig_term_handler(false))
1517                 return NT_STATUS_NO_MEMORY;
1518         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1519                                             logfilename))
1520                 return NT_STATUS_NO_MEMORY;
1521
1522         /* Stop zombies in children */
1523         CatchChild();
1524
1525         /* Don't handle the same messages as our parent. */
1526         messaging_deregister(global_messaging_context(),
1527                              MSG_SMB_CONF_UPDATED, NULL);
1528         messaging_deregister(global_messaging_context(),
1529                              MSG_SHUTDOWN, NULL);
1530         messaging_deregister(global_messaging_context(),
1531                              MSG_WINBIND_OFFLINE, NULL);
1532         messaging_deregister(global_messaging_context(),
1533                              MSG_WINBIND_ONLINE, NULL);
1534         messaging_deregister(global_messaging_context(),
1535                              MSG_WINBIND_ONLINESTATUS, NULL);
1536         messaging_deregister(global_messaging_context(),
1537                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1538         messaging_deregister(global_messaging_context(),
1539                              MSG_DEBUG, NULL);
1540
1541         messaging_deregister(global_messaging_context(),
1542                              MSG_WINBIND_DOMAIN_OFFLINE, NULL);
1543         messaging_deregister(global_messaging_context(),
1544                              MSG_WINBIND_DOMAIN_ONLINE, NULL);
1545
1546         /* We have destroyed all events in the winbindd_event_context
1547          * in reinit_after_fork(), so clean out all possible pending
1548          * event pointers. */
1549
1550         /* Deal with check_online_events. */
1551
1552         for (domain = domain_list(); domain; domain = domain->next) {
1553                 TALLOC_FREE(domain->check_online_event);
1554         }
1555
1556         /* Ensure we're not handling a credential cache event inherited
1557          * from our parent. */
1558
1559         ccache_remove_all_after_fork();
1560
1561         forall_children(winbindd_reinit_after_fork_fn, &state);
1562
1563         return NT_STATUS_OK;
1564 }
1565
1566 /*
1567  * In a child there will be only one domain, reference that here.
1568  */
1569 static struct winbindd_domain *child_domain;
1570
1571 struct winbindd_domain *wb_child_domain(void)
1572 {
1573         return child_domain;
1574 }
1575
1576 struct child_handler_state {
1577         struct winbindd_child *child;
1578         struct winbindd_cli_state cli;
1579 };
1580
1581 static void child_handler(struct tevent_context *ev, struct tevent_fd *fde,
1582                           uint16_t flags, void *private_data)
1583 {
1584         struct child_handler_state *state =
1585                 (struct child_handler_state *)private_data;
1586         NTSTATUS status;
1587
1588         /* fetch a request from the main daemon */
1589         status = child_read_request(state->cli.sock, state->cli.request);
1590
1591         if (!NT_STATUS_IS_OK(status)) {
1592                 /* we lost contact with our parent */
1593                 _exit(0);
1594         }
1595
1596         DEBUG(4,("child daemon request %d\n",
1597                  (int)state->cli.request->cmd));
1598
1599         ZERO_STRUCTP(state->cli.response);
1600         state->cli.request->null_term = '\0';
1601         state->cli.mem_ctx = talloc_tos();
1602         child_process_request(state->child, &state->cli);
1603
1604         DEBUG(4, ("Finished processing child request %d\n",
1605                   (int)state->cli.request->cmd));
1606
1607         SAFE_FREE(state->cli.request->extra_data.data);
1608
1609         status = child_write_response(state->cli.sock, state->cli.response);
1610         if (!NT_STATUS_IS_OK(status)) {
1611                 exit(1);
1612         }
1613 }
1614
1615 static bool fork_domain_child(struct winbindd_child *child)
1616 {
1617         int fdpair[2];
1618         struct child_handler_state state;
1619         struct winbindd_request request;
1620         struct winbindd_response response;
1621         struct winbindd_domain *primary_domain = NULL;
1622         NTSTATUS status;
1623         ssize_t nwritten;
1624         struct tevent_fd *fde;
1625
1626         if (child->domain) {
1627                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1628                            child->domain->name));
1629         } else {
1630                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1631         }
1632
1633         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1634                 DEBUG(0, ("Could not open child pipe: %s\n",
1635                           strerror(errno)));
1636                 return False;
1637         }
1638
1639         ZERO_STRUCT(state);
1640         state.child = child;
1641         state.cli.pid = getpid();
1642         state.cli.request = &request;
1643         state.cli.response = &response;
1644
1645         child->pid = fork();
1646
1647         if (child->pid == -1) {
1648                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1649                 close(fdpair[0]);
1650                 close(fdpair[1]);
1651                 return False;
1652         }
1653
1654         if (child->pid != 0) {
1655                 /* Parent */
1656                 ssize_t nread;
1657
1658                 close(fdpair[0]);
1659
1660                 nread = sys_read(fdpair[1], &status, sizeof(status));
1661                 if (nread != sizeof(status)) {
1662                         DEBUG(1, ("fork_domain_child: Could not read child status: "
1663                                   "nread=%d, error=%s\n", (int)nread,
1664                                   strerror(errno)));
1665                         close(fdpair[1]);
1666                         return false;
1667                 }
1668                 if (!NT_STATUS_IS_OK(status)) {
1669                         DEBUG(1, ("fork_domain_child: Child status is %s\n",
1670                                   nt_errstr(status)));
1671                         close(fdpair[1]);
1672                         return false;
1673                 }
1674
1675                 child->monitor_fde = tevent_add_fd(global_event_context(),
1676                                                    global_event_context(),
1677                                                    fdpair[1],
1678                                                    TEVENT_FD_READ,
1679                                                    child_socket_readable,
1680                                                    child);
1681                 if (child->monitor_fde == NULL) {
1682                         DBG_WARNING("tevent_add_fd failed\n");
1683                         close(fdpair[1]);
1684                         return false;
1685                 }
1686
1687                 child->sock = fdpair[1];
1688                 return True;
1689         }
1690
1691         /* Child */
1692         child_domain = child->domain;
1693
1694         DEBUG(10, ("Child process %d\n", (int)getpid()));
1695
1696         state.cli.sock = fdpair[0];
1697         close(fdpair[1]);
1698
1699         status = winbindd_reinit_after_fork(child, child->logfilename);
1700
1701         nwritten = sys_write(state.cli.sock, &status, sizeof(status));
1702         if (nwritten != sizeof(status)) {
1703                 DEBUG(1, ("fork_domain_child: Could not write status: "
1704                           "nwritten=%d, error=%s\n", (int)nwritten,
1705                           strerror(errno)));
1706                 _exit(0);
1707         }
1708         if (!NT_STATUS_IS_OK(status)) {
1709                 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
1710                           nt_errstr(status)));
1711                 _exit(0);
1712         }
1713
1714         if (child_domain != NULL) {
1715                 setproctitle("domain child [%s]", child_domain->name);
1716         } else if (child == idmap_child()) {
1717                 setproctitle("idmap child");
1718         }
1719
1720         /* Handle online/offline messages. */
1721         messaging_register(global_messaging_context(), NULL,
1722                            MSG_WINBIND_OFFLINE, child_msg_offline);
1723         messaging_register(global_messaging_context(), NULL,
1724                            MSG_WINBIND_ONLINE, child_msg_online);
1725         messaging_register(global_messaging_context(), NULL,
1726                            MSG_DEBUG, debug_message);
1727         messaging_register(global_messaging_context(), NULL,
1728                            MSG_WINBIND_IP_DROPPED,
1729                            winbind_msg_ip_dropped);
1730         messaging_register(global_messaging_context(), NULL,
1731                            MSG_WINBIND_DISCONNECT_DC,
1732                            winbind_msg_disconnect_dc);
1733
1734         primary_domain = find_our_domain();
1735
1736         if (primary_domain == NULL) {
1737                 smb_panic("no primary domain found");
1738         }
1739
1740         /* It doesn't matter if we allow cache login,
1741          * try to bring domain online after fork. */
1742         if ( child->domain ) {
1743                 child->domain->startup = True;
1744                 child->domain->startup_time = time_mono(NULL);
1745                 /* we can be in primary domain or in trusted domain
1746                  * If we are in trusted domain, set the primary domain
1747                  * in start-up mode */
1748                 if (!(child->domain->internal)) {
1749                         set_domain_online_request(child->domain);
1750                         if (!(child->domain->primary)) {
1751                                 primary_domain->startup = True;
1752                                 primary_domain->startup_time = time_mono(NULL);
1753                                 set_domain_online_request(primary_domain);
1754                         }
1755                 }
1756         }
1757
1758         /*
1759          * We are in idmap child, make sure that we set the
1760          * check_online_event to bring primary domain online.
1761          */
1762         if (child == idmap_child()) {
1763                 set_domain_online_request(primary_domain);
1764         }
1765
1766         /* We might be in the idmap child...*/
1767         if (child->domain && !(child->domain->internal) &&
1768             lp_winbind_offline_logon()) {
1769
1770                 set_domain_online_request(child->domain);
1771
1772                 if (primary_domain && (primary_domain != child->domain)) {
1773                         /* We need to talk to the primary
1774                          * domain as well as the trusted
1775                          * domain inside a trusted domain
1776                          * child.
1777                          * See the code in :
1778                          * set_dc_type_and_flags_trustinfo()
1779                          * for details.
1780                          */
1781                         set_domain_online_request(primary_domain);
1782                 }
1783
1784                 child->lockout_policy_event = tevent_add_timer(
1785                         global_event_context(), NULL, timeval_zero(),
1786                         account_lockout_policy_handler,
1787                         child);
1788         }
1789
1790         if (child->domain && child->domain->primary &&
1791             !USE_KERBEROS_KEYTAB &&
1792             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1793
1794                 struct timeval next_change;
1795
1796                 if (calculate_next_machine_pwd_change(child->domain->name,
1797                                                        &next_change)) {
1798                         child->machine_password_change_event = tevent_add_timer(
1799                                 global_event_context(), NULL, next_change,
1800                                 machine_password_change_handler,
1801                                 child);
1802                 }
1803         }
1804
1805         fde = tevent_add_fd(global_event_context(), NULL, state.cli.sock,
1806                             TEVENT_FD_READ, child_handler, &state);
1807         if (fde == NULL) {
1808                 DEBUG(1, ("tevent_add_fd failed\n"));
1809                 _exit(1);
1810         }
1811
1812         while (1) {
1813
1814                 int ret;
1815                 TALLOC_CTX *frame = talloc_stackframe();
1816
1817                 ret = tevent_loop_once(global_event_context());
1818                 if (ret != 0) {
1819                         DEBUG(1, ("tevent_loop_once failed: %s\n",
1820                                   strerror(errno)));
1821                         _exit(1);
1822                 }
1823
1824                 if (child->domain && child->domain->startup &&
1825                                 (time_mono(NULL) > child->domain->startup_time + 30)) {
1826                         /* No longer in "startup" mode. */
1827                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1828                                 child->domain->name ));
1829                         child->domain->startup = False;
1830                 }
1831
1832                 TALLOC_FREE(frame);
1833         }
1834 }
1835
1836 void winbind_msg_ip_dropped_parent(struct messaging_context *msg_ctx,
1837                                    void *private_data,
1838                                    uint32_t msg_type,
1839                                    struct server_id server_id,
1840                                    DATA_BLOB *data)
1841 {
1842         struct winbind_msg_relay_state state = {
1843                 .msg_ctx = msg_ctx,
1844                 .msg_type = msg_type,
1845                 .data = data,
1846         };
1847
1848         winbind_msg_ip_dropped(msg_ctx, private_data, msg_type,
1849                                server_id, data);
1850
1851         forall_children(winbind_msg_relay_fn, &state);
1852 }