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