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