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