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