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