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