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