7e53fbbbeeb91570825cf79371e1d2e999fdae6e
[samba.git] / source / 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
38 /* Read some data from a client connection */
39
40 static void child_read_request(struct winbindd_cli_state *state)
41 {
42         ssize_t len;
43
44         /* Read data */
45
46         len = read_data(state->sock, (char *)&state->request,
47                         sizeof(state->request));
48
49         if (len != sizeof(state->request)) {
50                 DEBUG(len > 0 ? 0 : 3, ("Got invalid request length: %d\n", (int)len));
51                 state->finished = True;
52                 return;
53         }
54
55         if (state->request.extra_len == 0) {
56                 state->request.extra_data.data = NULL;
57                 return;
58         }
59
60         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request.extra_len));
61
62         state->request.extra_data.data =
63                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
64
65         if (state->request.extra_data.data == NULL) {
66                 DEBUG(0, ("malloc failed\n"));
67                 state->finished = True;
68                 return;
69         }
70
71         /* Ensure null termination */
72         state->request.extra_data.data[state->request.extra_len] = '\0';
73
74         len = read_data(state->sock, state->request.extra_data.data,
75                         state->request.extra_len);
76
77         if (len != state->request.extra_len) {
78                 DEBUG(0, ("Could not read extra data\n"));
79                 state->finished = True;
80                 return;
81         }
82 }
83
84 /*
85  * Machinery for async requests sent to children. You set up a
86  * winbindd_request, select a child to query, and issue a async_request
87  * call. When the request is completed, the callback function you specified is
88  * called back with the private pointer you gave to async_request.
89  */
90
91 struct winbindd_async_request {
92         struct winbindd_async_request *next, *prev;
93         TALLOC_CTX *mem_ctx;
94         struct winbindd_child *child;
95         struct winbindd_request *request;
96         struct winbindd_response *response;
97         void (*continuation)(void *private_data, BOOL success);
98         struct timed_event *reply_timeout_event;
99         pid_t child_pid; /* pid of the child we're waiting on. Used to detect
100                             a restart of the child (child->pid != child_pid). */
101         void *private_data;
102 };
103
104 static void async_main_request_sent(void *private_data, BOOL success);
105 static void async_request_sent(void *private_data, BOOL success);
106 static void async_reply_recv(void *private_data, BOOL success);
107 static void schedule_async_request(struct winbindd_child *child);
108
109 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
110                    struct winbindd_request *request,
111                    struct winbindd_response *response,
112                    void (*continuation)(void *private_data, BOOL success),
113                    void *private_data)
114 {
115         struct winbindd_async_request *state;
116
117         SMB_ASSERT(continuation != NULL);
118
119         state = TALLOC_P(mem_ctx, struct winbindd_async_request);
120
121         if (state == NULL) {
122                 DEBUG(0, ("talloc failed\n"));
123                 continuation(private_data, False);
124                 return;
125         }
126
127         state->mem_ctx = mem_ctx;
128         state->child = child;
129         state->request = request;
130         state->response = response;
131         state->continuation = continuation;
132         state->private_data = private_data;
133
134         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
135
136         schedule_async_request(child);
137
138         return;
139 }
140
141 static void async_main_request_sent(void *private_data, BOOL success)
142 {
143         struct winbindd_async_request *state =
144                 talloc_get_type_abort(private_data, struct winbindd_async_request);
145
146         if (!success) {
147                 DEBUG(5, ("Could not send async request\n"));
148
149                 state->response->length = sizeof(struct winbindd_response);
150                 state->response->result = WINBINDD_ERROR;
151                 state->continuation(state->private_data, False);
152                 return;
153         }
154
155         if (state->request->extra_len == 0) {
156                 async_request_sent(private_data, True);
157                 return;
158         }
159
160         setup_async_write(&state->child->event, state->request->extra_data.data,
161                           state->request->extra_len,
162                           async_request_sent, state);
163 }
164
165 /****************************************************************
166  Handler triggered if the child winbindd doesn't respond within
167  a given timeout.
168 ****************************************************************/
169
170 static void async_request_timeout_handler(struct event_context *ctx,
171                                         struct timed_event *te,
172                                         const struct timeval *now,
173                                         void *private_data)
174 {
175         struct winbindd_async_request *state =
176                 talloc_get_type_abort(private_data, struct winbindd_async_request);
177
178         DEBUG(0,("async_request_timeout_handler: child pid %u is not responding. "
179                 "Closing connection to it.\n",
180                 state->child_pid ));
181
182         /* Deal with the reply - set to error. */
183         async_reply_recv(private_data, False);
184 }
185
186 /**************************************************************
187  Common function called on both async send and recv fail.
188  Cleans up the child and schedules the next request.
189 **************************************************************/
190
191 static void async_request_fail(struct winbindd_async_request *state)
192 {
193         DLIST_REMOVE(state->child->requests, state);
194
195         TALLOC_FREE(state->reply_timeout_event);
196
197         SMB_ASSERT(state->child_pid != (pid_t)0);
198
199         /* If not already reaped, send kill signal to child. */
200         if (state->child->pid == state->child_pid) {
201                 kill(state->child_pid, SIGTERM);
202
203                 /* 
204                  * Close the socket to the child.
205                  */
206                 winbind_child_died(state->child_pid);
207         }
208
209         state->response->length = sizeof(struct winbindd_response);
210         state->response->result = WINBINDD_ERROR;
211         state->continuation(state->private_data, False);
212 }
213
214 static void async_request_sent(void *private_data_data, BOOL success)
215 {
216         struct winbindd_async_request *state =
217                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
218
219         if (!success) {
220                 DEBUG(5, ("Could not send async request to child pid %u\n",
221                         (unsigned int)state->child_pid ));
222                 async_request_fail(state);
223                 return;
224         }
225
226         /* Request successfully sent to the child, setup the wait for reply */
227
228         setup_async_read(&state->child->event,
229                          &state->response->result,
230                          sizeof(state->response->result),
231                          async_reply_recv, state);
232
233         /* 
234          * Set up a timeout of 300 seconds for the response.
235          * If we don't get it close the child socket and
236          * report failure.
237          */
238
239         state->reply_timeout_event = event_add_timed(winbind_event_context(),
240                                                         NULL,
241                                                         timeval_current_ofs(300,0),
242                                                         "async_request_timeout",
243                                                         async_request_timeout_handler,
244                                                         state);
245         if (!state->reply_timeout_event) {
246                 smb_panic("async_request_sent: failed to add timeout handler.\n");
247         }
248 }
249
250 static void async_reply_recv(void *private_data, BOOL success)
251 {
252         struct winbindd_async_request *state =
253                 talloc_get_type_abort(private_data, struct winbindd_async_request);
254         struct winbindd_child *child = state->child;
255
256         TALLOC_FREE(state->reply_timeout_event);
257
258         state->response->length = sizeof(struct winbindd_response);
259
260         if (!success) {
261                 DEBUG(5, ("Could not receive async reply from child pid %u\n",
262                         (unsigned int)state->child_pid ));
263
264                 cache_cleanup_response(state->child_pid);
265                 async_request_fail(state);
266                 return;
267         }
268
269         SMB_ASSERT(cache_retrieve_response(state->child_pid,
270                                            state->response));
271
272         cache_cleanup_response(state->child_pid);
273         
274         DLIST_REMOVE(child->requests, state);
275
276         schedule_async_request(child);
277
278         state->continuation(state->private_data, True);
279 }
280
281 static BOOL fork_domain_child(struct winbindd_child *child);
282
283 static void schedule_async_request(struct winbindd_child *child)
284 {
285         struct winbindd_async_request *request = child->requests;
286
287         if (request == NULL) {
288                 return;
289         }
290
291         if (child->event.flags != 0) {
292                 return;         /* Busy */
293         }
294
295         if ((child->pid == 0) && (!fork_domain_child(child))) {
296                 /* Cancel all outstanding requests */
297
298                 while (request != NULL) {
299                         /* request might be free'd in the continuation */
300                         struct winbindd_async_request *next = request->next;
301                         request->continuation(request->private_data, False);
302                         request = next;
303                 }
304                 return;
305         }
306
307         /* Now we know who we're sending to - remember the pid. */
308         request->child_pid = child->pid;
309
310         setup_async_write(&child->event, request->request,
311                           sizeof(*request->request),
312                           async_main_request_sent, request);
313
314         return;
315 }
316
317 struct domain_request_state {
318         TALLOC_CTX *mem_ctx;
319         struct winbindd_domain *domain;
320         struct winbindd_request *request;
321         struct winbindd_response *response;
322         void (*continuation)(void *private_data_data, BOOL success);
323         void *private_data_data;
324 };
325
326 static void domain_init_recv(void *private_data_data, BOOL success);
327
328 void async_domain_request(TALLOC_CTX *mem_ctx,
329                           struct winbindd_domain *domain,
330                           struct winbindd_request *request,
331                           struct winbindd_response *response,
332                           void (*continuation)(void *private_data_data, BOOL success),
333                           void *private_data_data)
334 {
335         struct domain_request_state *state;
336
337         if (domain->initialized) {
338                 async_request(mem_ctx, &domain->child, request, response,
339                               continuation, private_data_data);
340                 return;
341         }
342
343         state = TALLOC_P(mem_ctx, struct domain_request_state);
344         if (state == NULL) {
345                 DEBUG(0, ("talloc failed\n"));
346                 continuation(private_data_data, False);
347                 return;
348         }
349
350         state->mem_ctx = mem_ctx;
351         state->domain = domain;
352         state->request = request;
353         state->response = response;
354         state->continuation = continuation;
355         state->private_data_data = private_data_data;
356
357         init_child_connection(domain, domain_init_recv, state);
358 }
359
360 static void domain_init_recv(void *private_data_data, BOOL success)
361 {
362         struct domain_request_state *state =
363                 talloc_get_type_abort(private_data_data, struct domain_request_state);
364
365         if (!success) {
366                 DEBUG(5, ("Domain init returned an error\n"));
367                 state->continuation(state->private_data_data, False);
368                 return;
369         }
370
371         async_request(state->mem_ctx, &state->domain->child,
372                       state->request, state->response,
373                       state->continuation, state->private_data_data);
374 }
375
376 static void recvfrom_child(void *private_data_data, BOOL success)
377 {
378         struct winbindd_cli_state *state =
379                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
380         enum winbindd_result result = state->response.result;
381
382         /* This is an optimization: The child has written directly to the
383          * response buffer. The request itself is still in pending state,
384          * state that in the result code. */
385
386         state->response.result = WINBINDD_PENDING;
387
388         if ((!success) || (result != WINBINDD_OK)) {
389                 request_error(state);
390                 return;
391         }
392
393         request_ok(state);
394 }
395
396 void sendto_child(struct winbindd_cli_state *state,
397                   struct winbindd_child *child)
398 {
399         async_request(state->mem_ctx, child, &state->request,
400                       &state->response, recvfrom_child, state);
401 }
402
403 void sendto_domain(struct winbindd_cli_state *state,
404                    struct winbindd_domain *domain)
405 {
406         async_domain_request(state->mem_ctx, domain,
407                              &state->request, &state->response,
408                              recvfrom_child, state);
409 }
410
411 const struct winbindd_child_dispatch_table domain_dispatch_table[] = {
412
413         { WINBINDD_LOOKUPSID,            winbindd_dual_lookupsid,             "LOOKUPSID" },
414         { WINBINDD_LOOKUPNAME,           winbindd_dual_lookupname,            "LOOKUPNAME" },
415         { WINBINDD_LOOKUPRIDS,           winbindd_dual_lookuprids,            "LOOKUPRIDS" },
416         { WINBINDD_LIST_TRUSTDOM,        winbindd_dual_list_trusted_domains,  "LIST_TRUSTDOM" },
417         { WINBINDD_INIT_CONNECTION,      winbindd_dual_init_connection,       "INIT_CONNECTION" },
418         { WINBINDD_GETDCNAME,            winbindd_dual_getdcname,             "GETDCNAME" },
419         { WINBINDD_SHOW_SEQUENCE,        winbindd_dual_show_sequence,         "SHOW_SEQUENCE" },
420         { WINBINDD_PAM_AUTH,             winbindd_dual_pam_auth,              "PAM_AUTH" },
421         { WINBINDD_PAM_AUTH_CRAP,        winbindd_dual_pam_auth_crap,         "AUTH_CRAP" },
422         { WINBINDD_PAM_LOGOFF,           winbindd_dual_pam_logoff,            "PAM_LOGOFF" },
423         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP,winbindd_dual_pam_chng_pswd_auth_crap,"CHNG_PSWD_AUTH_CRAP" },
424         { WINBINDD_PAM_CHAUTHTOK,        winbindd_dual_pam_chauthtok,         "PAM_CHAUTHTOK" },
425         { WINBINDD_CHECK_MACHACC,        winbindd_dual_check_machine_acct,    "CHECK_MACHACC" },
426         { WINBINDD_DUAL_USERINFO,        winbindd_dual_userinfo,              "DUAL_USERINFO" },
427         { WINBINDD_GETUSERDOMGROUPS,     winbindd_dual_getuserdomgroups,      "GETUSERDOMGROUPS" },
428         { WINBINDD_DUAL_GETSIDALIASES,   winbindd_dual_getsidaliases,         "GETSIDALIASES" },
429         { WINBINDD_CCACHE_NTLMAUTH,      winbindd_dual_ccache_ntlm_auth,      "CCACHE_NTLM_AUTH" },
430         /* End of list */
431
432         { WINBINDD_NUM_CMDS, NULL, "NONE" }
433 };
434
435 static void child_process_request(struct winbindd_child *child,
436                                   struct winbindd_cli_state *state)
437 {
438         struct winbindd_domain *domain = child->domain;
439         const struct winbindd_child_dispatch_table *table = child->table;
440
441         /* Free response data - we may be interrupted and receive another
442            command before being able to send this data off. */
443
444         state->response.result = WINBINDD_ERROR;
445         state->response.length = sizeof(struct winbindd_response);
446
447         /* as all requests in the child are sync, we can use talloc_tos() */
448         state->mem_ctx = talloc_tos();
449
450         /* Process command */
451
452         for (; table->fn; table++) {
453                 if (state->request.cmd == table->cmd) {
454                         DEBUG(10,("process_request: request fn %s\n",
455                                   table->winbindd_cmd_name ));
456                         state->response.result = table->fn(domain, state);
457                         break;
458                 }
459         }
460
461         if (!table->fn) {
462                 DEBUG(1 ,("child_process_request: unknown request fn number %d\n",
463                           (int)state->request.cmd ));
464                 state->response.result = WINBINDD_ERROR;
465         }
466 }
467
468 void setup_domain_child(struct winbindd_domain *domain,
469                         struct winbindd_child *child,
470                         const struct winbindd_child_dispatch_table *table,
471                         const char *explicit_logfile)
472 {
473         if (explicit_logfile != NULL) {
474                 pstr_sprintf(child->logfilename, "%s/log.winbindd-%s",
475                              dyn_LOGFILEBASE, explicit_logfile);
476         } else if (domain != NULL) {
477                 pstr_sprintf(child->logfilename, "%s/log.wb-%s",
478                              dyn_LOGFILEBASE, domain->name);
479         } else {
480                 smb_panic("Internal error: domain == NULL && "
481                           "explicit_logfile == NULL");
482         }
483
484         child->domain = domain;
485         child->table = table;
486 }
487
488 struct winbindd_child *children = NULL;
489
490 void winbind_child_died(pid_t pid)
491 {
492         struct winbindd_child *child;
493
494         for (child = children; child != NULL; child = child->next) {
495                 if (child->pid == pid) {
496                         break;
497                 }
498         }
499
500         if (child == NULL) {
501                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
502                 return;
503         }
504
505         remove_fd_event(&child->event);
506         close(child->event.fd);
507         child->event.fd = 0;
508         child->event.flags = 0;
509         child->pid = 0;
510
511         schedule_async_request(child);
512 }
513
514 /* Ensure any negative cache entries with the netbios or realm names are removed. */
515
516 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
517 {
518         flush_negative_conn_cache_for_domain(domain->name);
519         if (*domain->alt_name) {
520                 flush_negative_conn_cache_for_domain(domain->alt_name);
521         }
522 }
523
524 /* Set our domains as offline and forward the offline message to our children. */
525
526 void winbind_msg_offline(struct messaging_context *msg_ctx,
527                          void *private_data,
528                          uint32_t msg_type,
529                          struct server_id server_id,
530                          DATA_BLOB *data)
531 {
532         struct winbindd_child *child;
533         struct winbindd_domain *domain;
534
535         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
536
537         if (!lp_winbind_offline_logon()) {
538                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
539                 return;
540         }
541
542         /* Set our global state as offline. */
543         if (!set_global_winbindd_state_offline()) {
544                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
545                 return;
546         }
547
548         /* Set all our domains as offline. */
549         for (domain = domain_list(); domain; domain = domain->next) {
550                 if (domain->internal) {
551                         continue;
552                 }
553                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
554                 set_domain_offline(domain);
555         }
556
557         for (child = children; child != NULL; child = child->next) {
558                 /* Don't send message to internal childs.  We've already
559                    done so above. */
560                 if (!child->domain || winbindd_internal_child(child)) {
561                         continue;
562                 }
563
564                 /* Or internal domains (this should not be possible....) */
565                 if (child->domain->internal) {
566                         continue;
567                 }
568
569                 /* Each winbindd child should only process requests for one domain - make sure
570                    we only set it online / offline for that domain. */
571
572                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
573                         (unsigned int)child->pid, domain->name ));
574
575                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
576                                    MSG_WINBIND_OFFLINE,
577                                    (uint8 *)child->domain->name,
578                                    strlen(child->domain->name)+1);
579         }
580 }
581
582 /* Set our domains as online and forward the online message to our children. */
583
584 void winbind_msg_online(struct messaging_context *msg_ctx,
585                         void *private_data,
586                         uint32_t msg_type,
587                         struct server_id server_id,
588                         DATA_BLOB *data)
589 {
590         struct winbindd_child *child;
591         struct winbindd_domain *domain;
592
593         DEBUG(10,("winbind_msg_online: got online message.\n"));
594
595         if (!lp_winbind_offline_logon()) {
596                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
597                 return;
598         }
599
600         /* Set our global state as online. */
601         set_global_winbindd_state_online();
602
603         smb_nscd_flush_user_cache();
604         smb_nscd_flush_group_cache();
605
606         /* Set all our domains as online. */
607         for (domain = domain_list(); domain; domain = domain->next) {
608                 if (domain->internal) {
609                         continue;
610                 }
611                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
612
613                 winbindd_flush_negative_conn_cache(domain);
614                 set_domain_online_request(domain);
615
616                 /* Send an online message to the idmap child when our
617                    primary domain comes back online */
618
619                 if ( domain->primary ) {
620                         struct winbindd_child *idmap = idmap_child();
621                         
622                         if ( idmap->pid != 0 ) {
623                                 messaging_send_buf(msg_ctx,
624                                                    pid_to_procid(idmap->pid), 
625                                                    MSG_WINBIND_ONLINE,
626                                                    (uint8 *)domain->name,
627                                                    strlen(domain->name)+1);
628                         }
629                         
630                 }
631         }
632
633         for (child = children; child != NULL; child = child->next) {
634                 /* Don't send message to internal childs. */
635                 if (!child->domain || winbindd_internal_child(child)) {
636                         continue;
637                 }
638
639                 /* Or internal domains (this should not be possible....) */
640                 if (child->domain->internal) {
641                         continue;
642                 }
643
644                 /* Each winbindd child should only process requests for one domain - make sure
645                    we only set it online / offline for that domain. */
646
647                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
648                         (unsigned int)child->pid, child->domain->name ));
649
650                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
651                                    MSG_WINBIND_ONLINE,
652                                    (uint8 *)child->domain->name,
653                                    strlen(child->domain->name)+1);
654         }
655 }
656
657 /* Forward the online/offline messages to our children. */
658 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
659                               void *private_data,
660                               uint32_t msg_type,
661                               struct server_id server_id,
662                               DATA_BLOB *data)
663 {
664         struct winbindd_child *child;
665
666         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
667
668         for (child = children; child != NULL; child = child->next) {
669                 if (child->domain && child->domain->primary) {
670                         DEBUG(10,("winbind_msg_onlinestatus: "
671                                   "sending message to pid %u of primary domain.\n",
672                                   (unsigned int)child->pid));
673                         messaging_send_buf(msg_ctx, pid_to_procid(child->pid), 
674                                            MSG_WINBIND_ONLINESTATUS,
675                                            (uint8 *)data->data,
676                                            data->length);
677                         break;
678                 }
679         }
680 }
681
682 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
683                                  void *private_data,
684                                  uint32_t msg_type,
685                                  struct server_id server_id,
686                                  DATA_BLOB *data)
687 {
688         struct winbindd_child *child;
689
690         DEBUG(10,("winbind_msg_dump_event_list received\n"));
691
692         dump_event_list(winbind_event_context());
693
694         for (child = children; child != NULL; child = child->next) {
695
696                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
697                         (unsigned int)child->pid));
698
699                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
700                                    MSG_DUMP_EVENT_LIST,
701                                    NULL, 0);
702         }
703
704 }
705
706 static void account_lockout_policy_handler(struct event_context *ctx,
707                                            struct timed_event *te,
708                                            const struct timeval *now,
709                                            void *private_data)
710 {
711         struct winbindd_child *child =
712                 (struct winbindd_child *)private_data;
713         TALLOC_CTX *mem_ctx = NULL;
714         struct winbindd_methods *methods;
715         SAM_UNK_INFO_12 lockout_policy;
716         NTSTATUS result;
717
718         DEBUG(10,("account_lockout_policy_handler called\n"));
719
720         TALLOC_FREE(child->lockout_policy_event);
721
722         if ( !winbindd_can_contact_domain( child->domain ) ) {
723                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
724                           "do not have an incoming trust to domain %s\n", 
725                           child->domain->name));
726
727                 return;         
728         }
729
730         methods = child->domain->methods;
731
732         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
733         if (!mem_ctx) {
734                 result = NT_STATUS_NO_MEMORY;
735         } else {
736                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
737         }
738         TALLOC_FREE(mem_ctx);
739
740         if (!NT_STATUS_IS_OK(result)) {
741                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
742                          nt_errstr(result)));
743         }
744
745         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
746                                                       timeval_current_ofs(3600, 0),
747                                                       "account_lockout_policy_handler",
748                                                       account_lockout_policy_handler,
749                                                       child);
750 }
751
752 /* Deal with a request to go offline. */
753
754 static void child_msg_offline(struct messaging_context *msg,
755                               void *private_data,
756                               uint32_t msg_type,
757                               struct server_id server_id,
758                               DATA_BLOB *data)
759 {
760         struct winbindd_domain *domain;
761         const char *domainname = (const char *)data->data;
762
763         if (data->data == NULL || data->length == 0) {
764                 return;
765         }
766
767         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
768
769         if (!lp_winbind_offline_logon()) {
770                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
771                 return;
772         }
773
774         /* Mark the requested domain offline. */
775
776         for (domain = domain_list(); domain; domain = domain->next) {
777                 if (domain->internal) {
778                         continue;
779                 }
780                 if (strequal(domain->name, domainname)) {
781                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
782                         set_domain_offline(domain);
783                 }
784         }
785 }
786
787 /* Deal with a request to go online. */
788
789 static void child_msg_online(struct messaging_context *msg,
790                              void *private_data,
791                              uint32_t msg_type,
792                              struct server_id server_id,
793                              DATA_BLOB *data)
794 {
795         struct winbindd_domain *domain;
796         const char *domainname = (const char *)data->data;
797
798         if (data->data == NULL || data->length == 0) {
799                 return;
800         }
801
802         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
803
804         if (!lp_winbind_offline_logon()) {
805                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
806                 return;
807         }
808
809         /* Set our global state as online. */
810         set_global_winbindd_state_online();
811
812         /* Try and mark everything online - delete any negative cache entries
813            to force a reconnect now. */
814
815         for (domain = domain_list(); domain; domain = domain->next) {
816                 if (domain->internal) {
817                         continue;
818                 }
819                 if (strequal(domain->name, domainname)) {
820                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
821                         winbindd_flush_negative_conn_cache(domain);
822                         set_domain_online_request(domain);
823                 }
824         }
825 }
826
827 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
828 {
829         struct winbindd_domain *domain;
830         char *buf = NULL;
831
832         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
833                                    get_global_winbindd_state_offline() ? 
834                                    "Offline":"Online")) == NULL) {
835                 return NULL;
836         }
837
838         for (domain = domain_list(); domain; domain = domain->next) {
839                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
840                                                   domain->name, 
841                                                   domain->online ?
842                                                   "Online":"Offline")) == NULL) {
843                         return NULL;
844                 }
845         }
846
847         buf = talloc_asprintf_append_buffer(buf, "\n");
848
849         DEBUG(5,("collect_onlinestatus: %s", buf));
850
851         return buf;
852 }
853
854 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
855                                    void *private_data,
856                                    uint32_t msg_type,
857                                    struct server_id server_id,
858                                    DATA_BLOB *data)
859 {
860         TALLOC_CTX *mem_ctx;
861         const char *message;
862         struct server_id *sender;
863         
864         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
865
866         if (!data->data) {
867                 return;
868         }
869
870         sender = (struct server_id *)data->data;
871
872         mem_ctx = talloc_init("winbind_msg_onlinestatus");
873         if (mem_ctx == NULL) {
874                 return;
875         }
876         
877         message = collect_onlinestatus(mem_ctx);
878         if (message == NULL) {
879                 talloc_destroy(mem_ctx);
880                 return;
881         }
882
883         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
884                            (uint8 *)message, strlen(message) + 1);
885
886         talloc_destroy(mem_ctx);
887 }
888
889 static void child_msg_dump_event_list(struct messaging_context *msg,
890                                       void *private_data,
891                                       uint32_t msg_type,
892                                       struct server_id server_id,
893                                       DATA_BLOB *data)
894 {
895         DEBUG(5,("child_msg_dump_event_list received\n"));
896
897         dump_event_list(winbind_event_context());
898 }
899
900
901 static BOOL fork_domain_child(struct winbindd_child *child)
902 {
903         int fdpair[2];
904         struct winbindd_cli_state state;
905         struct winbindd_domain *domain;
906
907         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
908                 DEBUG(0, ("Could not open child pipe: %s\n",
909                           strerror(errno)));
910                 return False;
911         }
912
913         ZERO_STRUCT(state);
914         state.pid = sys_getpid();
915
916         /* Stop zombies */
917         CatchChild();
918
919         child->pid = sys_fork();
920
921         if (child->pid == -1) {
922                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
923                 return False;
924         }
925
926         if (child->pid != 0) {
927                 /* Parent */
928                 close(fdpair[0]);
929                 child->next = child->prev = NULL;
930                 DLIST_ADD(children, child);
931                 child->event.fd = fdpair[1];
932                 child->event.flags = 0;
933                 child->requests = NULL;
934                 add_fd_event(&child->event);
935                 return True;
936         }
937
938         /* Child */
939
940         state.sock = fdpair[0];
941         close(fdpair[1]);
942
943         /* tdb needs special fork handling */
944         if (tdb_reopen_all(1) == -1) {
945                 DEBUG(0,("tdb_reopen_all failed.\n"));
946                 _exit(0);
947         }
948
949         close_conns_after_fork();
950
951         if (!override_logfile) {
952                 lp_set_logfile(child->logfilename);
953                 reopen_logs();
954         }
955
956         /*
957          * For clustering, we need to re-init our ctdbd connection after the
958          * fork
959          */
960         if (!NT_STATUS_IS_OK(messaging_reinit(winbind_messaging_context())))
961                 exit(1);
962
963         /* Don't handle the same messages as our parent. */
964         messaging_deregister(winbind_messaging_context(),
965                              MSG_SMB_CONF_UPDATED, NULL);
966         messaging_deregister(winbind_messaging_context(),
967                              MSG_SHUTDOWN, NULL);
968         messaging_deregister(winbind_messaging_context(),
969                              MSG_WINBIND_OFFLINE, NULL);
970         messaging_deregister(winbind_messaging_context(),
971                              MSG_WINBIND_ONLINE, NULL);
972         messaging_deregister(winbind_messaging_context(),
973                              MSG_WINBIND_ONLINESTATUS, NULL);
974         messaging_deregister(winbind_messaging_context(),
975                              MSG_DUMP_EVENT_LIST, NULL);
976
977         /* Handle online/offline messages. */
978         messaging_register(winbind_messaging_context(), NULL,
979                            MSG_WINBIND_OFFLINE, child_msg_offline);
980         messaging_register(winbind_messaging_context(), NULL,
981                            MSG_WINBIND_ONLINE, child_msg_online);
982         messaging_register(winbind_messaging_context(), NULL,
983                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
984         messaging_register(winbind_messaging_context(), NULL,
985                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
986
987         if ( child->domain ) {
988                 child->domain->startup = True;
989                 child->domain->startup_time = time(NULL);
990         }
991
992         /* Ensure we have no pending check_online events other
993            than one for this domain. */
994
995         for (domain = domain_list(); domain; domain = domain->next) {
996                 if (domain != child->domain) {
997                         TALLOC_FREE(domain->check_online_event);
998                 }
999         }
1000
1001         /* Ensure we're not handling an event inherited from
1002            our parent. */
1003
1004         cancel_named_event(winbind_event_context(),
1005                            "krb5_ticket_refresh_handler");
1006
1007         /* We might be in the idmap child...*/
1008         if (child->domain && !(child->domain->internal) &&
1009             lp_winbind_offline_logon()) {
1010
1011                 set_domain_online_request(child->domain);
1012
1013                 child->lockout_policy_event = event_add_timed(
1014                         winbind_event_context(), NULL, timeval_zero(),
1015                         "account_lockout_policy_handler",
1016                         account_lockout_policy_handler,
1017                         child);
1018         }
1019
1020         while (1) {
1021
1022                 int ret;
1023                 fd_set read_fds;
1024                 struct timeval t;
1025                 struct timeval *tp;
1026                 struct timeval now;
1027                 TALLOC_CTX *frame = talloc_stackframe();
1028
1029                 run_events(winbind_event_context(), 0, NULL, NULL);
1030
1031                 GetTimeOfDay(&now);
1032
1033                 if (child->domain && child->domain->startup &&
1034                                 (now.tv_sec > child->domain->startup_time + 30)) {
1035                         /* No longer in "startup" mode. */
1036                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1037                                 child->domain->name ));
1038                         child->domain->startup = False;
1039                 }
1040
1041                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1042                 if (tp) {
1043                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1044                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1045                 }
1046
1047                 /* Handle messages */
1048
1049                 message_dispatch(winbind_messaging_context());
1050
1051                 FD_ZERO(&read_fds);
1052                 FD_SET(state.sock, &read_fds);
1053
1054                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
1055
1056                 if (ret == 0) {
1057                         DEBUG(11,("nothing is ready yet, continue\n"));
1058                         TALLOC_FREE(frame);
1059                         continue;
1060                 }
1061
1062                 if (ret == -1 && errno == EINTR) {
1063                         /* We got a signal - continue. */
1064                         TALLOC_FREE(frame);
1065                         continue;
1066                 }
1067
1068                 if (ret == -1 && errno != EINTR) {
1069                         DEBUG(0,("select error occured\n"));
1070                         TALLOC_FREE(frame);
1071                         perror("select");
1072                         return False;
1073                 }
1074
1075                 /* fetch a request from the main daemon */
1076                 child_read_request(&state);
1077
1078                 if (state.finished) {
1079                         /* we lost contact with our parent */
1080                         exit(0);
1081                 }
1082
1083                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1084
1085                 ZERO_STRUCT(state.response);
1086                 state.request.null_term = '\0';
1087                 child_process_request(child, &state);
1088
1089                 SAFE_FREE(state.request.extra_data.data);
1090
1091                 cache_store_response(sys_getpid(), &state.response);
1092
1093                 SAFE_FREE(state.response.extra_data.data);
1094
1095                 /* We just send the result code back, the result
1096                  * structure needs to be fetched via the
1097                  * winbindd_cache. Hmm. That needs fixing... */
1098
1099                 if (write_data(state.sock,
1100                                (const char *)&state.response.result,
1101                                sizeof(state.response.result)) !=
1102                     sizeof(state.response.result)) {
1103                         DEBUG(0, ("Could not write result\n"));
1104                         exit(1);
1105                 }
1106                 TALLOC_FREE(frame);
1107         }
1108 }