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