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