s3: Use poll in winbind
[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 "librpc/gen_ndr/messaging.h"
34 #include "secrets.h"
35 #include "../lib/util/select.h"
36 #include "../libcli/security/security.h"
37 #include "system/select.h"
38
39 #undef DBGC_CLASS
40 #define DBGC_CLASS DBGC_WINBIND
41
42 extern bool override_logfile;
43 extern struct winbindd_methods cache_methods;
44
45 /* Read some data from a client connection */
46
47 static NTSTATUS child_read_request(struct winbindd_cli_state *state)
48 {
49         NTSTATUS status;
50
51         /* Read data */
52
53         status = read_data(state->sock, (char *)state->request,
54                            sizeof(*state->request));
55
56         if (!NT_STATUS_IS_OK(status)) {
57                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
58                           nt_errstr(status)));
59                 return status;
60         }
61
62         if (state->request->extra_len == 0) {
63                 state->request->extra_data.data = NULL;
64                 return NT_STATUS_OK;
65         }
66
67         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request->extra_len));
68
69         state->request->extra_data.data =
70                 SMB_MALLOC_ARRAY(char, state->request->extra_len + 1);
71
72         if (state->request->extra_data.data == NULL) {
73                 DEBUG(0, ("malloc failed\n"));
74                 return NT_STATUS_NO_MEMORY;
75         }
76
77         /* Ensure null termination */
78         state->request->extra_data.data[state->request->extra_len] = '\0';
79
80         status= read_data(state->sock, state->request->extra_data.data,
81                           state->request->extra_len);
82
83         if (!NT_STATUS_IS_OK(status)) {
84                 DEBUG(0, ("Could not read extra data: %s\n",
85                           nt_errstr(status)));
86         }
87         return status;
88 }
89
90 /*
91  * Do winbind child async request. This is not simply wb_simple_trans. We have
92  * to do the queueing ourselves because while a request is queued, the child
93  * might have crashed, and we have to re-fork it in the _trigger function.
94  */
95
96 struct wb_child_request_state {
97         struct tevent_context *ev;
98         struct winbindd_child *child;
99         struct winbindd_request *request;
100         struct winbindd_response *response;
101 };
102
103 static bool fork_domain_child(struct winbindd_child *child);
104
105 static void wb_child_request_trigger(struct tevent_req *req,
106                                             void *private_data);
107 static void wb_child_request_done(struct tevent_req *subreq);
108
109 struct tevent_req *wb_child_request_send(TALLOC_CTX *mem_ctx,
110                                          struct tevent_context *ev,
111                                          struct winbindd_child *child,
112                                          struct winbindd_request *request)
113 {
114         struct tevent_req *req;
115         struct wb_child_request_state *state;
116
117         req = tevent_req_create(mem_ctx, &state,
118                                 struct wb_child_request_state);
119         if (req == NULL) {
120                 return NULL;
121         }
122
123         state->ev = ev;
124         state->child = child;
125         state->request = request;
126
127         if (!tevent_queue_add(child->queue, ev, req,
128                               wb_child_request_trigger, NULL)) {
129                 tevent_req_nomem(NULL, req);
130                 return tevent_req_post(req, ev);
131         }
132         return req;
133 }
134
135 static void wb_child_request_trigger(struct tevent_req *req,
136                                      void *private_data)
137 {
138         struct wb_child_request_state *state = tevent_req_data(
139                 req, struct wb_child_request_state);
140         struct tevent_req *subreq;
141
142         if ((state->child->sock == -1) && (!fork_domain_child(state->child))) {
143                 tevent_req_error(req, errno);
144                 return;
145         }
146
147         subreq = wb_simple_trans_send(state, winbind_event_context(), NULL,
148                                       state->child->sock, state->request);
149         if (tevent_req_nomem(subreq, req)) {
150                 return;
151         }
152         tevent_req_set_callback(subreq, wb_child_request_done, req);
153
154         if (!tevent_req_set_endtime(req, state->ev,
155                                     timeval_current_ofs(300, 0))) {
156                 tevent_req_nomem(NULL, req);
157                 return;
158         }
159 }
160
161 static void wb_child_request_done(struct tevent_req *subreq)
162 {
163         struct tevent_req *req = tevent_req_callback_data(
164                 subreq, struct tevent_req);
165         struct wb_child_request_state *state = tevent_req_data(
166                 req, struct wb_child_request_state);
167         int ret, err;
168
169         ret = wb_simple_trans_recv(subreq, state, &state->response, &err);
170         TALLOC_FREE(subreq);
171         if (ret == -1) {
172                 /*
173                  * The basic parent/child communication broke, close
174                  * our socket
175                  */
176                 close(state->child->sock);
177                 state->child->sock = -1;
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()) {
460                         char *end = NULL;
461
462                         if (asprintf(&logbase, "%s", lp_logfile()) < 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 static struct winbindd_child *winbindd_children = NULL;
497
498 void winbind_child_died(pid_t pid)
499 {
500         struct winbindd_child *child;
501
502         for (child = winbindd_children; child != NULL; child = child->next) {
503                 if (child->pid == pid) {
504                         break;
505                 }
506         }
507
508         if (child == NULL) {
509                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
510                 return;
511         }
512
513         /* This will be re-added in fork_domain_child() */
514
515         DLIST_REMOVE(winbindd_children, child);
516         child->pid = 0;
517 }
518
519 /* Ensure any negative cache entries with the netbios or realm names are removed. */
520
521 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
522 {
523         flush_negative_conn_cache_for_domain(domain->name);
524         if (*domain->alt_name) {
525                 flush_negative_conn_cache_for_domain(domain->alt_name);
526         }
527 }
528
529 /* 
530  * Parent winbindd process sets its own debug level first and then
531  * sends a message to all the winbindd children to adjust their debug
532  * level to that of parents.
533  */
534
535 void winbind_msg_debug(struct messaging_context *msg_ctx,
536                          void *private_data,
537                          uint32_t msg_type,
538                          struct server_id server_id,
539                          DATA_BLOB *data)
540 {
541         struct winbindd_child *child;
542
543         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
544
545         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
546
547         for (child = winbindd_children; child != NULL; child = child->next) {
548
549                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
550                         (unsigned int)child->pid));
551
552                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
553                            MSG_DEBUG,
554                            data->data,
555                            strlen((char *) data->data) + 1);
556         }
557 }
558
559 /* Set our domains as offline and forward the offline message to our children. */
560
561 void winbind_msg_offline(struct messaging_context *msg_ctx,
562                          void *private_data,
563                          uint32_t msg_type,
564                          struct server_id server_id,
565                          DATA_BLOB *data)
566 {
567         struct winbindd_child *child;
568         struct winbindd_domain *domain;
569
570         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
571
572         if (!lp_winbind_offline_logon()) {
573                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
574                 return;
575         }
576
577         /* Set our global state as offline. */
578         if (!set_global_winbindd_state_offline()) {
579                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
580                 return;
581         }
582
583         /* Set all our domains as offline. */
584         for (domain = domain_list(); domain; domain = domain->next) {
585                 if (domain->internal) {
586                         continue;
587                 }
588                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
589                 set_domain_offline(domain);
590         }
591
592         for (child = winbindd_children; child != NULL; child = child->next) {
593                 /* Don't send message to internal children.  We've already
594                    done so above. */
595                 if (!child->domain || winbindd_internal_child(child)) {
596                         continue;
597                 }
598
599                 /* Or internal domains (this should not be possible....) */
600                 if (child->domain->internal) {
601                         continue;
602                 }
603
604                 /* Each winbindd child should only process requests for one domain - make sure
605                    we only set it online / offline for that domain. */
606
607                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
608                         (unsigned int)child->pid, domain->name ));
609
610                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
611                                    MSG_WINBIND_OFFLINE,
612                                    (uint8 *)child->domain->name,
613                                    strlen(child->domain->name)+1);
614         }
615 }
616
617 /* Set our domains as online and forward the online message to our children. */
618
619 void winbind_msg_online(struct messaging_context *msg_ctx,
620                         void *private_data,
621                         uint32_t msg_type,
622                         struct server_id server_id,
623                         DATA_BLOB *data)
624 {
625         struct winbindd_child *child;
626         struct winbindd_domain *domain;
627
628         DEBUG(10,("winbind_msg_online: got online message.\n"));
629
630         if (!lp_winbind_offline_logon()) {
631                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
632                 return;
633         }
634
635         /* Set our global state as online. */
636         set_global_winbindd_state_online();
637
638         smb_nscd_flush_user_cache();
639         smb_nscd_flush_group_cache();
640
641         /* Set all our domains as online. */
642         for (domain = domain_list(); domain; domain = domain->next) {
643                 if (domain->internal) {
644                         continue;
645                 }
646                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
647
648                 winbindd_flush_negative_conn_cache(domain);
649                 set_domain_online_request(domain);
650
651                 /* Send an online message to the idmap child when our
652                    primary domain comes back online */
653
654                 if ( domain->primary ) {
655                         struct winbindd_child *idmap = idmap_child();
656
657                         if ( idmap->pid != 0 ) {
658                                 messaging_send_buf(msg_ctx,
659                                                    pid_to_procid(idmap->pid), 
660                                                    MSG_WINBIND_ONLINE,
661                                                    (uint8 *)domain->name,
662                                                    strlen(domain->name)+1);
663                         }
664                 }
665         }
666
667         for (child = winbindd_children; child != NULL; child = child->next) {
668                 /* Don't send message to internal childs. */
669                 if (!child->domain || winbindd_internal_child(child)) {
670                         continue;
671                 }
672
673                 /* Or internal domains (this should not be possible....) */
674                 if (child->domain->internal) {
675                         continue;
676                 }
677
678                 /* Each winbindd child should only process requests for one domain - make sure
679                    we only set it online / offline for that domain. */
680
681                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
682                         (unsigned int)child->pid, child->domain->name ));
683
684                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
685                                    MSG_WINBIND_ONLINE,
686                                    (uint8 *)child->domain->name,
687                                    strlen(child->domain->name)+1);
688         }
689 }
690
691 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
692 {
693         struct winbindd_domain *domain;
694         char *buf = NULL;
695
696         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
697                                    get_global_winbindd_state_offline() ? 
698                                    "Offline":"Online")) == NULL) {
699                 return NULL;
700         }
701
702         for (domain = domain_list(); domain; domain = domain->next) {
703                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
704                                                   domain->name, 
705                                                   domain->online ?
706                                                   "Online":"Offline")) == NULL) {
707                         return NULL;
708                 }
709         }
710
711         buf = talloc_asprintf_append_buffer(buf, "\n");
712
713         DEBUG(5,("collect_onlinestatus: %s", buf));
714
715         return buf;
716 }
717
718 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
719                               void *private_data,
720                               uint32_t msg_type,
721                               struct server_id server_id,
722                               DATA_BLOB *data)
723 {
724         TALLOC_CTX *mem_ctx;
725         const char *message;
726         struct server_id *sender;
727
728         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
729
730         if (!data->data) {
731                 return;
732         }
733
734         sender = (struct server_id *)data->data;
735
736         mem_ctx = talloc_init("winbind_msg_onlinestatus");
737         if (mem_ctx == NULL) {
738                 return;
739         }
740
741         message = collect_onlinestatus(mem_ctx);
742         if (message == NULL) {
743                 talloc_destroy(mem_ctx);
744                 return;
745         }
746
747         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
748                            (uint8 *)message, strlen(message) + 1);
749
750         talloc_destroy(mem_ctx);
751 }
752
753 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
754                                  void *private_data,
755                                  uint32_t msg_type,
756                                  struct server_id server_id,
757                                  DATA_BLOB *data)
758 {
759         struct winbindd_child *child;
760
761         DEBUG(10,("winbind_msg_dump_event_list received\n"));
762
763         dump_event_list(winbind_event_context());
764
765         for (child = winbindd_children; child != NULL; child = child->next) {
766
767                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
768                         (unsigned int)child->pid));
769
770                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
771                                    MSG_DUMP_EVENT_LIST,
772                                    NULL, 0);
773         }
774
775 }
776
777 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
778                                   void *private_data,
779                                   uint32_t msg_type,
780                                   struct server_id server_id,
781                                   DATA_BLOB *data)
782 {
783         TALLOC_CTX *mem_ctx;
784         const char *message = NULL;
785         struct server_id *sender = NULL;
786         const char *domain = NULL;
787         char *s = NULL;
788         NTSTATUS status;
789         struct winbindd_domain *dom = NULL;
790
791         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
792
793         if (!data || !data->data) {
794                 return;
795         }
796
797         if (data->length < sizeof(struct server_id)) {
798                 return;
799         }
800
801         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
802         if (!mem_ctx) {
803                 return;
804         }
805
806         sender = (struct server_id *)data->data;
807         if (data->length > sizeof(struct server_id)) {
808                 domain = (const char *)data->data+sizeof(struct server_id);
809         }
810
811         if (domain) {
812
813                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
814                         domain));
815
816                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
817                                                   find_domain_from_name_noinit(domain));
818                 if (!message) {
819                         talloc_destroy(mem_ctx);
820                         return;
821                 }
822
823                 messaging_send_buf(msg_ctx, *sender,
824                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
825                                    (uint8_t *)message, strlen(message) + 1);
826
827                 talloc_destroy(mem_ctx);
828
829                 return;
830         }
831
832         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
833
834         for (dom = domain_list(); dom; dom=dom->next) {
835                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
836                 if (!message) {
837                         talloc_destroy(mem_ctx);
838                         return;
839                 }
840
841                 s = talloc_asprintf_append(s, "%s\n", message);
842                 if (!s) {
843                         talloc_destroy(mem_ctx);
844                         return;
845                 }
846         }
847
848         status = messaging_send_buf(msg_ctx, *sender,
849                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
850                                     (uint8_t *)s, strlen(s) + 1);
851         if (!NT_STATUS_IS_OK(status)) {
852                 DEBUG(0,("failed to send message: %s\n",
853                 nt_errstr(status)));
854         }
855
856         talloc_destroy(mem_ctx);
857 }
858
859 static void account_lockout_policy_handler(struct event_context *ctx,
860                                            struct timed_event *te,
861                                            struct timeval now,
862                                            void *private_data)
863 {
864         struct winbindd_child *child =
865                 (struct winbindd_child *)private_data;
866         TALLOC_CTX *mem_ctx = NULL;
867         struct winbindd_methods *methods;
868         struct samr_DomInfo12 lockout_policy;
869         NTSTATUS result;
870
871         DEBUG(10,("account_lockout_policy_handler called\n"));
872
873         TALLOC_FREE(child->lockout_policy_event);
874
875         if ( !winbindd_can_contact_domain( child->domain ) ) {
876                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
877                           "do not have an incoming trust to domain %s\n", 
878                           child->domain->name));
879
880                 return;         
881         }
882
883         methods = child->domain->methods;
884
885         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
886         if (!mem_ctx) {
887                 result = NT_STATUS_NO_MEMORY;
888         } else {
889                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
890         }
891         TALLOC_FREE(mem_ctx);
892
893         if (!NT_STATUS_IS_OK(result)) {
894                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
895                          nt_errstr(result)));
896         }
897
898         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
899                                                       timeval_current_ofs(3600, 0),
900                                                       account_lockout_policy_handler,
901                                                       child);
902 }
903
904 static time_t get_machine_password_timeout(void)
905 {
906         /* until we have gpo support use lp setting */
907         return lp_machine_password_timeout();
908 }
909
910 static bool calculate_next_machine_pwd_change(const char *domain,
911                                               struct timeval *t)
912 {
913         time_t pass_last_set_time;
914         time_t timeout;
915         time_t next_change;
916         struct timeval tv;
917         char *pw;
918
919         pw = secrets_fetch_machine_password(domain,
920                                             &pass_last_set_time,
921                                             NULL);
922
923         if (pw == NULL) {
924                 DEBUG(0,("cannot fetch own machine password ????"));
925                 return false;
926         }
927
928         SAFE_FREE(pw);
929
930         timeout = get_machine_password_timeout();
931         if (timeout == 0) {
932                 DEBUG(10,("machine password never expires\n"));
933                 return false;
934         }
935
936         tv.tv_sec = pass_last_set_time;
937         DEBUG(10, ("password last changed %s\n",
938                    timeval_string(talloc_tos(), &tv, false)));
939         tv.tv_sec += timeout;
940         DEBUGADD(10, ("password valid until %s\n",
941                       timeval_string(talloc_tos(), &tv, false)));
942
943         if (time(NULL) < (pass_last_set_time + timeout)) {
944                 next_change = pass_last_set_time + timeout;
945                 DEBUG(10,("machine password still valid until: %s\n",
946                         http_timestring(talloc_tos(), next_change)));
947                 *t = timeval_set(next_change, 0);
948
949                 if (lp_clustering()) {
950                         uint8_t randbuf;
951                         /*
952                          * When having a cluster, we have several
953                          * winbinds racing for the password change. In
954                          * the machine_password_change_handler()
955                          * function we check if someone else was
956                          * faster when the event triggers. We add a
957                          * 255-second random delay here, so that we
958                          * don't run to change the password at the
959                          * exact same moment.
960                          */
961                         generate_random_buffer(&randbuf, sizeof(randbuf));
962                         DEBUG(10, ("adding %d seconds randomness\n",
963                                    (int)randbuf));
964                         t->tv_sec += randbuf;
965                 }
966                 return true;
967         }
968
969         DEBUG(10,("machine password expired, needs immediate change\n"));
970
971         *t = timeval_zero();
972
973         return true;
974 }
975
976 static void machine_password_change_handler(struct event_context *ctx,
977                                             struct timed_event *te,
978                                             struct timeval now,
979                                             void *private_data)
980 {
981         struct winbindd_child *child =
982                 (struct winbindd_child *)private_data;
983         struct rpc_pipe_client *netlogon_pipe = NULL;
984         TALLOC_CTX *frame;
985         NTSTATUS result;
986         struct timeval next_change;
987
988         DEBUG(10,("machine_password_change_handler called\n"));
989
990         TALLOC_FREE(child->machine_password_change_event);
991
992         if (!calculate_next_machine_pwd_change(child->domain->name,
993                                                &next_change)) {
994                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
995                 return;
996         }
997
998         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
999                    timeval_string(talloc_tos(), &next_change, false)));
1000
1001         if (!timeval_expired(&next_change)) {
1002                 DEBUG(10, ("Someone else has already changed the pw\n"));
1003                 goto done;
1004         }
1005
1006         if (!winbindd_can_contact_domain(child->domain)) {
1007                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
1008                           "do not have an incoming trust to domain %s\n",
1009                           child->domain->name));
1010                 return;
1011         }
1012
1013         result = cm_connect_netlogon(child->domain, &netlogon_pipe);
1014         if (!NT_STATUS_IS_OK(result)) {
1015                 DEBUG(10,("machine_password_change_handler: "
1016                         "failed to connect netlogon pipe: %s\n",
1017                          nt_errstr(result)));
1018                 return;
1019         }
1020
1021         frame = talloc_stackframe();
1022
1023         result = trust_pw_find_change_and_store_it(netlogon_pipe,
1024                                                    frame,
1025                                                    child->domain->name);
1026         TALLOC_FREE(frame);
1027
1028         DEBUG(10, ("machine_password_change_handler: "
1029                    "trust_pw_find_change_and_store_it returned %s\n",
1030                    nt_errstr(result)));
1031
1032         if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1033                 DEBUG(3,("machine_password_change_handler: password set returned "
1034                          "ACCESS_DENIED.  Maybe the trust account "
1035                          "password was changed and we didn't know it. "
1036                          "Killing connections to domain %s\n",
1037                          child->domain->name));
1038                 TALLOC_FREE(child->domain->conn.netlogon_pipe);
1039         }
1040
1041         if (!calculate_next_machine_pwd_change(child->domain->name,
1042                                                &next_change)) {
1043                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1044                 return;
1045         }
1046
1047         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1048                    timeval_string(talloc_tos(), &next_change, false)));
1049
1050         if (!NT_STATUS_IS_OK(result)) {
1051                 struct timeval tmp;
1052                 /*
1053                  * In case of failure, give the DC a minute to recover
1054                  */
1055                 tmp = timeval_current_ofs(60, 0);
1056                 next_change = timeval_max(&next_change, &tmp);
1057         }
1058
1059 done:
1060         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
1061                                                               next_change,
1062                                                               machine_password_change_handler,
1063                                                               child);
1064 }
1065
1066 /* Deal with a request to go offline. */
1067
1068 static void child_msg_offline(struct messaging_context *msg,
1069                               void *private_data,
1070                               uint32_t msg_type,
1071                               struct server_id server_id,
1072                               DATA_BLOB *data)
1073 {
1074         struct winbindd_domain *domain;
1075         struct winbindd_domain *primary_domain = NULL;
1076         const char *domainname = (const char *)data->data;
1077
1078         if (data->data == NULL || data->length == 0) {
1079                 return;
1080         }
1081
1082         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
1083
1084         if (!lp_winbind_offline_logon()) {
1085                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
1086                 return;
1087         }
1088
1089         primary_domain = find_our_domain();
1090
1091         /* Mark the requested domain offline. */
1092
1093         for (domain = domain_list(); domain; domain = domain->next) {
1094                 if (domain->internal) {
1095                         continue;
1096                 }
1097                 if (strequal(domain->name, domainname)) {
1098                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1099                         set_domain_offline(domain);
1100                         /* we are in the trusted domain, set the primary domain 
1101                          * offline too */
1102                         if (domain != primary_domain) {
1103                                 set_domain_offline(primary_domain);
1104                         }
1105                 }
1106         }
1107 }
1108
1109 /* Deal with a request to go online. */
1110
1111 static void child_msg_online(struct messaging_context *msg,
1112                              void *private_data,
1113                              uint32_t msg_type,
1114                              struct server_id server_id,
1115                              DATA_BLOB *data)
1116 {
1117         struct winbindd_domain *domain;
1118         struct winbindd_domain *primary_domain = NULL;
1119         const char *domainname = (const char *)data->data;
1120
1121         if (data->data == NULL || data->length == 0) {
1122                 return;
1123         }
1124
1125         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1126
1127         if (!lp_winbind_offline_logon()) {
1128                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1129                 return;
1130         }
1131
1132         primary_domain = find_our_domain();
1133
1134         /* Set our global state as online. */
1135         set_global_winbindd_state_online();
1136
1137         /* Try and mark everything online - delete any negative cache entries
1138            to force a reconnect now. */
1139
1140         for (domain = domain_list(); domain; domain = domain->next) {
1141                 if (domain->internal) {
1142                         continue;
1143                 }
1144                 if (strequal(domain->name, domainname)) {
1145                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1146                         winbindd_flush_negative_conn_cache(domain);
1147                         set_domain_online_request(domain);
1148
1149                         /* we can be in trusted domain, which will contact primary domain
1150                          * we have to bring primary domain online in trusted domain process
1151                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1152                          * --> contact_domain = find_our_domain()
1153                          * */
1154                         if (domain != primary_domain) {
1155                                 winbindd_flush_negative_conn_cache(primary_domain);
1156                                 set_domain_online_request(primary_domain);
1157                         }
1158                 }
1159         }
1160 }
1161
1162 static void child_msg_dump_event_list(struct messaging_context *msg,
1163                                       void *private_data,
1164                                       uint32_t msg_type,
1165                                       struct server_id server_id,
1166                                       DATA_BLOB *data)
1167 {
1168         DEBUG(5,("child_msg_dump_event_list received\n"));
1169
1170         dump_event_list(winbind_event_context());
1171 }
1172
1173 bool winbindd_reinit_after_fork(const char *logfilename)
1174 {
1175         struct winbindd_domain *domain;
1176         struct winbindd_child *cl;
1177         NTSTATUS status;
1178
1179         status = reinit_after_fork(
1180                 winbind_messaging_context(),
1181                 winbind_event_context(),
1182                 procid_self(),
1183                 true);
1184         if (!NT_STATUS_IS_OK(status)) {
1185                 DEBUG(0,("reinit_after_fork() failed\n"));
1186                 return false;
1187         }
1188
1189         close_conns_after_fork();
1190
1191         if (!override_logfile && logfilename) {
1192                 lp_set_logfile(logfilename);
1193                 reopen_logs();
1194         }
1195
1196         if (!winbindd_setup_sig_term_handler(false))
1197                 return false;
1198         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1199                                             logfilename))
1200                 return false;
1201
1202         /* Stop zombies in children */
1203         CatchChild();
1204
1205         /* Don't handle the same messages as our parent. */
1206         messaging_deregister(winbind_messaging_context(),
1207                              MSG_SMB_CONF_UPDATED, NULL);
1208         messaging_deregister(winbind_messaging_context(),
1209                              MSG_SHUTDOWN, NULL);
1210         messaging_deregister(winbind_messaging_context(),
1211                              MSG_WINBIND_OFFLINE, NULL);
1212         messaging_deregister(winbind_messaging_context(),
1213                              MSG_WINBIND_ONLINE, NULL);
1214         messaging_deregister(winbind_messaging_context(),
1215                              MSG_WINBIND_ONLINESTATUS, NULL);
1216         messaging_deregister(winbind_messaging_context(),
1217                              MSG_DUMP_EVENT_LIST, NULL);
1218         messaging_deregister(winbind_messaging_context(),
1219                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1220         messaging_deregister(winbind_messaging_context(),
1221                              MSG_DEBUG, NULL);
1222
1223         /* We have destroyed all events in the winbindd_event_context
1224          * in reinit_after_fork(), so clean out all possible pending
1225          * event pointers. */
1226
1227         /* Deal with check_online_events. */
1228
1229         for (domain = domain_list(); domain; domain = domain->next) {
1230                 TALLOC_FREE(domain->check_online_event);
1231         }
1232
1233         /* Ensure we're not handling a credential cache event inherited
1234          * from our parent. */
1235
1236         ccache_remove_all_after_fork();
1237
1238         /* Destroy all possible events in child list. */
1239         for (cl = winbindd_children; cl != NULL; cl = cl->next) {
1240                 TALLOC_FREE(cl->lockout_policy_event);
1241                 TALLOC_FREE(cl->machine_password_change_event);
1242
1243                 /* Children should never be able to send
1244                  * each other messages, all messages must
1245                  * go through the parent.
1246                  */
1247                 cl->pid = (pid_t)0;
1248         }
1249         /*
1250          * This is a little tricky, children must not
1251          * send an MSG_WINBIND_ONLINE message to idmap_child().
1252          * If we are in a child of our primary domain or
1253          * in the process created by fork_child_dc_connect(),
1254          * and the primary domain cannot go online,
1255          * fork_child_dc_connection() sends MSG_WINBIND_ONLINE
1256          * periodically to idmap_child().
1257          *
1258          * The sequence is, fork_child_dc_connect() ---> getdcs() --->
1259          * get_dc_name_via_netlogon() ---> cm_connect_netlogon()
1260          * ---> init_dc_connection() ---> cm_open_connection --->
1261          * set_domain_online(), sends MSG_WINBIND_ONLINE to
1262          * idmap_child(). Disallow children sending messages
1263          * to each other, all messages must go through the parent.
1264          */
1265         cl = idmap_child();
1266         cl->pid = (pid_t)0;
1267
1268         return true;
1269 }
1270
1271 /*
1272  * In a child there will be only one domain, reference that here.
1273  */
1274 static struct winbindd_domain *child_domain;
1275
1276 struct winbindd_domain *wb_child_domain(void)
1277 {
1278         return child_domain;
1279 }
1280
1281 static bool fork_domain_child(struct winbindd_child *child)
1282 {
1283         int fdpair[2];
1284         struct winbindd_cli_state state;
1285         struct winbindd_request request;
1286         struct winbindd_response response;
1287         struct winbindd_domain *primary_domain = NULL;
1288
1289         if (child->domain) {
1290                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1291                            child->domain->name));
1292         } else {
1293                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1294         }
1295
1296         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1297                 DEBUG(0, ("Could not open child pipe: %s\n",
1298                           strerror(errno)));
1299                 return False;
1300         }
1301
1302         ZERO_STRUCT(state);
1303         state.pid = sys_getpid();
1304         state.request = &request;
1305         state.response = &response;
1306
1307         child->pid = sys_fork();
1308
1309         if (child->pid == -1) {
1310                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1311                 return False;
1312         }
1313
1314         if (child->pid != 0) {
1315                 /* Parent */
1316                 close(fdpair[0]);
1317                 child->next = child->prev = NULL;
1318                 DLIST_ADD(winbindd_children, child);
1319                 child->sock = fdpair[1];
1320                 return True;
1321         }
1322
1323         /* Child */
1324         child_domain = child->domain;
1325
1326         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1327
1328         state.sock = fdpair[0];
1329         close(fdpair[1]);
1330
1331         if (!winbindd_reinit_after_fork(child->logfilename)) {
1332                 _exit(0);
1333         }
1334
1335         /* Handle online/offline messages. */
1336         messaging_register(winbind_messaging_context(), NULL,
1337                            MSG_WINBIND_OFFLINE, child_msg_offline);
1338         messaging_register(winbind_messaging_context(), NULL,
1339                            MSG_WINBIND_ONLINE, child_msg_online);
1340         messaging_register(winbind_messaging_context(), NULL,
1341                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1342         messaging_register(winbind_messaging_context(), NULL,
1343                            MSG_DEBUG, debug_message);
1344         messaging_register(winbind_messaging_context(), NULL,
1345                            MSG_WINBIND_IP_DROPPED,
1346                            winbind_msg_ip_dropped);
1347
1348
1349         primary_domain = find_our_domain();
1350
1351         if (primary_domain == NULL) {
1352                 smb_panic("no primary domain found");
1353         }
1354
1355         /* It doesn't matter if we allow cache login,
1356          * try to bring domain online after fork. */
1357         if ( child->domain ) {
1358                 child->domain->startup = True;
1359                 child->domain->startup_time = time_mono(NULL);
1360                 /* we can be in primary domain or in trusted domain
1361                  * If we are in trusted domain, set the primary domain
1362                  * in start-up mode */
1363                 if (!(child->domain->internal)) {
1364                         set_domain_online_request(child->domain);
1365                         if (!(child->domain->primary)) {
1366                                 primary_domain->startup = True;
1367                                 primary_domain->startup_time = time_mono(NULL);
1368                                 set_domain_online_request(primary_domain);
1369                         }
1370                 }
1371         }
1372
1373         /*
1374          * We are in idmap child, make sure that we set the
1375          * check_online_event to bring primary domain online.
1376          */
1377         if (child == idmap_child()) {
1378                 set_domain_online_request(primary_domain);
1379         }
1380
1381         /* We might be in the idmap child...*/
1382         if (child->domain && !(child->domain->internal) &&
1383             lp_winbind_offline_logon()) {
1384
1385                 set_domain_online_request(child->domain);
1386
1387                 if (primary_domain && (primary_domain != child->domain)) {
1388                         /* We need to talk to the primary
1389                          * domain as well as the trusted
1390                          * domain inside a trusted domain
1391                          * child.
1392                          * See the code in :
1393                          * set_dc_type_and_flags_trustinfo()
1394                          * for details.
1395                          */
1396                         set_domain_online_request(primary_domain);
1397                 }
1398
1399                 child->lockout_policy_event = event_add_timed(
1400                         winbind_event_context(), NULL, timeval_zero(),
1401                         account_lockout_policy_handler,
1402                         child);
1403         }
1404
1405         if (child->domain && child->domain->primary &&
1406             !USE_KERBEROS_KEYTAB &&
1407             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1408
1409                 struct timeval next_change;
1410
1411                 if (calculate_next_machine_pwd_change(child->domain->name,
1412                                                        &next_change)) {
1413                         child->machine_password_change_event = event_add_timed(
1414                                 winbind_event_context(), NULL, next_change,
1415                                 machine_password_change_handler,
1416                                 child);
1417                 }
1418         }
1419
1420         while (1) {
1421
1422                 int ret;
1423                 struct pollfd *pfds;
1424                 int num_pfds;
1425                 int timeout;
1426                 struct timeval t;
1427                 struct timeval *tp;
1428                 TALLOC_CTX *frame = talloc_stackframe();
1429                 struct iovec iov[2];
1430                 int iov_count;
1431                 NTSTATUS status;
1432
1433                 if (run_events_poll(winbind_event_context(), 0, NULL, 0)) {
1434                         TALLOC_FREE(frame);
1435                         continue;
1436                 }
1437
1438                 if (child->domain && child->domain->startup &&
1439                                 (time_mono(NULL) > child->domain->startup_time + 30)) {
1440                         /* No longer in "startup" mode. */
1441                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1442                                 child->domain->name ));
1443                         child->domain->startup = False;
1444                 }
1445
1446                 pfds = TALLOC_ZERO_P(talloc_tos(), struct pollfd);
1447                 if (pfds == NULL) {
1448                         DEBUG(1, ("talloc failed\n"));
1449                         _exit(1);
1450                 }
1451
1452                 pfds->fd = state.sock;
1453                 pfds->events = POLLIN|POLLHUP;
1454                 num_pfds = 1;
1455
1456                 timeout = INT_MAX;
1457
1458                 if (!event_add_to_poll_args(
1459                             winbind_event_context(), talloc_tos(),
1460                             &pfds, &num_pfds, &timeout)) {
1461                         DEBUG(1, ("event_add_to_poll_args failed\n"));
1462                         _exit(1);
1463                 }
1464                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1465                 if (tp) {
1466                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1467                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1468                 }
1469
1470                 ret = sys_poll(pfds, num_pfds, timeout);
1471
1472                 if (run_events_poll(winbind_event_context(), ret,
1473                                     pfds, num_pfds)) {
1474                         /* We got a signal - continue. */
1475                         TALLOC_FREE(frame);
1476                         continue;
1477                 }
1478
1479                 TALLOC_FREE(pfds);
1480
1481                 if (ret == 0) {
1482                         DEBUG(11,("nothing is ready yet, continue\n"));
1483                         TALLOC_FREE(frame);
1484                         continue;
1485                 }
1486
1487                 if (ret == -1 && errno == EINTR) {
1488                         /* We got a signal - continue. */
1489                         TALLOC_FREE(frame);
1490                         continue;
1491                 }
1492
1493                 if (ret == -1 && errno != EINTR) {
1494                         DEBUG(0,("poll error occured\n"));
1495                         TALLOC_FREE(frame);
1496                         perror("poll");
1497                         _exit(1);
1498                 }
1499
1500                 /* fetch a request from the main daemon */
1501                 status = child_read_request(&state);
1502
1503                 if (!NT_STATUS_IS_OK(status)) {
1504                         /* we lost contact with our parent */
1505                         _exit(0);
1506                 }
1507
1508                 DEBUG(4,("child daemon request %d\n", (int)state.request->cmd));
1509
1510                 ZERO_STRUCTP(state.response);
1511                 state.request->null_term = '\0';
1512                 state.mem_ctx = frame;
1513                 child_process_request(child, &state);
1514
1515                 DEBUG(4, ("Finished processing child request %d\n",
1516                           (int)state.request->cmd));
1517
1518                 SAFE_FREE(state.request->extra_data.data);
1519
1520                 iov[0].iov_base = (void *)state.response;
1521                 iov[0].iov_len = sizeof(struct winbindd_response);
1522                 iov_count = 1;
1523
1524                 if (state.response->length > sizeof(struct winbindd_response)) {
1525                         iov[1].iov_base =
1526                                 (void *)state.response->extra_data.data;
1527                         iov[1].iov_len = state.response->length-iov[0].iov_len;
1528                         iov_count = 2;
1529                 }
1530
1531                 DEBUG(10, ("Writing %d bytes to parent\n",
1532                            (int)state.response->length));
1533
1534                 if (write_data_iov(state.sock, iov, iov_count) !=
1535                     state.response->length) {
1536                         DEBUG(0, ("Could not write result\n"));
1537                         exit(1);
1538                 }
1539                 TALLOC_FREE(frame);
1540         }
1541 }
1542
1543 void winbind_msg_ip_dropped_parent(struct messaging_context *msg_ctx,
1544                                    void *private_data,
1545                                    uint32_t msg_type,
1546                                    struct server_id server_id,
1547                                    DATA_BLOB *data)
1548 {
1549         struct winbindd_child *child;
1550
1551         winbind_msg_ip_dropped(msg_ctx, private_data, msg_type,
1552                                server_id, data);
1553
1554
1555         for (child = winbindd_children; child != NULL; child = child->next) {
1556                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
1557                                    msg_type, data->data, data->length);
1558         }
1559 }