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