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