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