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