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