s3:winbind killed winbind child logs back trace
[obnox/samba-ctdb.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
33 #undef DBGC_CLASS
34 #define DBGC_CLASS DBGC_WINBIND
35
36 extern bool override_logfile;
37 extern struct winbindd_methods cache_methods;
38
39 /* Read some data from a client connection */
40
41 static void child_read_request(struct winbindd_cli_state *state)
42 {
43         NTSTATUS status;
44
45         /* Read data */
46
47         status = read_data(state->sock, (char *)&state->request,
48                            sizeof(state->request));
49
50         if (!NT_STATUS_IS_OK(status)) {
51                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
52                           nt_errstr(status)));
53                 state->finished = True;
54                 return;
55         }
56
57         if (state->request.extra_len == 0) {
58                 state->request.extra_data.data = NULL;
59                 return;
60         }
61
62         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request.extra_len));
63
64         state->request.extra_data.data =
65                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
66
67         if (state->request.extra_data.data == NULL) {
68                 DEBUG(0, ("malloc failed\n"));
69                 state->finished = True;
70                 return;
71         }
72
73         /* Ensure null termination */
74         state->request.extra_data.data[state->request.extra_len] = '\0';
75
76         status= read_data(state->sock, state->request.extra_data.data,
77                           state->request.extra_len);
78
79         if (!NT_STATUS_IS_OK(status)) {
80                 DEBUG(0, ("Could not read extra data: %s\n",
81                           nt_errstr(status)));
82                 state->finished = True;
83                 return;
84         }
85 }
86
87 /*
88  * Machinery for async requests sent to children. You set up a
89  * winbindd_request, select a child to query, and issue a async_request
90  * call. When the request is completed, the callback function you specified is
91  * called back with the private pointer you gave to async_request.
92  */
93
94 struct winbindd_async_request {
95         struct winbindd_async_request *next, *prev;
96         TALLOC_CTX *mem_ctx;
97         struct winbindd_child *child;
98         struct winbindd_request *request;
99         struct winbindd_response *response;
100         void (*continuation)(void *private_data, bool success);
101         struct timed_event *reply_timeout_event;
102         pid_t child_pid; /* pid of the child we're waiting on. Used to detect
103                             a restart of the child (child->pid != child_pid). */
104         void *private_data;
105 };
106
107 static void async_request_fail(struct winbindd_async_request *state);
108 static void async_main_request_sent(void *private_data, bool success);
109 static void async_request_sent(void *private_data, bool success);
110 static void async_reply_recv(void *private_data, bool success);
111 static void schedule_async_request(struct winbindd_child *child);
112
113 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
114                    struct winbindd_request *request,
115                    struct winbindd_response *response,
116                    void (*continuation)(void *private_data, bool success),
117                    void *private_data)
118 {
119         struct winbindd_async_request *state;
120
121         SMB_ASSERT(continuation != NULL);
122
123         DEBUG(10, ("Sending request to child pid %d (domain=%s)\n",
124                    (int)child->pid,
125                    (child->domain != NULL) ? child->domain->name : "''"));
126
127         state = TALLOC_P(mem_ctx, struct winbindd_async_request);
128
129         if (state == NULL) {
130                 DEBUG(0, ("talloc failed\n"));
131                 continuation(private_data, False);
132                 return;
133         }
134
135         state->mem_ctx = mem_ctx;
136         state->child = child;
137         state->reply_timeout_event = NULL;
138         state->request = request;
139         state->response = response;
140         state->continuation = continuation;
141         state->private_data = private_data;
142
143         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
144
145         schedule_async_request(child);
146
147         return;
148 }
149
150 static void async_main_request_sent(void *private_data, bool success)
151 {
152         struct winbindd_async_request *state =
153                 talloc_get_type_abort(private_data, struct winbindd_async_request);
154
155         if (!success) {
156                 DEBUG(5, ("Could not send async request\n"));
157                 async_request_fail(state);
158                 return;
159         }
160
161         if (state->request->extra_len == 0) {
162                 async_request_sent(private_data, True);
163                 return;
164         }
165
166         setup_async_write(&state->child->event, state->request->extra_data.data,
167                           state->request->extra_len,
168                           async_request_sent, state);
169 }
170
171 /****************************************************************
172  Handler triggered if the child winbindd doesn't respond within
173  a given timeout.
174 ****************************************************************/
175
176 static void async_request_timeout_handler(struct event_context *ctx,
177                                         struct timed_event *te,
178                                         struct timeval now,
179                                         void *private_data)
180 {
181         struct winbindd_async_request *state =
182                 talloc_get_type_abort(private_data, struct winbindd_async_request);
183
184         DEBUG(0,("async_request_timeout_handler: child pid %u is not responding. "
185                 "Closing connection to it.\n",
186                 (unsigned int)state->child_pid ));
187
188         /* Deal with the reply - set to error. */
189         async_reply_recv(private_data, False);
190 }
191
192 /**************************************************************
193  Common function called on both async send and recv fail.
194  Cleans up the child and schedules the next request.
195 **************************************************************/
196
197 static void async_request_fail(struct winbindd_async_request *state)
198 {
199         DLIST_REMOVE(state->child->requests, state);
200
201         TALLOC_FREE(state->reply_timeout_event);
202
203         /* If child exists and is not already reaped,
204            send kill signal to child. */
205
206         if ((state->child->pid != (pid_t)0) &&
207                         (state->child->pid != (pid_t)-1) &&
208                         (state->child->pid == state->child_pid)) {
209                 kill(state->child_pid, SIGXCPU);
210
211                 /* 
212                  * Close the socket to the child.
213                  */
214                 winbind_child_died(state->child_pid);
215         }
216
217         state->response->length = sizeof(struct winbindd_response);
218         state->response->result = WINBINDD_ERROR;
219         state->continuation(state->private_data, False);
220 }
221
222 static void async_request_sent(void *private_data_data, bool success)
223 {
224         struct winbindd_async_request *state =
225                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
226
227         if (!success) {
228                 DEBUG(5, ("Could not send async request to child pid %u\n",
229                         (unsigned int)state->child_pid ));
230                 async_request_fail(state);
231                 return;
232         }
233
234         /* Request successfully sent to the child, setup the wait for reply */
235
236         setup_async_read(&state->child->event,
237                          &state->response->result,
238                          sizeof(state->response->result),
239                          async_reply_recv, state);
240
241         /* 
242          * Set up a timeout of 300 seconds for the response.
243          * If we don't get it close the child socket and
244          * report failure.
245          */
246
247         state->reply_timeout_event = event_add_timed(winbind_event_context(),
248                                                         NULL,
249                                                         timeval_current_ofs(300,0),
250                                                         async_request_timeout_handler,
251                                                         state);
252         if (!state->reply_timeout_event) {
253                 smb_panic("async_request_sent: failed to add timeout handler.\n");
254         }
255 }
256
257 static void async_reply_recv(void *private_data, bool success)
258 {
259         struct winbindd_async_request *state =
260                 talloc_get_type_abort(private_data, struct winbindd_async_request);
261         struct winbindd_child *child = state->child;
262
263         TALLOC_FREE(state->reply_timeout_event);
264
265         state->response->length = sizeof(struct winbindd_response);
266
267         if (!success) {
268                 DEBUG(5, ("Could not receive async reply from child pid %u\n",
269                         (unsigned int)state->child_pid ));
270
271                 cache_cleanup_response(state->child_pid);
272                 async_request_fail(state);
273                 return;
274         }
275
276         SMB_ASSERT(cache_retrieve_response(state->child_pid,
277                                            state->response));
278
279         cache_cleanup_response(state->child_pid);
280         
281         DLIST_REMOVE(child->requests, state);
282
283         schedule_async_request(child);
284
285         state->continuation(state->private_data, True);
286 }
287
288 static bool winbindd_child_busy(const struct winbindd_child *child)
289 {
290         return (child->event.flags != 0);
291 }
292
293 static bool fork_domain_child(struct winbindd_child *child);
294
295 static void schedule_async_request(struct winbindd_child *child)
296 {
297         struct winbindd_async_request *request = child->requests;
298
299         if (request == NULL) {
300                 return;
301         }
302
303         if (winbindd_child_busy(child)) {
304                 return;         /* Busy */
305         }
306
307         /*
308          * This may be a reschedule, so we might
309          * have an existing timeout event pending on
310          * the first entry in the child->requests list
311          * (we only send one request at a time).
312          * Ensure we free it before we reschedule.
313          * Bug #5814, from hargagan <shargagan@novell.com>.
314          * JRA.
315          */
316
317         TALLOC_FREE(request->reply_timeout_event);
318
319         if ((child->pid == 0) && (!fork_domain_child(child))) {
320                 /* fork_domain_child failed.
321                    Cancel all outstanding requests */
322
323                 while (request != NULL) {
324                         /* request might be free'd in the continuation */
325                         struct winbindd_async_request *next = request->next;
326
327                         async_request_fail(request);
328                         request = next;
329                 }
330                 return;
331         }
332
333         /* Now we know who we're sending to - remember the pid. */
334         request->child_pid = child->pid;
335
336         setup_async_write(&child->event, request->request,
337                           sizeof(*request->request),
338                           async_main_request_sent, request);
339
340         return;
341 }
342
343 static struct winbindd_child *find_idle_child(struct winbindd_domain *domain)
344 {
345         int i;
346
347         for (i=0; i<lp_winbind_max_domain_connections(); i++) {
348                 if (!winbindd_child_busy(&domain->children[i])) {
349                         return &domain->children[i];
350                 }
351         }
352
353         return NULL;
354 }
355
356 static struct winbindd_child *choose_domain_child(
357         struct winbindd_domain *domain)
358 {
359         struct winbindd_child *result;
360
361         result = find_idle_child(domain);
362         if (result != NULL) {
363                 return result;
364         }
365         return &domain->children[rand() % lp_winbind_max_domain_connections()];
366 }
367
368 struct domain_request_state {
369         TALLOC_CTX *mem_ctx;
370         struct winbindd_domain *domain;
371         struct winbindd_request *request;
372         struct winbindd_response *response;
373         void (*continuation)(void *private_data_data, bool success);
374         void *private_data_data;
375 };
376
377 static void domain_init_recv(void *private_data_data, bool success);
378
379 void async_domain_request(TALLOC_CTX *mem_ctx,
380                           struct winbindd_domain *domain,
381                           struct winbindd_request *request,
382                           struct winbindd_response *response,
383                           void (*continuation)(void *private_data_data, bool success),
384                           void *private_data_data)
385 {
386         struct domain_request_state *state;
387
388         if (domain->initialized) {
389                 struct winbindd_child *child = choose_domain_child(domain);
390
391                 async_request(mem_ctx, child, request, response,
392                               continuation, private_data_data);
393                 return;
394         }
395
396         state = TALLOC_P(mem_ctx, struct domain_request_state);
397         if (state == NULL) {
398                 DEBUG(0, ("talloc failed\n"));
399                 continuation(private_data_data, False);
400                 return;
401         }
402
403         state->mem_ctx = mem_ctx;
404         state->domain = domain;
405         state->request = request;
406         state->response = response;
407         state->continuation = continuation;
408         state->private_data_data = private_data_data;
409
410         init_child_connection(domain, domain_init_recv, state);
411 }
412
413 static void domain_init_recv(void *private_data_data, bool success)
414 {
415         struct domain_request_state *state =
416                 talloc_get_type_abort(private_data_data, struct domain_request_state);
417
418         if (!success) {
419                 DEBUG(5, ("Domain init returned an error\n"));
420                 state->continuation(state->private_data_data, False);
421                 return;
422         }
423
424         async_request(state->mem_ctx, &state->domain->children[0],
425                       state->request, state->response,
426                       state->continuation, state->private_data_data);
427 }
428
429 static void recvfrom_child(void *private_data_data, bool success)
430 {
431         struct winbindd_cli_state *state =
432                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
433         enum winbindd_result result = state->response.result;
434
435         /* This is an optimization: The child has written directly to the
436          * response buffer. The request itself is still in pending state,
437          * state that in the result code. */
438
439         state->response.result = WINBINDD_PENDING;
440
441         if ((!success) || (result != WINBINDD_OK)) {
442                 request_error(state);
443                 return;
444         }
445
446         request_ok(state);
447 }
448
449 void sendto_child(struct winbindd_cli_state *state,
450                   struct winbindd_child *child)
451 {
452         async_request(state->mem_ctx, child, &state->request,
453                       &state->response, recvfrom_child, state);
454 }
455
456 void sendto_domain(struct winbindd_cli_state *state,
457                    struct winbindd_domain *domain)
458 {
459         async_domain_request(state->mem_ctx, domain,
460                              &state->request, &state->response,
461                              recvfrom_child, state);
462 }
463
464 static void child_process_request(struct winbindd_child *child,
465                                   struct winbindd_cli_state *state)
466 {
467         struct winbindd_domain *domain = child->domain;
468         const struct winbindd_child_dispatch_table *table = child->table;
469
470         /* Free response data - we may be interrupted and receive another
471            command before being able to send this data off. */
472
473         state->response.result = WINBINDD_ERROR;
474         state->response.length = sizeof(struct winbindd_response);
475
476         /* as all requests in the child are sync, we can use talloc_tos() */
477         state->mem_ctx = talloc_tos();
478
479         /* Process command */
480
481         for (; table->name; table++) {
482                 if (state->request.cmd == table->struct_cmd) {
483                         DEBUG(10,("child_process_request: request fn %s\n",
484                                   table->name));
485                         state->response.result = table->struct_fn(domain, state);
486                         return;
487                 }
488         }
489
490         DEBUG(1 ,("child_process_request: unknown request fn number %d\n",
491                   (int)state->request.cmd));
492         state->response.result = WINBINDD_ERROR;
493 }
494
495 void setup_child(struct winbindd_child *child,
496                  const struct winbindd_child_dispatch_table *table,
497                  const char *logprefix,
498                  const char *logname)
499 {
500         if (logprefix && logname) {
501                 if (asprintf(&child->logfilename, "%s/%s-%s",
502                              get_dyn_LOGFILEBASE(), logprefix, logname) < 0) {
503                         smb_panic("Internal error: asprintf failed");
504                 }
505         } else {
506                 smb_panic("Internal error: logprefix == NULL && "
507                           "logname == NULL");
508         }
509
510         child->domain = NULL;
511         child->table = table;
512 }
513
514 struct winbindd_child *children = NULL;
515
516 void winbind_child_died(pid_t pid)
517 {
518         struct winbindd_child *child;
519
520         for (child = children; child != NULL; child = child->next) {
521                 if (child->pid == pid) {
522                         break;
523                 }
524         }
525
526         if (child == NULL) {
527                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
528                 return;
529         }
530
531         /* This will be re-added in fork_domain_child() */
532
533         DLIST_REMOVE(children, child);
534         
535         remove_fd_event(&child->event);
536         close(child->event.fd);
537         child->event.fd = 0;
538         child->event.flags = 0;
539         child->pid = 0;
540
541         if (child->requests) {
542                 /*
543                  * schedule_async_request() will also
544                  * clear this event but the call is
545                  * idempotent so it doesn't hurt to
546                  * cover all possible future code
547                  * paths. JRA.
548                  */
549                 TALLOC_FREE(child->requests->reply_timeout_event);
550         }
551
552         schedule_async_request(child);
553 }
554
555 /* Ensure any negative cache entries with the netbios or realm names are removed. */
556
557 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
558 {
559         flush_negative_conn_cache_for_domain(domain->name);
560         if (*domain->alt_name) {
561                 flush_negative_conn_cache_for_domain(domain->alt_name);
562         }
563 }
564
565 /* 
566  * Parent winbindd process sets its own debug level first and then
567  * sends a message to all the winbindd children to adjust their debug
568  * level to that of parents.
569  */
570
571 void winbind_msg_debug(struct messaging_context *msg_ctx,
572                          void *private_data,
573                          uint32_t msg_type,
574                          struct server_id server_id,
575                          DATA_BLOB *data)
576 {
577         struct winbindd_child *child;
578
579         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
580         
581         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
582
583         for (child = children; child != NULL; child = child->next) {
584
585                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
586                         (unsigned int)child->pid));
587
588                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
589                            MSG_DEBUG,
590                            data->data,
591                            strlen((char *) data->data) + 1);
592         }
593 }
594
595 /* Set our domains as offline and forward the offline message to our children. */
596
597 void winbind_msg_offline(struct messaging_context *msg_ctx,
598                          void *private_data,
599                          uint32_t msg_type,
600                          struct server_id server_id,
601                          DATA_BLOB *data)
602 {
603         struct winbindd_child *child;
604         struct winbindd_domain *domain;
605
606         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
607
608         if (!lp_winbind_offline_logon()) {
609                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
610                 return;
611         }
612
613         /* Set our global state as offline. */
614         if (!set_global_winbindd_state_offline()) {
615                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
616                 return;
617         }
618
619         /* Set all our domains as offline. */
620         for (domain = domain_list(); domain; domain = domain->next) {
621                 if (domain->internal) {
622                         continue;
623                 }
624                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
625                 set_domain_offline(domain);
626         }
627
628         for (child = children; child != NULL; child = child->next) {
629                 /* Don't send message to internal childs.  We've already
630                    done so above. */
631                 if (!child->domain || winbindd_internal_child(child)) {
632                         continue;
633                 }
634
635                 /* Or internal domains (this should not be possible....) */
636                 if (child->domain->internal) {
637                         continue;
638                 }
639
640                 /* Each winbindd child should only process requests for one domain - make sure
641                    we only set it online / offline for that domain. */
642
643                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
644                         (unsigned int)child->pid, domain->name ));
645
646                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
647                                    MSG_WINBIND_OFFLINE,
648                                    (uint8 *)child->domain->name,
649                                    strlen(child->domain->name)+1);
650         }
651 }
652
653 /* Set our domains as online and forward the online message to our children. */
654
655 void winbind_msg_online(struct messaging_context *msg_ctx,
656                         void *private_data,
657                         uint32_t msg_type,
658                         struct server_id server_id,
659                         DATA_BLOB *data)
660 {
661         struct winbindd_child *child;
662         struct winbindd_domain *domain;
663
664         DEBUG(10,("winbind_msg_online: got online message.\n"));
665
666         if (!lp_winbind_offline_logon()) {
667                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
668                 return;
669         }
670
671         /* Set our global state as online. */
672         set_global_winbindd_state_online();
673
674         smb_nscd_flush_user_cache();
675         smb_nscd_flush_group_cache();
676
677         /* Set all our domains as online. */
678         for (domain = domain_list(); domain; domain = domain->next) {
679                 if (domain->internal) {
680                         continue;
681                 }
682                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
683
684                 winbindd_flush_negative_conn_cache(domain);
685                 set_domain_online_request(domain);
686
687                 /* Send an online message to the idmap child when our
688                    primary domain comes back online */
689
690                 if ( domain->primary ) {
691                         struct winbindd_child *idmap = idmap_child();
692                         
693                         if ( idmap->pid != 0 ) {
694                                 messaging_send_buf(msg_ctx,
695                                                    pid_to_procid(idmap->pid), 
696                                                    MSG_WINBIND_ONLINE,
697                                                    (uint8 *)domain->name,
698                                                    strlen(domain->name)+1);
699                         }
700                         
701                 }
702         }
703
704         for (child = children; child != NULL; child = child->next) {
705                 /* Don't send message to internal childs. */
706                 if (!child->domain || winbindd_internal_child(child)) {
707                         continue;
708                 }
709
710                 /* Or internal domains (this should not be possible....) */
711                 if (child->domain->internal) {
712                         continue;
713                 }
714
715                 /* Each winbindd child should only process requests for one domain - make sure
716                    we only set it online / offline for that domain. */
717
718                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
719                         (unsigned int)child->pid, child->domain->name ));
720
721                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
722                                    MSG_WINBIND_ONLINE,
723                                    (uint8 *)child->domain->name,
724                                    strlen(child->domain->name)+1);
725         }
726 }
727
728 /* Forward the online/offline messages to our children. */
729 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
730                               void *private_data,
731                               uint32_t msg_type,
732                               struct server_id server_id,
733                               DATA_BLOB *data)
734 {
735         struct winbindd_child *child;
736
737         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
738
739         for (child = children; child != NULL; child = child->next) {
740                 if (child->domain && child->domain->primary) {
741                         DEBUG(10,("winbind_msg_onlinestatus: "
742                                   "sending message to pid %u of primary domain.\n",
743                                   (unsigned int)child->pid));
744                         messaging_send_buf(msg_ctx, pid_to_procid(child->pid), 
745                                            MSG_WINBIND_ONLINESTATUS,
746                                            (uint8 *)data->data,
747                                            data->length);
748                         break;
749                 }
750         }
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 = 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(10, ("Dropping the NETLOGON connection, someone else "
1034                            "changed the machine password simultaneously\n"));
1035                 TALLOC_FREE(child->domain->conn.netlogon_pipe);
1036         }
1037
1038         if (!calculate_next_machine_pwd_change(child->domain->name,
1039                                                &next_change)) {
1040                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1041                 return;
1042         }
1043
1044         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1045                    timeval_string(talloc_tos(), &next_change, false)));
1046
1047         if (!NT_STATUS_IS_OK(result)) {
1048                 struct timeval tmp;
1049                 /*
1050                  * In case of failure, give the DC a minute to recover
1051                  */
1052                 tmp = timeval_current_ofs(60, 0);
1053                 next_change = timeval_max(&next_change, &tmp);
1054         }
1055
1056 done:
1057         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
1058                                                               next_change,
1059                                                               machine_password_change_handler,
1060                                                               child);
1061 }
1062
1063 /* Deal with a request to go offline. */
1064
1065 static void child_msg_offline(struct messaging_context *msg,
1066                               void *private_data,
1067                               uint32_t msg_type,
1068                               struct server_id server_id,
1069                               DATA_BLOB *data)
1070 {
1071         struct winbindd_domain *domain;
1072         struct winbindd_domain *primary_domain = NULL;
1073         const char *domainname = (const char *)data->data;
1074
1075         if (data->data == NULL || data->length == 0) {
1076                 return;
1077         }
1078
1079         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
1080
1081         if (!lp_winbind_offline_logon()) {
1082                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
1083                 return;
1084         }
1085
1086         primary_domain = find_our_domain();
1087
1088         /* Mark the requested domain offline. */
1089
1090         for (domain = domain_list(); domain; domain = domain->next) {
1091                 if (domain->internal) {
1092                         continue;
1093                 }
1094                 if (strequal(domain->name, domainname)) {
1095                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1096                         set_domain_offline(domain);
1097                         /* we are in the trusted domain, set the primary domain 
1098                          * offline too */
1099                         if (domain != primary_domain) {
1100                                 set_domain_offline(primary_domain);
1101                         }
1102                 }
1103         }
1104 }
1105
1106 /* Deal with a request to go online. */
1107
1108 static void child_msg_online(struct messaging_context *msg,
1109                              void *private_data,
1110                              uint32_t msg_type,
1111                              struct server_id server_id,
1112                              DATA_BLOB *data)
1113 {
1114         struct winbindd_domain *domain;
1115         struct winbindd_domain *primary_domain = NULL;
1116         const char *domainname = (const char *)data->data;
1117
1118         if (data->data == NULL || data->length == 0) {
1119                 return;
1120         }
1121
1122         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1123
1124         if (!lp_winbind_offline_logon()) {
1125                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1126                 return;
1127         }
1128
1129         primary_domain = find_our_domain();
1130
1131         /* Set our global state as online. */
1132         set_global_winbindd_state_online();
1133
1134         /* Try and mark everything online - delete any negative cache entries
1135            to force a reconnect now. */
1136
1137         for (domain = domain_list(); domain; domain = domain->next) {
1138                 if (domain->internal) {
1139                         continue;
1140                 }
1141                 if (strequal(domain->name, domainname)) {
1142                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1143                         winbindd_flush_negative_conn_cache(domain);
1144                         set_domain_online_request(domain);
1145
1146                         /* we can be in trusted domain, which will contact primary domain
1147                          * we have to bring primary domain online in trusted domain process
1148                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1149                          * --> contact_domain = find_our_domain()
1150                          * */
1151                         if (domain != primary_domain) {
1152                                 winbindd_flush_negative_conn_cache(primary_domain);
1153                                 set_domain_online_request(primary_domain);
1154                         }
1155                 }
1156         }
1157 }
1158
1159 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
1160 {
1161         struct winbindd_domain *domain;
1162         char *buf = NULL;
1163
1164         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
1165                                    get_global_winbindd_state_offline() ? 
1166                                    "Offline":"Online")) == NULL) {
1167                 return NULL;
1168         }
1169
1170         for (domain = domain_list(); domain; domain = domain->next) {
1171                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
1172                                                   domain->name, 
1173                                                   domain->online ?
1174                                                   "Online":"Offline")) == NULL) {
1175                         return NULL;
1176                 }
1177         }
1178
1179         buf = talloc_asprintf_append_buffer(buf, "\n");
1180
1181         DEBUG(5,("collect_onlinestatus: %s", buf));
1182
1183         return buf;
1184 }
1185
1186 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
1187                                    void *private_data,
1188                                    uint32_t msg_type,
1189                                    struct server_id server_id,
1190                                    DATA_BLOB *data)
1191 {
1192         TALLOC_CTX *mem_ctx;
1193         const char *message;
1194         struct server_id *sender;
1195         
1196         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
1197
1198         if (!data->data) {
1199                 return;
1200         }
1201
1202         sender = (struct server_id *)data->data;
1203
1204         mem_ctx = talloc_init("winbind_msg_onlinestatus");
1205         if (mem_ctx == NULL) {
1206                 return;
1207         }
1208         
1209         message = collect_onlinestatus(mem_ctx);
1210         if (message == NULL) {
1211                 talloc_destroy(mem_ctx);
1212                 return;
1213         }
1214
1215         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
1216                            (uint8 *)message, strlen(message) + 1);
1217
1218         talloc_destroy(mem_ctx);
1219 }
1220
1221 static void child_msg_dump_event_list(struct messaging_context *msg,
1222                                       void *private_data,
1223                                       uint32_t msg_type,
1224                                       struct server_id server_id,
1225                                       DATA_BLOB *data)
1226 {
1227         DEBUG(5,("child_msg_dump_event_list received\n"));
1228
1229         dump_event_list(winbind_event_context());
1230 }
1231
1232 bool winbindd_reinit_after_fork(const char *logfilename)
1233 {
1234         struct winbindd_domain *domain;
1235         struct winbindd_child *cl;
1236
1237         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1238                                                winbind_event_context(),
1239                                                true))) {
1240                 DEBUG(0,("reinit_after_fork() failed\n"));
1241                 return false;
1242         }
1243
1244         close_conns_after_fork();
1245
1246         if (!override_logfile && logfilename) {
1247                 lp_set_logfile(logfilename);
1248                 reopen_logs();
1249         }
1250
1251         if (!winbindd_setup_sig_term_handler(false))
1252                 return false;
1253         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1254                                             logfilename))
1255                 return false;
1256
1257         /* Stop zombies in children */
1258         CatchChild();
1259
1260         /* Don't handle the same messages as our parent. */
1261         messaging_deregister(winbind_messaging_context(),
1262                              MSG_SMB_CONF_UPDATED, NULL);
1263         messaging_deregister(winbind_messaging_context(),
1264                              MSG_SHUTDOWN, NULL);
1265         messaging_deregister(winbind_messaging_context(),
1266                              MSG_WINBIND_OFFLINE, NULL);
1267         messaging_deregister(winbind_messaging_context(),
1268                              MSG_WINBIND_ONLINE, NULL);
1269         messaging_deregister(winbind_messaging_context(),
1270                              MSG_WINBIND_ONLINESTATUS, NULL);
1271         messaging_deregister(winbind_messaging_context(),
1272                              MSG_DUMP_EVENT_LIST, NULL);
1273         messaging_deregister(winbind_messaging_context(),
1274                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1275         messaging_deregister(winbind_messaging_context(),
1276                              MSG_DEBUG, NULL);
1277
1278         /* We have destroyed all events in the winbindd_event_context
1279          * in reinit_after_fork(), so clean out all possible pending
1280          * event pointers. */
1281
1282         /* Deal with check_online_events. */
1283
1284         for (domain = domain_list(); domain; domain = domain->next) {
1285                 TALLOC_FREE(domain->check_online_event);
1286         }
1287
1288         /* Ensure we're not handling a credential cache event inherited
1289          * from our parent. */
1290
1291         ccache_remove_all_after_fork();
1292
1293         /* Destroy all possible events in child list. */
1294         for (cl = children; cl != NULL; cl = cl->next) {
1295                 struct winbindd_async_request *request;
1296
1297                 for (request = cl->requests; request; request = request->next) {
1298                         TALLOC_FREE(request->reply_timeout_event);
1299                 }
1300                 TALLOC_FREE(cl->lockout_policy_event);
1301                 TALLOC_FREE(cl->machine_password_change_event);
1302
1303                 /* Children should never be able to send
1304                  * each other messages, all messages must
1305                  * go through the parent.
1306                  */
1307                 cl->pid = (pid_t)0;
1308         }
1309         /*
1310          * This is a little tricky, children must not
1311          * send an MSG_WINBIND_ONLINE message to idmap_child().
1312          * If we are in a child of our primary domain or
1313          * in the process created by fork_child_dc_connect(),
1314          * and the primary domain cannot go online,
1315          * fork_child_dc_connection() sends MSG_WINBIND_ONLINE
1316          * periodically to idmap_child().
1317          *
1318          * The sequence is, fork_child_dc_connect() ---> getdcs() --->
1319          * get_dc_name_via_netlogon() ---> cm_connect_netlogon()
1320          * ---> init_dc_connection() ---> cm_open_connection --->
1321          * set_domain_online(), sends MSG_WINBIND_ONLINE to
1322          * idmap_child(). Disallow children sending messages
1323          * to each other, all messages must go through the parent.
1324          */
1325         cl = idmap_child();
1326         cl->pid = (pid_t)0;
1327
1328         return true;
1329 }
1330
1331 static bool fork_domain_child(struct winbindd_child *child)
1332 {
1333         int fdpair[2];
1334         struct winbindd_cli_state state;
1335         struct winbindd_domain *primary_domain = NULL;
1336
1337         if (child->domain) {
1338                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1339                            child->domain->name));
1340         } else {
1341                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1342         }
1343
1344         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1345                 DEBUG(0, ("Could not open child pipe: %s\n",
1346                           strerror(errno)));
1347                 return False;
1348         }
1349
1350         ZERO_STRUCT(state);
1351         state.pid = sys_getpid();
1352
1353         child->pid = sys_fork();
1354
1355         if (child->pid == -1) {
1356                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1357                 return False;
1358         }
1359
1360         if (child->pid != 0) {
1361                 /* Parent */
1362                 close(fdpair[0]);
1363                 child->next = child->prev = NULL;
1364                 DLIST_ADD(children, child);
1365                 child->event.fd = fdpair[1];
1366                 child->event.flags = 0;
1367                 add_fd_event(&child->event);
1368                 return True;
1369         }
1370
1371         /* Child */
1372
1373         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1374
1375         state.sock = fdpair[0];
1376         close(fdpair[1]);
1377
1378         if (!winbindd_reinit_after_fork(child->logfilename)) {
1379                 _exit(0);
1380         }
1381
1382         /* Handle online/offline messages. */
1383         messaging_register(winbind_messaging_context(), NULL,
1384                            MSG_WINBIND_OFFLINE, child_msg_offline);
1385         messaging_register(winbind_messaging_context(), NULL,
1386                            MSG_WINBIND_ONLINE, child_msg_online);
1387         messaging_register(winbind_messaging_context(), NULL,
1388                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
1389         messaging_register(winbind_messaging_context(), NULL,
1390                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1391         messaging_register(winbind_messaging_context(), NULL,
1392                            MSG_DEBUG, debug_message);
1393         messaging_register(winbind_messaging_context(), NULL,
1394                            MSG_WINBIND_IP_DROPPED,
1395                            winbind_msg_ip_dropped);
1396
1397
1398         primary_domain = find_our_domain();
1399
1400         if (primary_domain == NULL) {
1401                 smb_panic("no primary domain found");
1402         }
1403
1404         /* It doesn't matter if we allow cache login,
1405          * try to bring domain online after fork. */
1406         if ( child->domain ) {
1407                 child->domain->startup = True;
1408                 child->domain->startup_time = time(NULL);
1409                 /* we can be in primary domain or in trusted domain
1410                  * If we are in trusted domain, set the primary domain
1411                  * in start-up mode */
1412                 if (!(child->domain->internal)) {
1413                         set_domain_online_request(child->domain);
1414                         if (!(child->domain->primary)) {
1415                                 primary_domain->startup = True;
1416                                 primary_domain->startup_time = time(NULL);
1417                                 set_domain_online_request(primary_domain);
1418                         }
1419                 }
1420         }
1421         
1422         /*
1423          * We are in idmap child, make sure that we set the
1424          * check_online_event to bring primary domain online.
1425          */
1426         if (child == idmap_child()) {
1427                 set_domain_online_request(primary_domain);
1428         }
1429
1430         /* We might be in the idmap child...*/
1431         if (child->domain && !(child->domain->internal) &&
1432             lp_winbind_offline_logon()) {
1433
1434                 set_domain_online_request(child->domain);
1435
1436                 if (primary_domain && (primary_domain != child->domain)) {
1437                         /* We need to talk to the primary
1438                          * domain as well as the trusted
1439                          * domain inside a trusted domain
1440                          * child.
1441                          * See the code in :
1442                          * set_dc_type_and_flags_trustinfo()
1443                          * for details.
1444                          */
1445                         set_domain_online_request(primary_domain);
1446                 }
1447
1448                 child->lockout_policy_event = event_add_timed(
1449                         winbind_event_context(), NULL, timeval_zero(),
1450                         account_lockout_policy_handler,
1451                         child);
1452         }
1453
1454         if (child->domain && child->domain->primary &&
1455             !USE_KERBEROS_KEYTAB &&
1456             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1457
1458                 struct timeval next_change;
1459
1460                 if (calculate_next_machine_pwd_change(child->domain->name,
1461                                                        &next_change)) {
1462                         child->machine_password_change_event = event_add_timed(
1463                                 winbind_event_context(), NULL, next_change,
1464                                 machine_password_change_handler,
1465                                 child);
1466                 }
1467         }
1468
1469         while (1) {
1470
1471                 int ret;
1472                 fd_set r_fds;
1473                 fd_set w_fds;
1474                 int maxfd;
1475                 struct timeval t;
1476                 struct timeval *tp;
1477                 struct timeval now;
1478                 TALLOC_CTX *frame = talloc_stackframe();
1479
1480                 if (run_events(winbind_event_context(), 0, NULL, NULL)) {
1481                         TALLOC_FREE(frame);
1482                         continue;
1483                 }
1484
1485                 GetTimeOfDay(&now);
1486
1487                 if (child->domain && child->domain->startup &&
1488                                 (now.tv_sec > child->domain->startup_time + 30)) {
1489                         /* No longer in "startup" mode. */
1490                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1491                                 child->domain->name ));
1492                         child->domain->startup = False;
1493                 }
1494
1495                 FD_ZERO(&r_fds);
1496                 FD_ZERO(&w_fds);
1497                 FD_SET(state.sock, &r_fds);
1498                 maxfd = state.sock;
1499
1500                 event_add_to_select_args(winbind_event_context(), &now,
1501                                          &r_fds, &w_fds, &t, &maxfd);
1502                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1503                 if (tp) {
1504                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1505                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1506                 }
1507
1508                 ret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, tp);
1509
1510                 if (run_events(winbind_event_context(), ret, &r_fds, &w_fds)) {
1511                         /* We got a signal - continue. */
1512                         TALLOC_FREE(frame);
1513                         continue;
1514                 }
1515
1516                 if (ret == 0) {
1517                         DEBUG(11,("nothing is ready yet, continue\n"));
1518                         TALLOC_FREE(frame);
1519                         continue;
1520                 }
1521
1522                 if (ret == -1 && errno == EINTR) {
1523                         /* We got a signal - continue. */
1524                         TALLOC_FREE(frame);
1525                         continue;
1526                 }
1527
1528                 if (ret == -1 && errno != EINTR) {
1529                         DEBUG(0,("select error occured\n"));
1530                         TALLOC_FREE(frame);
1531                         perror("select");
1532                         _exit(1);
1533                 }
1534
1535                 /* fetch a request from the main daemon */
1536                 child_read_request(&state);
1537
1538                 if (state.finished) {
1539                         /* we lost contact with our parent */
1540                         _exit(0);
1541                 }
1542
1543                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1544
1545                 ZERO_STRUCT(state.response);
1546                 state.request.null_term = '\0';
1547                 child_process_request(child, &state);
1548
1549                 SAFE_FREE(state.request.extra_data.data);
1550
1551                 cache_store_response(sys_getpid(), &state.response);
1552
1553                 SAFE_FREE(state.response.extra_data.data);
1554
1555                 /* We just send the result code back, the result
1556                  * structure needs to be fetched via the
1557                  * winbindd_cache. Hmm. That needs fixing... */
1558
1559                 if (write_data(state.sock,
1560                                (const char *)&state.response.result,
1561                                sizeof(state.response.result)) !=
1562                     sizeof(state.response.result)) {
1563                         DEBUG(0, ("Could not write result\n"));
1564                         exit(1);
1565                 }
1566                 TALLOC_FREE(frame);
1567         }
1568 }