r19209: Ensure we don't make mistakes by sending online/offline
[sfrench/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 2 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 /* Read some data from a client connection */
38
39 static void child_read_request(struct winbindd_cli_state *state)
40 {
41         ssize_t len;
42
43         /* Read data */
44
45         len = read_data(state->sock, (char *)&state->request,
46                         sizeof(state->request));
47
48         if (len != sizeof(state->request)) {
49                 DEBUG(len > 0 ? 0 : 3, ("Got invalid request length: %d\n", (int)len));
50                 state->finished = True;
51                 return;
52         }
53
54         if (state->request.extra_len == 0) {
55                 state->request.extra_data.data = NULL;
56                 return;
57         }
58
59         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request.extra_len));
60
61         state->request.extra_data.data =
62                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
63
64         if (state->request.extra_data.data == NULL) {
65                 DEBUG(0, ("malloc failed\n"));
66                 state->finished = True;
67                 return;
68         }
69
70         /* Ensure null termination */
71         state->request.extra_data.data[state->request.extra_len] = '\0';
72
73         len = read_data(state->sock, state->request.extra_data.data,
74                         state->request.extra_len);
75
76         if (len != state->request.extra_len) {
77                 DEBUG(0, ("Could not read extra data\n"));
78                 state->finished = True;
79                 return;
80         }
81 }
82
83 /*
84  * Machinery for async requests sent to children. You set up a
85  * winbindd_request, select a child to query, and issue a async_request
86  * call. When the request is completed, the callback function you specified is
87  * called back with the private pointer you gave to async_request.
88  */
89
90 struct winbindd_async_request {
91         struct winbindd_async_request *next, *prev;
92         TALLOC_CTX *mem_ctx;
93         struct winbindd_child *child;
94         struct winbindd_request *request;
95         struct winbindd_response *response;
96         void (*continuation)(void *private_data, BOOL success);
97         void *private_data;
98 };
99
100 static void async_main_request_sent(void *private_data, BOOL success);
101 static void async_request_sent(void *private_data, BOOL success);
102 static void async_reply_recv(void *private_data, BOOL success);
103 static void schedule_async_request(struct winbindd_child *child);
104
105 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
106                    struct winbindd_request *request,
107                    struct winbindd_response *response,
108                    void (*continuation)(void *private_data, BOOL success),
109                    void *private_data)
110 {
111         struct winbindd_async_request *state;
112
113         SMB_ASSERT(continuation != NULL);
114
115         state = TALLOC_P(mem_ctx, struct winbindd_async_request);
116
117         if (state == NULL) {
118                 DEBUG(0, ("talloc failed\n"));
119                 continuation(private_data, False);
120                 return;
121         }
122
123         state->mem_ctx = mem_ctx;
124         state->child = child;
125         state->request = request;
126         state->response = response;
127         state->continuation = continuation;
128         state->private_data = private_data;
129
130         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
131
132         schedule_async_request(child);
133
134         return;
135 }
136
137 static void async_main_request_sent(void *private_data, BOOL success)
138 {
139         struct winbindd_async_request *state =
140                 talloc_get_type_abort(private_data, struct winbindd_async_request);
141
142         if (!success) {
143                 DEBUG(5, ("Could not send async request\n"));
144
145                 state->response->length = sizeof(struct winbindd_response);
146                 state->response->result = WINBINDD_ERROR;
147                 state->continuation(state->private_data, False);
148                 return;
149         }
150
151         if (state->request->extra_len == 0) {
152                 async_request_sent(private_data, True);
153                 return;
154         }
155
156         setup_async_write(&state->child->event, state->request->extra_data.data,
157                           state->request->extra_len,
158                           async_request_sent, state);
159 }
160
161 static void async_request_sent(void *private_data_data, BOOL success)
162 {
163         struct winbindd_async_request *state =
164                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
165
166         if (!success) {
167                 DEBUG(5, ("Could not send async request\n"));
168
169                 state->response->length = sizeof(struct winbindd_response);
170                 state->response->result = WINBINDD_ERROR;
171                 state->continuation(state->private_data, False);
172                 return;
173         }
174
175         /* Request successfully sent to the child, setup the wait for reply */
176
177         setup_async_read(&state->child->event,
178                          &state->response->result,
179                          sizeof(state->response->result),
180                          async_reply_recv, state);
181 }
182
183 static void async_reply_recv(void *private_data, BOOL success)
184 {
185         struct winbindd_async_request *state =
186                 talloc_get_type_abort(private_data, struct winbindd_async_request);
187         struct winbindd_child *child = state->child;
188
189         state->response->length = sizeof(struct winbindd_response);
190
191         if (!success) {
192                 DEBUG(5, ("Could not receive async reply\n"));
193                 state->response->result = WINBINDD_ERROR;
194                 return;
195         }
196
197         SMB_ASSERT(cache_retrieve_response(child->pid,
198                                            state->response));
199
200         cache_cleanup_response(child->pid);
201         
202         DLIST_REMOVE(child->requests, state);
203
204         schedule_async_request(child);
205
206         state->continuation(state->private_data, True);
207 }
208
209 static BOOL fork_domain_child(struct winbindd_child *child);
210
211 static void schedule_async_request(struct winbindd_child *child)
212 {
213         struct winbindd_async_request *request = child->requests;
214
215         if (request == NULL) {
216                 return;
217         }
218
219         if (child->event.flags != 0) {
220                 return;         /* Busy */
221         }
222
223         if ((child->pid == 0) && (!fork_domain_child(child))) {
224                 /* Cancel all outstanding requests */
225
226                 while (request != NULL) {
227                         /* request might be free'd in the continuation */
228                         struct winbindd_async_request *next = request->next;
229                         request->continuation(request->private_data, False);
230                         request = next;
231                 }
232                 return;
233         }
234
235         setup_async_write(&child->event, request->request,
236                           sizeof(*request->request),
237                           async_main_request_sent, request);
238
239         talloc_destroy(child->mem_ctx);
240         return;
241 }
242
243 struct domain_request_state {
244         TALLOC_CTX *mem_ctx;
245         struct winbindd_domain *domain;
246         struct winbindd_request *request;
247         struct winbindd_response *response;
248         void (*continuation)(void *private_data_data, BOOL success);
249         void *private_data_data;
250 };
251
252 static void domain_init_recv(void *private_data_data, BOOL success);
253
254 void async_domain_request(TALLOC_CTX *mem_ctx,
255                           struct winbindd_domain *domain,
256                           struct winbindd_request *request,
257                           struct winbindd_response *response,
258                           void (*continuation)(void *private_data_data, BOOL success),
259                           void *private_data_data)
260 {
261         struct domain_request_state *state;
262
263         if (domain->initialized) {
264                 async_request(mem_ctx, &domain->child, request, response,
265                               continuation, private_data_data);
266                 return;
267         }
268
269         state = TALLOC_P(mem_ctx, struct domain_request_state);
270         if (state == NULL) {
271                 DEBUG(0, ("talloc failed\n"));
272                 continuation(private_data_data, False);
273                 return;
274         }
275
276         state->mem_ctx = mem_ctx;
277         state->domain = domain;
278         state->request = request;
279         state->response = response;
280         state->continuation = continuation;
281         state->private_data_data = private_data_data;
282
283         init_child_connection(domain, domain_init_recv, state);
284 }
285
286 static void recvfrom_child(void *private_data_data, BOOL success)
287 {
288         struct winbindd_cli_state *state =
289                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
290         enum winbindd_result result = state->response.result;
291
292         /* This is an optimization: The child has written directly to the
293          * response buffer. The request itself is still in pending state,
294          * state that in the result code. */
295
296         state->response.result = WINBINDD_PENDING;
297
298         if ((!success) || (result != WINBINDD_OK)) {
299                 request_error(state);
300                 return;
301         }
302
303         request_ok(state);
304 }
305
306 void sendto_child(struct winbindd_cli_state *state,
307                   struct winbindd_child *child)
308 {
309         async_request(state->mem_ctx, child, &state->request,
310                       &state->response, recvfrom_child, state);
311 }
312
313 void sendto_domain(struct winbindd_cli_state *state,
314                    struct winbindd_domain *domain)
315 {
316         async_domain_request(state->mem_ctx, domain,
317                              &state->request, &state->response,
318                              recvfrom_child, state);
319 }
320
321 static void domain_init_recv(void *private_data_data, BOOL success)
322 {
323         struct domain_request_state *state =
324                 talloc_get_type_abort(private_data_data, struct domain_request_state);
325
326         if (!success) {
327                 DEBUG(5, ("Domain init returned an error\n"));
328                 state->continuation(state->private_data_data, False);
329                 return;
330         }
331
332         async_request(state->mem_ctx, &state->domain->child,
333                       state->request, state->response,
334                       state->continuation, state->private_data_data);
335 }
336
337 struct winbindd_child_dispatch_table {
338         enum winbindd_cmd cmd;
339         enum winbindd_result (*fn)(struct winbindd_domain *domain,
340                                    struct winbindd_cli_state *state);
341         const char *winbindd_cmd_name;
342 };
343
344 static struct winbindd_child_dispatch_table child_dispatch_table[] = {
345         
346         { WINBINDD_LOOKUPSID,            winbindd_dual_lookupsid,             "LOOKUPSID" },
347         { WINBINDD_LOOKUPNAME,           winbindd_dual_lookupname,            "LOOKUPNAME" },
348         { WINBINDD_LOOKUPRIDS,           winbindd_dual_lookuprids,            "LOOKUPRIDS" },
349         { WINBINDD_LIST_TRUSTDOM,        winbindd_dual_list_trusted_domains,  "LIST_TRUSTDOM" },
350         { WINBINDD_INIT_CONNECTION,      winbindd_dual_init_connection,       "INIT_CONNECTION" },
351         { WINBINDD_GETDCNAME,            winbindd_dual_getdcname,             "GETDCNAME" },
352         { WINBINDD_SHOW_SEQUENCE,        winbindd_dual_show_sequence,         "SHOW_SEQUENCE" },
353         { WINBINDD_PAM_AUTH,             winbindd_dual_pam_auth,              "PAM_AUTH" },
354         { WINBINDD_PAM_AUTH_CRAP,        winbindd_dual_pam_auth_crap,         "AUTH_CRAP" },
355         { WINBINDD_PAM_LOGOFF,           winbindd_dual_pam_logoff,            "PAM_LOGOFF" },
356         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP,winbindd_dual_pam_chng_pswd_auth_crap,"CHNG_PSWD_AUTH_CRAP" },
357         { WINBINDD_CHECK_MACHACC,        winbindd_dual_check_machine_acct,    "CHECK_MACHACC" },
358         { WINBINDD_DUAL_SID2UID,         winbindd_dual_sid2uid,               "DUAL_SID2UID" },
359         { WINBINDD_DUAL_SID2GID,         winbindd_dual_sid2gid,               "DUAL_SID2GID" },
360         { WINBINDD_DUAL_UID2SID,         winbindd_dual_uid2sid,               "DUAL_UID2SID" },
361         { WINBINDD_DUAL_GID2SID,         winbindd_dual_gid2sid,               "DUAL_GID2SID" },
362         { WINBINDD_DUAL_UID2NAME,        winbindd_dual_uid2name,              "DUAL_UID2NAME" },
363         { WINBINDD_DUAL_NAME2UID,        winbindd_dual_name2uid,              "DUAL_NAME2UID" },
364         { WINBINDD_DUAL_GID2NAME,        winbindd_dual_gid2name,              "DUAL_GID2NAME" },
365         { WINBINDD_DUAL_NAME2GID,        winbindd_dual_name2gid,              "DUAL_NAME2GID" },
366         { WINBINDD_DUAL_IDMAPSET,        winbindd_dual_idmapset,              "DUAL_IDMAPSET" },
367         { WINBINDD_DUAL_USERINFO,        winbindd_dual_userinfo,              "DUAL_USERINFO" },
368         { WINBINDD_ALLOCATE_UID,         winbindd_dual_allocate_uid,          "ALLOCATE_UID" },
369         { WINBINDD_ALLOCATE_GID,         winbindd_dual_allocate_gid,          "ALLOCATE_GID" },
370         { WINBINDD_GETUSERDOMGROUPS,     winbindd_dual_getuserdomgroups,      "GETUSERDOMGROUPS" },
371         { WINBINDD_DUAL_GETSIDALIASES,   winbindd_dual_getsidaliases,         "GETSIDALIASES" },
372         { WINBINDD_CCACHE_NTLMAUTH,      winbindd_dual_ccache_ntlm_auth,      "CCACHE_NTLM_AUTH" },
373         /* End of list */
374
375         { WINBINDD_NUM_CMDS, NULL, "NONE" }
376 };
377
378 static void child_process_request(struct winbindd_domain *domain,
379                                   struct winbindd_cli_state *state)
380 {
381         struct winbindd_child_dispatch_table *table;
382
383         /* Free response data - we may be interrupted and receive another
384            command before being able to send this data off. */
385
386         state->response.result = WINBINDD_ERROR;
387         state->response.length = sizeof(struct winbindd_response);
388
389         state->mem_ctx = talloc_init("winbind request");
390         if (state->mem_ctx == NULL)
391                 return;
392
393         /* Process command */
394
395         for (table = child_dispatch_table; table->fn; table++) {
396                 if (state->request.cmd == table->cmd) {
397                         DEBUG(10,("process_request: request fn %s\n",
398                                   table->winbindd_cmd_name ));
399                         state->response.result = table->fn(domain, state);
400                         break;
401                 }
402         }
403
404         if (!table->fn) {
405                 DEBUG(10,("process_request: unknown request fn number %d\n",
406                           (int)state->request.cmd ));
407                 state->response.result = WINBINDD_ERROR;
408         }
409
410         talloc_destroy(state->mem_ctx);
411 }
412
413 void setup_domain_child(struct winbindd_domain *domain,
414                         struct winbindd_child *child,
415                         const char *explicit_logfile)
416 {
417         if (explicit_logfile != NULL) {
418                 pstr_sprintf(child->logfilename, "%s/log.winbindd-%s",
419                              dyn_LOGFILEBASE, explicit_logfile);
420         } else if (domain != NULL) {
421                 pstr_sprintf(child->logfilename, "%s/log.wb-%s",
422                              dyn_LOGFILEBASE, domain->name);
423         } else {
424                 smb_panic("Internal error: domain == NULL && "
425                           "explicit_logfile == NULL");
426         }
427
428         child->domain = domain;
429 }
430
431 struct winbindd_child *children = NULL;
432
433 void winbind_child_died(pid_t pid)
434 {
435         struct winbindd_child *child;
436
437         for (child = children; child != NULL; child = child->next) {
438                 if (child->pid == pid) {
439                         break;
440                 }
441         }
442
443         if (child == NULL) {
444                 DEBUG(0, ("Unknown child %d died!\n", pid));
445                 return;
446         }
447
448         remove_fd_event(&child->event);
449         close(child->event.fd);
450         child->event.fd = 0;
451         child->event.flags = 0;
452         child->pid = 0;
453
454         schedule_async_request(child);
455 }
456
457 /* Ensure any negative cache entries with the netbios or realm names are removed. */
458
459 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
460 {
461         flush_negative_conn_cache_for_domain(domain->name);
462         if (*domain->alt_name) {
463                 flush_negative_conn_cache_for_domain(domain->alt_name);
464         }
465 }
466
467 /* Set our domains as offline and forward the offline message to our children. */
468
469 void winbind_msg_offline(int msg_type, struct process_id src, void *buf, size_t len)
470 {
471         struct winbindd_child *child;
472         struct winbindd_domain *domain;
473
474         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
475
476         if (!lp_winbind_offline_logon()) {
477                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
478                 return;
479         }
480
481         /* Set our global state as offline. */
482         if (!set_global_winbindd_state_offline()) {
483                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
484                 return;
485         }
486
487         /* Set all our domains as offline. */
488         for (domain = domain_list(); domain; domain = domain->next) {
489                 if (domain->internal) {
490                         continue;
491                 }
492                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
493                 set_domain_offline(domain);
494         }
495
496         for (child = children; child != NULL; child = child->next) {
497                 /* Don't send message to idmap child. */
498                 if (!child->domain || (child == idmap_child())) {
499                         continue;
500                 }
501
502                 /* Or internal domains (this should not be possible....) */
503                 if (child->domain->internal) {
504                         continue;
505                 }
506
507                 /* Each winbindd child should only process requests for one domain - make sure
508                    we only set it online / offline for that domain. */
509
510                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
511                         (unsigned int)child->pid, domain->name ));
512
513                 message_send_pid(pid_to_procid(child->pid), MSG_WINBIND_OFFLINE, domain->name,
514                         strlen(domain->name)+1, False);
515         }
516 }
517
518 /* Set our domains as online and forward the online message to our children. */
519
520 void winbind_msg_online(int msg_type, struct process_id src, void *buf, size_t len)
521 {
522         struct winbindd_child *child;
523         struct winbindd_domain *domain;
524
525         DEBUG(10,("winbind_msg_online: got online message.\n"));
526
527         if (!lp_winbind_offline_logon()) {
528                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
529                 return;
530         }
531
532         /* Set our global state as online. */
533         set_global_winbindd_state_online();
534
535         smb_nscd_flush_user_cache();
536         smb_nscd_flush_group_cache();
537
538         /* Set all our domains as online. */
539         for (domain = domain_list(); domain; domain = domain->next) {
540                 if (domain->internal) {
541                         continue;
542                 }
543                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
544
545                 winbindd_flush_negative_conn_cache(domain);
546                 set_domain_online_request(domain);
547         }
548
549         for (child = children; child != NULL; child = child->next) {
550                 /* Don't send message to idmap child. */
551                 if (!child->domain || (child == idmap_child())) {
552                         continue;
553                 }
554
555                 /* Or internal domains (this should not be possible....) */
556                 if (child->domain->internal) {
557                         continue;
558                 }
559
560                 /* Each winbindd child should only process requests for one domain - make sure
561                    we only set it online / offline for that domain. */
562
563                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
564                         (unsigned int)child->pid, domain->name ));
565
566                 message_send_pid(pid_to_procid(child->pid), MSG_WINBIND_ONLINE, domain->name,
567                         strlen(domain->name)+1, False);
568         }
569 }
570
571 /* Forward the online/offline messages to our children. */
572 void winbind_msg_onlinestatus(int msg_type, struct process_id src, void *buf, size_t len)
573 {
574         struct winbindd_child *child;
575
576         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
577
578         for (child = children; child != NULL; child = child->next) {
579                 if (child->domain && child->domain->primary) {
580                         DEBUG(10,("winbind_msg_onlinestatus: "
581                                   "sending message to pid %u of primary domain.\n",
582                                   (unsigned int)child->pid));
583                         message_send_pid(pid_to_procid(child->pid), 
584                                          MSG_WINBIND_ONLINESTATUS, buf, len, False);
585                         break;
586                 }
587         }
588 }
589
590
591 static void account_lockout_policy_handler(struct timed_event *te,
592                                            const struct timeval *now,
593                                            void *private_data)
594 {
595         struct winbindd_child *child =
596                 (struct winbindd_child *)private_data;
597
598         struct winbindd_methods *methods;
599         SAM_UNK_INFO_12 lockout_policy;
600         NTSTATUS result;
601
602         DEBUG(10,("account_lockout_policy_handler called\n"));
603
604         if (child->lockout_policy_event) {
605                 TALLOC_FREE(child->lockout_policy_event);
606         }
607
608         methods = child->domain->methods;
609
610         result = methods->lockout_policy(child->domain, child->mem_ctx, &lockout_policy);
611         if (!NT_STATUS_IS_OK(result)) {
612                 DEBUG(10,("account_lockout_policy_handler: failed to call lockout_policy\n"));
613                 return;
614         }
615
616         child->lockout_policy_event = add_timed_event(child->mem_ctx, 
617                                                       timeval_current_ofs(3600, 0),
618                                                       "account_lockout_policy_handler",
619                                                       account_lockout_policy_handler,
620                                                       child);
621 }
622
623 /* Deal with a request to go offline. */
624
625 static void child_msg_offline(int msg_type, struct process_id src, void *buf, size_t len)
626 {
627         struct winbindd_domain *domain;
628         const char *domainname = (const char *)buf;
629
630         if (buf == NULL || len == 0) {
631                 return;
632         }
633
634         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
635
636         if (!lp_winbind_offline_logon()) {
637                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
638                 return;
639         }
640
641         /* Set our global state as offline. */
642         if (!set_global_winbindd_state_offline()) {
643                 DEBUG(10,("child_msg_offline: offline request failed.\n"));
644                 return;
645         }
646
647         /* Mark the requested domain offline. */
648
649         for (domain = domain_list(); domain; domain = domain->next) {
650                 if (domain->internal) {
651                         continue;
652                 }
653                 if (strequal(domain->name, domainname)) {
654                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
655                         set_domain_offline(domain);
656                 }
657         }
658 }
659
660 /* Deal with a request to go online. */
661
662 static void child_msg_online(int msg_type, struct process_id src, void *buf, size_t len)
663 {
664         struct winbindd_domain *domain;
665         const char *domainname = (const char *)buf;
666
667         if (buf == NULL || len == 0) {
668                 return;
669         }
670
671         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
672
673         if (!lp_winbind_offline_logon()) {
674                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
675                 return;
676         }
677
678         /* Set our global state as online. */
679         set_global_winbindd_state_online();
680
681         /* Try and mark everything online - delete any negative cache entries
682            to force a reconnect now. */
683
684         for (domain = domain_list(); domain; domain = domain->next) {
685                 if (domain->internal) {
686                         continue;
687                 }
688                 if (strequal(domain->name, domainname)) {
689                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
690                         winbindd_flush_negative_conn_cache(domain);
691                         set_domain_online_request(domain);
692                 }
693         }
694 }
695
696 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
697 {
698         struct winbindd_domain *domain;
699         char *buf = NULL;
700
701         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
702                                    get_global_winbindd_state_offline() ? 
703                                    "Offline":"Online")) == NULL) {
704                 return NULL;
705         }
706
707         for (domain = domain_list(); domain; domain = domain->next) {
708                 if ((buf = talloc_asprintf_append(buf, "%s:%s ", 
709                                                   domain->name, 
710                                                   domain->online ?
711                                                   "Online":"Offline")) == NULL) {
712                         return NULL;
713                 }
714         }
715
716         buf = talloc_asprintf_append(buf, "\n");
717
718         DEBUG(5,("collect_onlinestatus: %s", buf));
719
720         return buf;
721 }
722
723 static void child_msg_onlinestatus(int msg_type, struct process_id src, void *buf, size_t len)
724 {
725         TALLOC_CTX *mem_ctx;
726         const char *message;
727         struct process_id *sender;
728         
729         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
730
731         if (!buf) {
732                 return;
733         }
734
735         sender = (struct process_id *)buf;
736
737         mem_ctx = talloc_init("winbind_msg_onlinestatus");
738         if (mem_ctx == NULL) {
739                 return;
740         }
741         
742         message = collect_onlinestatus(mem_ctx);
743         if (message == NULL) {
744                 talloc_destroy(mem_ctx);
745                 return;
746         }
747
748         message_send_pid(*sender, MSG_WINBIND_ONLINESTATUS, 
749                          message, strlen(message) + 1, True);
750
751         talloc_destroy(mem_ctx);
752 }
753
754 static BOOL fork_domain_child(struct winbindd_child *child)
755 {
756         int fdpair[2];
757         struct winbindd_cli_state state;
758         extern BOOL override_logfile;
759
760         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
761                 DEBUG(0, ("Could not open child pipe: %s\n",
762                           strerror(errno)));
763                 return False;
764         }
765
766         ZERO_STRUCT(state);
767         state.pid = getpid();
768
769         /* Ensure we don't process messages whilst we're
770            changing the disposition for the child. */
771         message_block();
772
773         child->pid = sys_fork();
774
775         if (child->pid == -1) {
776                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
777                 message_unblock();
778                 return False;
779         }
780
781         if (child->pid != 0) {
782                 /* Parent */
783                 close(fdpair[0]);
784                 child->next = child->prev = NULL;
785                 DLIST_ADD(children, child);
786                 child->event.fd = fdpair[1];
787                 child->event.flags = 0;
788                 child->requests = NULL;
789                 add_fd_event(&child->event);
790                 /* We're ok with online/offline messages now. */
791                 message_unblock();
792                 return True;
793         }
794
795         /* Child */
796
797         state.sock = fdpair[0];
798         close(fdpair[1]);
799
800         /* tdb needs special fork handling */
801         if (tdb_reopen_all(1) == -1) {
802                 DEBUG(0,("tdb_reopen_all failed.\n"));
803                 _exit(0);
804         }
805
806         close_conns_after_fork();
807
808         if (!override_logfile) {
809                 lp_set_logfile(child->logfilename);
810                 reopen_logs();
811         }
812
813         /* Don't handle the same messages as our parent. */
814         message_deregister(MSG_SMB_CONF_UPDATED);
815         message_deregister(MSG_SHUTDOWN);
816         message_deregister(MSG_WINBIND_OFFLINE);
817         message_deregister(MSG_WINBIND_ONLINE);
818         message_deregister(MSG_WINBIND_ONLINESTATUS);
819
820         /* The child is ok with online/offline messages now. */
821         message_unblock();
822
823         child->mem_ctx = talloc_init("child_mem_ctx");
824         if (child->mem_ctx == NULL) {
825                 return False;
826         }
827
828         if (child->domain != NULL && lp_winbind_offline_logon()) {
829                 /* We might be in the idmap child...*/
830                 child->lockout_policy_event = add_timed_event(
831                         child->mem_ctx, timeval_zero(),
832                         "account_lockout_policy_handler",
833                         account_lockout_policy_handler,
834                         child);
835         }
836
837         /* Handle online/offline messages. */
838         message_register(MSG_WINBIND_OFFLINE,child_msg_offline);
839         message_register(MSG_WINBIND_ONLINE,child_msg_online);
840         message_register(MSG_WINBIND_ONLINESTATUS,child_msg_onlinestatus);
841
842         if ( child->domain ) {
843                 child->domain->startup = True;
844                 child->domain->startup_time = time(NULL);
845         }
846
847         while (1) {
848
849                 int ret;
850                 fd_set read_fds;
851                 struct timeval t;
852                 struct timeval *tp;
853                 struct timeval now;
854
855                 /* free up any talloc memory */
856                 lp_TALLOC_FREE();
857                 main_loop_TALLOC_FREE();
858
859                 run_events();
860
861                 GetTimeOfDay(&now);
862
863                 if (child->domain && child->domain->startup &&
864                                 (now.tv_sec > child->domain->startup_time + 30)) {
865                         /* No longer in "startup" mode. */
866                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
867                                 child->domain->name ));
868                         child->domain->startup = False;
869                 }
870
871                 tp = get_timed_events_timeout(&t);
872                 if (tp) {
873                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
874                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
875                 }
876
877                 /* Handle messages */
878
879                 message_dispatch();
880
881                 FD_ZERO(&read_fds);
882                 FD_SET(state.sock, &read_fds);
883
884                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
885
886                 if (ret == 0) {
887                         DEBUG(11,("nothing is ready yet, continue\n"));
888                         continue;
889                 }
890
891                 if (ret == -1 && errno == EINTR) {
892                         /* We got a signal - continue. */
893                         continue;
894                 }
895
896                 if (ret == -1 && errno != EINTR) {
897                         DEBUG(0,("select error occured\n"));
898                         perror("select");
899                         return False;
900                 }
901
902                 /* fetch a request from the main daemon */
903                 child_read_request(&state);
904
905                 if (state.finished) {
906                         /* we lost contact with our parent */
907                         exit(0);
908                 }
909
910                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
911
912                 ZERO_STRUCT(state.response);
913                 state.request.null_term = '\0';
914                 child_process_request(child->domain, &state);
915
916                 SAFE_FREE(state.request.extra_data.data);
917
918                 cache_store_response(sys_getpid(), &state.response);
919
920                 SAFE_FREE(state.response.extra_data.data);
921
922                 /* We just send the result code back, the result
923                  * structure needs to be fetched via the
924                  * winbindd_cache. Hmm. That needs fixing... */
925
926                 if (write_data(state.sock,
927                                (const char *)&state.response.result,
928                                sizeof(state.response.result)) !=
929                     sizeof(state.response.result)) {
930                         DEBUG(0, ("Could not write result\n"));
931                         exit(1);
932                 }
933         }
934 }