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