778886d8e28b87767f2d0eb63082563bc324f912
[metze/samba/wip.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         SAFE_FREE(child->logfilename);
484
485         schedule_async_request(child);
486 }
487
488 /* Ensure any negative cache entries with the netbios or realm names are removed. */
489
490 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
491 {
492         flush_negative_conn_cache_for_domain(domain->name);
493         if (*domain->alt_name) {
494                 flush_negative_conn_cache_for_domain(domain->alt_name);
495         }
496 }
497
498 /* Set our domains as offline and forward the offline message to our children. */
499
500 void winbind_msg_offline(struct messaging_context *msg_ctx,
501                          void *private_data,
502                          uint32_t msg_type,
503                          struct server_id server_id,
504                          DATA_BLOB *data)
505 {
506         struct winbindd_child *child;
507         struct winbindd_domain *domain;
508
509         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
510
511         if (!lp_winbind_offline_logon()) {
512                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
513                 return;
514         }
515
516         /* Set our global state as offline. */
517         if (!set_global_winbindd_state_offline()) {
518                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
519                 return;
520         }
521
522         /* Set all our domains as offline. */
523         for (domain = domain_list(); domain; domain = domain->next) {
524                 if (domain->internal) {
525                         continue;
526                 }
527                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
528                 set_domain_offline(domain);
529         }
530
531         for (child = children; child != NULL; child = child->next) {
532                 /* Don't send message to internal childs.  We've already
533                    done so above. */
534                 if (!child->domain || winbindd_internal_child(child)) {
535                         continue;
536                 }
537
538                 /* Or internal domains (this should not be possible....) */
539                 if (child->domain->internal) {
540                         continue;
541                 }
542
543                 /* Each winbindd child should only process requests for one domain - make sure
544                    we only set it online / offline for that domain. */
545
546                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
547                         (unsigned int)child->pid, domain->name ));
548
549                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
550                                    MSG_WINBIND_OFFLINE,
551                                    (uint8 *)child->domain->name,
552                                    strlen(child->domain->name)+1);
553         }
554 }
555
556 /* Set our domains as online and forward the online message to our children. */
557
558 void winbind_msg_online(struct messaging_context *msg_ctx,
559                         void *private_data,
560                         uint32_t msg_type,
561                         struct server_id server_id,
562                         DATA_BLOB *data)
563 {
564         struct winbindd_child *child;
565         struct winbindd_domain *domain;
566
567         DEBUG(10,("winbind_msg_online: got online message.\n"));
568
569         if (!lp_winbind_offline_logon()) {
570                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
571                 return;
572         }
573
574         /* Set our global state as online. */
575         set_global_winbindd_state_online();
576
577         smb_nscd_flush_user_cache();
578         smb_nscd_flush_group_cache();
579
580         /* Set all our domains as online. */
581         for (domain = domain_list(); domain; domain = domain->next) {
582                 if (domain->internal) {
583                         continue;
584                 }
585                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
586
587                 winbindd_flush_negative_conn_cache(domain);
588                 set_domain_online_request(domain);
589
590                 /* Send an online message to the idmap child when our
591                    primary domain comes back online */
592
593                 if ( domain->primary ) {
594                         struct winbindd_child *idmap = idmap_child();
595                         
596                         if ( idmap->pid != 0 ) {
597                                 messaging_send_buf(msg_ctx,
598                                                    pid_to_procid(idmap->pid), 
599                                                    MSG_WINBIND_ONLINE,
600                                                    (uint8 *)domain->name,
601                                                    strlen(domain->name)+1);
602                         }
603                         
604                 }
605         }
606
607         for (child = children; child != NULL; child = child->next) {
608                 /* Don't send message to internal childs. */
609                 if (!child->domain || winbindd_internal_child(child)) {
610                         continue;
611                 }
612
613                 /* Or internal domains (this should not be possible....) */
614                 if (child->domain->internal) {
615                         continue;
616                 }
617
618                 /* Each winbindd child should only process requests for one domain - make sure
619                    we only set it online / offline for that domain. */
620
621                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
622                         (unsigned int)child->pid, child->domain->name ));
623
624                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
625                                    MSG_WINBIND_ONLINE,
626                                    (uint8 *)child->domain->name,
627                                    strlen(child->domain->name)+1);
628         }
629 }
630
631 /* Forward the online/offline messages to our children. */
632 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
633                               void *private_data,
634                               uint32_t msg_type,
635                               struct server_id server_id,
636                               DATA_BLOB *data)
637 {
638         struct winbindd_child *child;
639
640         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
641
642         for (child = children; child != NULL; child = child->next) {
643                 if (child->domain && child->domain->primary) {
644                         DEBUG(10,("winbind_msg_onlinestatus: "
645                                   "sending message to pid %u of primary domain.\n",
646                                   (unsigned int)child->pid));
647                         messaging_send_buf(msg_ctx, pid_to_procid(child->pid), 
648                                            MSG_WINBIND_ONLINESTATUS,
649                                            (uint8 *)data->data,
650                                            data->length);
651                         break;
652                 }
653         }
654 }
655
656 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
657                                  void *private_data,
658                                  uint32_t msg_type,
659                                  struct server_id server_id,
660                                  DATA_BLOB *data)
661 {
662         struct winbindd_child *child;
663
664         DEBUG(10,("winbind_msg_dump_event_list received\n"));
665
666         dump_event_list(winbind_event_context());
667
668         for (child = children; child != NULL; child = child->next) {
669
670                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
671                         (unsigned int)child->pid));
672
673                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
674                                    MSG_DUMP_EVENT_LIST,
675                                    NULL, 0);
676         }
677
678 }
679
680 static void account_lockout_policy_handler(struct event_context *ctx,
681                                            struct timed_event *te,
682                                            const struct timeval *now,
683                                            void *private_data)
684 {
685         struct winbindd_child *child =
686                 (struct winbindd_child *)private_data;
687         TALLOC_CTX *mem_ctx = NULL;
688         struct winbindd_methods *methods;
689         SAM_UNK_INFO_12 lockout_policy;
690         NTSTATUS result;
691
692         DEBUG(10,("account_lockout_policy_handler called\n"));
693
694         TALLOC_FREE(child->lockout_policy_event);
695
696         if ( !winbindd_can_contact_domain( child->domain ) ) {
697                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
698                           "do not have an incoming trust to domain %s\n", 
699                           child->domain->name));
700
701                 return;         
702         }
703
704         methods = child->domain->methods;
705
706         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
707         if (!mem_ctx) {
708                 result = NT_STATUS_NO_MEMORY;
709         } else {
710                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
711         }
712         TALLOC_FREE(mem_ctx);
713
714         if (!NT_STATUS_IS_OK(result)) {
715                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
716                          nt_errstr(result)));
717         }
718
719         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
720                                                       timeval_current_ofs(3600, 0),
721                                                       "account_lockout_policy_handler",
722                                                       account_lockout_policy_handler,
723                                                       child);
724 }
725
726 /* Deal with a request to go offline. */
727
728 static void child_msg_offline(struct messaging_context *msg,
729                               void *private_data,
730                               uint32_t msg_type,
731                               struct server_id server_id,
732                               DATA_BLOB *data)
733 {
734         struct winbindd_domain *domain;
735         const char *domainname = (const char *)data->data;
736
737         if (data->data == NULL || data->length == 0) {
738                 return;
739         }
740
741         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
742
743         if (!lp_winbind_offline_logon()) {
744                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
745                 return;
746         }
747
748         /* Mark the requested domain offline. */
749
750         for (domain = domain_list(); domain; domain = domain->next) {
751                 if (domain->internal) {
752                         continue;
753                 }
754                 if (strequal(domain->name, domainname)) {
755                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
756                         set_domain_offline(domain);
757                 }
758         }
759 }
760
761 /* Deal with a request to go online. */
762
763 static void child_msg_online(struct messaging_context *msg,
764                              void *private_data,
765                              uint32_t msg_type,
766                              struct server_id server_id,
767                              DATA_BLOB *data)
768 {
769         struct winbindd_domain *domain;
770         const char *domainname = (const char *)data->data;
771
772         if (data->data == NULL || data->length == 0) {
773                 return;
774         }
775
776         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
777
778         if (!lp_winbind_offline_logon()) {
779                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
780                 return;
781         }
782
783         /* Set our global state as online. */
784         set_global_winbindd_state_online();
785
786         /* Try and mark everything online - delete any negative cache entries
787            to force a reconnect now. */
788
789         for (domain = domain_list(); domain; domain = domain->next) {
790                 if (domain->internal) {
791                         continue;
792                 }
793                 if (strequal(domain->name, domainname)) {
794                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
795                         winbindd_flush_negative_conn_cache(domain);
796                         set_domain_online_request(domain);
797                 }
798         }
799 }
800
801 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
802 {
803         struct winbindd_domain *domain;
804         char *buf = NULL;
805
806         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
807                                    get_global_winbindd_state_offline() ? 
808                                    "Offline":"Online")) == NULL) {
809                 return NULL;
810         }
811
812         for (domain = domain_list(); domain; domain = domain->next) {
813                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
814                                                   domain->name, 
815                                                   domain->online ?
816                                                   "Online":"Offline")) == NULL) {
817                         return NULL;
818                 }
819         }
820
821         buf = talloc_asprintf_append_buffer(buf, "\n");
822
823         DEBUG(5,("collect_onlinestatus: %s", buf));
824
825         return buf;
826 }
827
828 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
829                                    void *private_data,
830                                    uint32_t msg_type,
831                                    struct server_id server_id,
832                                    DATA_BLOB *data)
833 {
834         TALLOC_CTX *mem_ctx;
835         const char *message;
836         struct server_id *sender;
837         
838         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
839
840         if (!data->data) {
841                 return;
842         }
843
844         sender = (struct server_id *)data->data;
845
846         mem_ctx = talloc_init("winbind_msg_onlinestatus");
847         if (mem_ctx == NULL) {
848                 return;
849         }
850         
851         message = collect_onlinestatus(mem_ctx);
852         if (message == NULL) {
853                 talloc_destroy(mem_ctx);
854                 return;
855         }
856
857         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
858                            (uint8 *)message, strlen(message) + 1);
859
860         talloc_destroy(mem_ctx);
861 }
862
863 static void child_msg_dump_event_list(struct messaging_context *msg,
864                                       void *private_data,
865                                       uint32_t msg_type,
866                                       struct server_id server_id,
867                                       DATA_BLOB *data)
868 {
869         DEBUG(5,("child_msg_dump_event_list received\n"));
870
871         dump_event_list(winbind_event_context());
872 }
873
874
875 static bool fork_domain_child(struct winbindd_child *child)
876 {
877         int fdpair[2];
878         struct winbindd_cli_state state;
879         struct winbindd_domain *domain;
880
881         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
882                 DEBUG(0, ("Could not open child pipe: %s\n",
883                           strerror(errno)));
884                 return False;
885         }
886
887         ZERO_STRUCT(state);
888         state.pid = sys_getpid();
889
890         /* Stop zombies */
891         CatchChild();
892
893         child->pid = sys_fork();
894
895         if (child->pid == -1) {
896                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
897                 return False;
898         }
899
900         if (child->pid != 0) {
901                 /* Parent */
902                 close(fdpair[0]);
903                 child->next = child->prev = NULL;
904                 DLIST_ADD(children, child);
905                 child->event.fd = fdpair[1];
906                 child->event.flags = 0;
907                 child->requests = NULL;
908                 add_fd_event(&child->event);
909                 return True;
910         }
911
912         /* Child */
913
914         state.sock = fdpair[0];
915         close(fdpair[1]);
916
917         /* tdb needs special fork handling */
918         if (tdb_reopen_all(1) == -1) {
919                 DEBUG(0,("tdb_reopen_all failed.\n"));
920                 _exit(0);
921         }
922
923         close_conns_after_fork();
924
925         if (!override_logfile) {
926                 lp_set_logfile(child->logfilename);
927                 reopen_logs();
928         }
929
930         /*
931          * For clustering, we need to re-init our ctdbd connection after the
932          * fork
933          */
934         if (!NT_STATUS_IS_OK(messaging_reinit(winbind_messaging_context())))
935                 exit(1);
936
937         /* Don't handle the same messages as our parent. */
938         messaging_deregister(winbind_messaging_context(),
939                              MSG_SMB_CONF_UPDATED, NULL);
940         messaging_deregister(winbind_messaging_context(),
941                              MSG_SHUTDOWN, NULL);
942         messaging_deregister(winbind_messaging_context(),
943                              MSG_WINBIND_OFFLINE, NULL);
944         messaging_deregister(winbind_messaging_context(),
945                              MSG_WINBIND_ONLINE, NULL);
946         messaging_deregister(winbind_messaging_context(),
947                              MSG_WINBIND_ONLINESTATUS, NULL);
948         messaging_deregister(winbind_messaging_context(),
949                              MSG_DUMP_EVENT_LIST, NULL);
950
951         /* Handle online/offline messages. */
952         messaging_register(winbind_messaging_context(), NULL,
953                            MSG_WINBIND_OFFLINE, child_msg_offline);
954         messaging_register(winbind_messaging_context(), NULL,
955                            MSG_WINBIND_ONLINE, child_msg_online);
956         messaging_register(winbind_messaging_context(), NULL,
957                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
958         messaging_register(winbind_messaging_context(), NULL,
959                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
960
961         if ( child->domain ) {
962                 child->domain->startup = True;
963                 child->domain->startup_time = time(NULL);
964         }
965
966         /* Ensure we have no pending check_online events other
967            than one for this domain. */
968
969         for (domain = domain_list(); domain; domain = domain->next) {
970                 if (domain != child->domain) {
971                         TALLOC_FREE(domain->check_online_event);
972                 }
973         }
974
975         /* Ensure we're not handling an event inherited from
976            our parent. */
977
978         cancel_named_event(winbind_event_context(),
979                            "krb5_ticket_refresh_handler");
980
981         /* We might be in the idmap child...*/
982         if (child->domain && !(child->domain->internal) &&
983             lp_winbind_offline_logon()) {
984
985                 set_domain_online_request(child->domain);
986
987                 child->lockout_policy_event = event_add_timed(
988                         winbind_event_context(), NULL, timeval_zero(),
989                         "account_lockout_policy_handler",
990                         account_lockout_policy_handler,
991                         child);
992         }
993
994         while (1) {
995
996                 int ret;
997                 fd_set read_fds;
998                 struct timeval t;
999                 struct timeval *tp;
1000                 struct timeval now;
1001                 TALLOC_CTX *frame = talloc_stackframe();
1002
1003                 run_events(winbind_event_context(), 0, NULL, NULL);
1004
1005                 GetTimeOfDay(&now);
1006
1007                 if (child->domain && child->domain->startup &&
1008                                 (now.tv_sec > child->domain->startup_time + 30)) {
1009                         /* No longer in "startup" mode. */
1010                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1011                                 child->domain->name ));
1012                         child->domain->startup = False;
1013                 }
1014
1015                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1016                 if (tp) {
1017                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1018                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1019                 }
1020
1021                 /* Handle messages */
1022
1023                 message_dispatch(winbind_messaging_context());
1024
1025                 FD_ZERO(&read_fds);
1026                 FD_SET(state.sock, &read_fds);
1027
1028                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
1029
1030                 if (ret == 0) {
1031                         DEBUG(11,("nothing is ready yet, continue\n"));
1032                         TALLOC_FREE(frame);
1033                         continue;
1034                 }
1035
1036                 if (ret == -1 && errno == EINTR) {
1037                         /* We got a signal - continue. */
1038                         TALLOC_FREE(frame);
1039                         continue;
1040                 }
1041
1042                 if (ret == -1 && errno != EINTR) {
1043                         DEBUG(0,("select error occured\n"));
1044                         TALLOC_FREE(frame);
1045                         perror("select");
1046                         return False;
1047                 }
1048
1049                 /* fetch a request from the main daemon */
1050                 child_read_request(&state);
1051
1052                 if (state.finished) {
1053                         /* we lost contact with our parent */
1054                         exit(0);
1055                 }
1056
1057                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1058
1059                 ZERO_STRUCT(state.response);
1060                 state.request.null_term = '\0';
1061                 child_process_request(child, &state);
1062
1063                 SAFE_FREE(state.request.extra_data.data);
1064
1065                 cache_store_response(sys_getpid(), &state.response);
1066
1067                 SAFE_FREE(state.response.extra_data.data);
1068
1069                 /* We just send the result code back, the result
1070                  * structure needs to be fetched via the
1071                  * winbindd_cache. Hmm. That needs fixing... */
1072
1073                 if (write_data(state.sock,
1074                                (const char *)&state.response.result,
1075                                sizeof(state.response.result)) !=
1076                     sizeof(state.response.result)) {
1077                         DEBUG(0, ("Could not write result\n"));
1078                         exit(1);
1079                 }
1080                 TALLOC_FREE(frame);
1081         }
1082 }