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