Merge branch 'v3-2-test' of ssh://git.samba.org/data/git/samba into v3-2-test
[ira/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 extern struct winbindd_methods cache_methods;
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), NULL);
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, NULL);
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
135         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
136
137         schedule_async_request(child);
138
139         return;
140 }
141
142 static void async_main_request_sent(void *private_data, bool success)
143 {
144         struct winbindd_async_request *state =
145                 talloc_get_type_abort(private_data, struct winbindd_async_request);
146
147         if (!success) {
148                 DEBUG(5, ("Could not send async request\n"));
149
150                 state->response->length = sizeof(struct winbindd_response);
151                 state->response->result = WINBINDD_ERROR;
152                 state->continuation(state->private_data, False);
153                 return;
154         }
155
156         if (state->request->extra_len == 0) {
157                 async_request_sent(private_data, True);
158                 return;
159         }
160
161         setup_async_write(&state->child->event, state->request->extra_data.data,
162                           state->request->extra_len,
163                           async_request_sent, state);
164 }
165
166 /****************************************************************
167  Handler triggered if the child winbindd doesn't respond within
168  a given timeout.
169 ****************************************************************/
170
171 static void async_request_timeout_handler(struct event_context *ctx,
172                                         struct timed_event *te,
173                                         const struct timeval *now,
174                                         void *private_data)
175 {
176         struct winbindd_async_request *state =
177                 talloc_get_type_abort(private_data, struct winbindd_async_request);
178
179         DEBUG(0,("async_request_timeout_handler: child pid %u is not responding. "
180                 "Closing connection to it.\n",
181                 state->child_pid ));
182
183         /* Deal with the reply - set to error. */
184         async_reply_recv(private_data, False);
185 }
186
187 /**************************************************************
188  Common function called on both async send and recv fail.
189  Cleans up the child and schedules the next request.
190 **************************************************************/
191
192 static void async_request_fail(struct winbindd_async_request *state)
193 {
194         DLIST_REMOVE(state->child->requests, state);
195
196         TALLOC_FREE(state->reply_timeout_event);
197
198         SMB_ASSERT(state->child_pid != (pid_t)0);
199
200         /* If not already reaped, send kill signal to child. */
201         if (state->child->pid == state->child_pid) {
202                 kill(state->child_pid, SIGTERM);
203
204                 /* 
205                  * Close the socket to the child.
206                  */
207                 winbind_child_died(state->child_pid);
208         }
209
210         state->response->length = sizeof(struct winbindd_response);
211         state->response->result = WINBINDD_ERROR;
212         state->continuation(state->private_data, False);
213 }
214
215 static void async_request_sent(void *private_data_data, bool success)
216 {
217         struct winbindd_async_request *state =
218                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
219
220         if (!success) {
221                 DEBUG(5, ("Could not send async request to child pid %u\n",
222                         (unsigned int)state->child_pid ));
223                 async_request_fail(state);
224                 return;
225         }
226
227         /* Request successfully sent to the child, setup the wait for reply */
228
229         setup_async_read(&state->child->event,
230                          &state->response->result,
231                          sizeof(state->response->result),
232                          async_reply_recv, state);
233
234         /* 
235          * Set up a timeout of 300 seconds for the response.
236          * If we don't get it close the child socket and
237          * report failure.
238          */
239
240         state->reply_timeout_event = event_add_timed(winbind_event_context(),
241                                                         NULL,
242                                                         timeval_current_ofs(300,0),
243                                                         "async_request_timeout",
244                                                         async_request_timeout_handler,
245                                                         state);
246         if (!state->reply_timeout_event) {
247                 smb_panic("async_request_sent: failed to add timeout handler.\n");
248         }
249 }
250
251 static void async_reply_recv(void *private_data, bool success)
252 {
253         struct winbindd_async_request *state =
254                 talloc_get_type_abort(private_data, struct winbindd_async_request);
255         struct winbindd_child *child = state->child;
256
257         TALLOC_FREE(state->reply_timeout_event);
258
259         state->response->length = sizeof(struct winbindd_response);
260
261         if (!success) {
262                 DEBUG(5, ("Could not receive async reply from child pid %u\n",
263                         (unsigned int)state->child_pid ));
264
265                 cache_cleanup_response(state->child_pid);
266                 async_request_fail(state);
267                 return;
268         }
269
270         SMB_ASSERT(cache_retrieve_response(state->child_pid,
271                                            state->response));
272
273         cache_cleanup_response(state->child_pid);
274         
275         DLIST_REMOVE(child->requests, state);
276
277         schedule_async_request(child);
278
279         state->continuation(state->private_data, True);
280 }
281
282 static bool fork_domain_child(struct winbindd_child *child);
283
284 static void schedule_async_request(struct winbindd_child *child)
285 {
286         struct winbindd_async_request *request = child->requests;
287
288         if (request == NULL) {
289                 return;
290         }
291
292         if (child->event.flags != 0) {
293                 return;         /* Busy */
294         }
295
296         if ((child->pid == 0) && (!fork_domain_child(child))) {
297                 /* Cancel all outstanding requests */
298
299                 while (request != NULL) {
300                         /* request might be free'd in the continuation */
301                         struct winbindd_async_request *next = request->next;
302                         request->continuation(request->private_data, False);
303                         request = next;
304                 }
305                 return;
306         }
307
308         /* Now we know who we're sending to - remember the pid. */
309         request->child_pid = child->pid;
310
311         setup_async_write(&child->event, request->request,
312                           sizeof(*request->request),
313                           async_main_request_sent, request);
314
315         return;
316 }
317
318 struct domain_request_state {
319         TALLOC_CTX *mem_ctx;
320         struct winbindd_domain *domain;
321         struct winbindd_request *request;
322         struct winbindd_response *response;
323         void (*continuation)(void *private_data_data, bool success);
324         void *private_data_data;
325 };
326
327 static void domain_init_recv(void *private_data_data, bool success);
328
329 void async_domain_request(TALLOC_CTX *mem_ctx,
330                           struct winbindd_domain *domain,
331                           struct winbindd_request *request,
332                           struct winbindd_response *response,
333                           void (*continuation)(void *private_data_data, bool success),
334                           void *private_data_data)
335 {
336         struct domain_request_state *state;
337
338         if (domain->initialized) {
339                 async_request(mem_ctx, &domain->child, request, response,
340                               continuation, private_data_data);
341                 return;
342         }
343
344         state = TALLOC_P(mem_ctx, struct domain_request_state);
345         if (state == NULL) {
346                 DEBUG(0, ("talloc failed\n"));
347                 continuation(private_data_data, False);
348                 return;
349         }
350
351         state->mem_ctx = mem_ctx;
352         state->domain = domain;
353         state->request = request;
354         state->response = response;
355         state->continuation = continuation;
356         state->private_data_data = private_data_data;
357
358         init_child_connection(domain, domain_init_recv, state);
359 }
360
361 static void domain_init_recv(void *private_data_data, bool success)
362 {
363         struct domain_request_state *state =
364                 talloc_get_type_abort(private_data_data, struct domain_request_state);
365
366         if (!success) {
367                 DEBUG(5, ("Domain init returned an error\n"));
368                 state->continuation(state->private_data_data, False);
369                 return;
370         }
371
372         async_request(state->mem_ctx, &state->domain->child,
373                       state->request, state->response,
374                       state->continuation, state->private_data_data);
375 }
376
377 static void recvfrom_child(void *private_data_data, bool success)
378 {
379         struct winbindd_cli_state *state =
380                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
381         enum winbindd_result result = state->response.result;
382
383         /* This is an optimization: The child has written directly to the
384          * response buffer. The request itself is still in pending state,
385          * state that in the result code. */
386
387         state->response.result = WINBINDD_PENDING;
388
389         if ((!success) || (result != WINBINDD_OK)) {
390                 request_error(state);
391                 return;
392         }
393
394         request_ok(state);
395 }
396
397 void sendto_child(struct winbindd_cli_state *state,
398                   struct winbindd_child *child)
399 {
400         async_request(state->mem_ctx, child, &state->request,
401                       &state->response, recvfrom_child, state);
402 }
403
404 void sendto_domain(struct winbindd_cli_state *state,
405                    struct winbindd_domain *domain)
406 {
407         async_domain_request(state->mem_ctx, domain,
408                              &state->request, &state->response,
409                              recvfrom_child, state);
410 }
411
412 static void child_process_request(struct winbindd_child *child,
413                                   struct winbindd_cli_state *state)
414 {
415         struct winbindd_domain *domain = child->domain;
416         const struct winbindd_child_dispatch_table *table = child->table;
417
418         /* Free response data - we may be interrupted and receive another
419            command before being able to send this data off. */
420
421         state->response.result = WINBINDD_ERROR;
422         state->response.length = sizeof(struct winbindd_response);
423
424         /* as all requests in the child are sync, we can use talloc_tos() */
425         state->mem_ctx = talloc_tos();
426
427         /* Process command */
428
429         for (; table->name; table++) {
430                 if (state->request.cmd == table->struct_cmd) {
431                         DEBUG(10,("child_process_request: request fn %s\n",
432                                   table->name));
433                         state->response.result = table->struct_fn(domain, state);
434                         return;
435                 }
436         }
437
438         DEBUG(1 ,("child_process_request: unknown request fn number %d\n",
439                   (int)state->request.cmd));
440         state->response.result = WINBINDD_ERROR;
441 }
442
443 void setup_child(struct winbindd_child *child,
444                  const struct winbindd_child_dispatch_table *table,
445                  const char *logprefix,
446                  const char *logname)
447 {
448         if (logprefix && logname) {
449                 if (asprintf(&child->logfilename, "%s/%s-%s",
450                              get_dyn_LOGFILEBASE(), logprefix, logname) < 0) {
451                         smb_panic("Internal error: asprintf failed");
452                 }
453         } else {
454                 smb_panic("Internal error: logprefix == NULL && "
455                           "logname == NULL");
456         }
457
458         child->domain = NULL;
459         child->table = table;
460 }
461
462 struct winbindd_child *children = NULL;
463
464 void winbind_child_died(pid_t pid)
465 {
466         struct winbindd_child *child;
467
468         for (child = children; child != NULL; child = child->next) {
469                 if (child->pid == pid) {
470                         break;
471                 }
472         }
473
474         if (child == NULL) {
475                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
476                 return;
477         }
478
479         remove_fd_event(&child->event);
480         close(child->event.fd);
481         child->event.fd = 0;
482         child->event.flags = 0;
483         child->pid = 0;
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 void winbind_msg_dump_domain_list(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         TALLOC_CTX *mem_ctx;
687         const char *message = NULL;
688         struct server_id *sender = NULL;
689         const char *domain = NULL;
690         char *s = NULL;
691         NTSTATUS status;
692         struct winbindd_domain *dom = NULL;
693
694         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
695
696         if (!data || !data->data) {
697                 return;
698         }
699
700         if (data->length < sizeof(struct server_id)) {
701                 return;
702         }
703
704         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
705         if (!mem_ctx) {
706                 return;
707         }
708
709         sender = (struct server_id *)data->data;
710         if (data->length > sizeof(struct server_id)) {
711                 domain = (const char *)data->data+sizeof(struct server_id);
712         }
713
714         if (domain) {
715
716                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
717                         domain));
718
719                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
720                                                   find_domain_from_name_noinit(domain));
721                 if (!message) {
722                         talloc_destroy(mem_ctx);
723                         return;
724                 }
725
726                 messaging_send_buf(msg_ctx, *sender,
727                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
728                                    (uint8_t *)message, strlen(message) + 1);
729
730                 talloc_destroy(mem_ctx);
731
732                 return;
733         }
734
735         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
736
737         for (dom = domain_list(); dom; dom=dom->next) {
738                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
739                 if (!message) {
740                         talloc_destroy(mem_ctx);
741                         return;
742                 }
743
744                 s = talloc_asprintf_append(s, "%s\n", message);
745                 if (!s) {
746                         talloc_destroy(mem_ctx);
747                         return;
748                 }
749         }
750
751         status = messaging_send_buf(msg_ctx, *sender,
752                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
753                                     (uint8_t *)s, strlen(s) + 1);
754         if (!NT_STATUS_IS_OK(status)) {
755                 DEBUG(0,("failed to send message: %s\n",
756                 nt_errstr(status)));
757         }
758
759         talloc_destroy(mem_ctx);
760 }
761
762 static void account_lockout_policy_handler(struct event_context *ctx,
763                                            struct timed_event *te,
764                                            const struct timeval *now,
765                                            void *private_data)
766 {
767         struct winbindd_child *child =
768                 (struct winbindd_child *)private_data;
769         TALLOC_CTX *mem_ctx = NULL;
770         struct winbindd_methods *methods;
771         SAM_UNK_INFO_12 lockout_policy;
772         NTSTATUS result;
773
774         DEBUG(10,("account_lockout_policy_handler called\n"));
775
776         TALLOC_FREE(child->lockout_policy_event);
777
778         if ( !winbindd_can_contact_domain( child->domain ) ) {
779                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
780                           "do not have an incoming trust to domain %s\n", 
781                           child->domain->name));
782
783                 return;         
784         }
785
786         methods = child->domain->methods;
787
788         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
789         if (!mem_ctx) {
790                 result = NT_STATUS_NO_MEMORY;
791         } else {
792                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
793         }
794         TALLOC_FREE(mem_ctx);
795
796         if (!NT_STATUS_IS_OK(result)) {
797                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
798                          nt_errstr(result)));
799         }
800
801         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
802                                                       timeval_current_ofs(3600, 0),
803                                                       "account_lockout_policy_handler",
804                                                       account_lockout_policy_handler,
805                                                       child);
806 }
807
808 /* Deal with a request to go offline. */
809
810 static void child_msg_offline(struct messaging_context *msg,
811                               void *private_data,
812                               uint32_t msg_type,
813                               struct server_id server_id,
814                               DATA_BLOB *data)
815 {
816         struct winbindd_domain *domain;
817         const char *domainname = (const char *)data->data;
818
819         if (data->data == NULL || data->length == 0) {
820                 return;
821         }
822
823         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
824
825         if (!lp_winbind_offline_logon()) {
826                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
827                 return;
828         }
829
830         /* Mark the requested domain offline. */
831
832         for (domain = domain_list(); domain; domain = domain->next) {
833                 if (domain->internal) {
834                         continue;
835                 }
836                 if (strequal(domain->name, domainname)) {
837                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
838                         set_domain_offline(domain);
839                 }
840         }
841 }
842
843 /* Deal with a request to go online. */
844
845 static void child_msg_online(struct messaging_context *msg,
846                              void *private_data,
847                              uint32_t msg_type,
848                              struct server_id server_id,
849                              DATA_BLOB *data)
850 {
851         struct winbindd_domain *domain;
852         const char *domainname = (const char *)data->data;
853
854         if (data->data == NULL || data->length == 0) {
855                 return;
856         }
857
858         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
859
860         if (!lp_winbind_offline_logon()) {
861                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
862                 return;
863         }
864
865         /* Set our global state as online. */
866         set_global_winbindd_state_online();
867
868         /* Try and mark everything online - delete any negative cache entries
869            to force a reconnect now. */
870
871         for (domain = domain_list(); domain; domain = domain->next) {
872                 if (domain->internal) {
873                         continue;
874                 }
875                 if (strequal(domain->name, domainname)) {
876                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
877                         winbindd_flush_negative_conn_cache(domain);
878                         set_domain_online_request(domain);
879                 }
880         }
881 }
882
883 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
884 {
885         struct winbindd_domain *domain;
886         char *buf = NULL;
887
888         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
889                                    get_global_winbindd_state_offline() ? 
890                                    "Offline":"Online")) == NULL) {
891                 return NULL;
892         }
893
894         for (domain = domain_list(); domain; domain = domain->next) {
895                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
896                                                   domain->name, 
897                                                   domain->online ?
898                                                   "Online":"Offline")) == NULL) {
899                         return NULL;
900                 }
901         }
902
903         buf = talloc_asprintf_append_buffer(buf, "\n");
904
905         DEBUG(5,("collect_onlinestatus: %s", buf));
906
907         return buf;
908 }
909
910 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
911                                    void *private_data,
912                                    uint32_t msg_type,
913                                    struct server_id server_id,
914                                    DATA_BLOB *data)
915 {
916         TALLOC_CTX *mem_ctx;
917         const char *message;
918         struct server_id *sender;
919         
920         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
921
922         if (!data->data) {
923                 return;
924         }
925
926         sender = (struct server_id *)data->data;
927
928         mem_ctx = talloc_init("winbind_msg_onlinestatus");
929         if (mem_ctx == NULL) {
930                 return;
931         }
932         
933         message = collect_onlinestatus(mem_ctx);
934         if (message == NULL) {
935                 talloc_destroy(mem_ctx);
936                 return;
937         }
938
939         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
940                            (uint8 *)message, strlen(message) + 1);
941
942         talloc_destroy(mem_ctx);
943 }
944
945 static void child_msg_dump_event_list(struct messaging_context *msg,
946                                       void *private_data,
947                                       uint32_t msg_type,
948                                       struct server_id server_id,
949                                       DATA_BLOB *data)
950 {
951         DEBUG(5,("child_msg_dump_event_list received\n"));
952
953         dump_event_list(winbind_event_context());
954 }
955
956
957 static bool fork_domain_child(struct winbindd_child *child)
958 {
959         int fdpair[2];
960         struct winbindd_cli_state state;
961         struct winbindd_domain *domain;
962
963         if (child->domain) {
964                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
965                            child->domain->name));
966         } else {
967                 DEBUG(10, ("fork_domain_child called without domain.\n"));
968         }
969
970         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
971                 DEBUG(0, ("Could not open child pipe: %s\n",
972                           strerror(errno)));
973                 return False;
974         }
975
976         ZERO_STRUCT(state);
977         state.pid = sys_getpid();
978
979         /* Stop zombies */
980         CatchChild();
981
982         child->pid = sys_fork();
983
984         if (child->pid == -1) {
985                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
986                 return False;
987         }
988
989         if (child->pid != 0) {
990                 /* Parent */
991                 close(fdpair[0]);
992                 child->next = child->prev = NULL;
993                 DLIST_ADD(children, child);
994                 child->event.fd = fdpair[1];
995                 child->event.flags = 0;
996                 child->requests = NULL;
997                 add_fd_event(&child->event);
998                 return True;
999         }
1000
1001         /* Child */
1002
1003         state.sock = fdpair[0];
1004         close(fdpair[1]);
1005
1006         /* tdb needs special fork handling */
1007         if (tdb_reopen_all(1) == -1) {
1008                 DEBUG(0,("tdb_reopen_all failed.\n"));
1009                 _exit(0);
1010         }
1011
1012         close_conns_after_fork();
1013
1014         if (!override_logfile) {
1015                 lp_set_logfile(child->logfilename);
1016                 reopen_logs();
1017         }
1018
1019         /*
1020          * For clustering, we need to re-init our ctdbd connection after the
1021          * fork
1022          */
1023         if (!NT_STATUS_IS_OK(messaging_reinit(winbind_messaging_context())))
1024                 exit(1);
1025
1026         /* Don't handle the same messages as our parent. */
1027         messaging_deregister(winbind_messaging_context(),
1028                              MSG_SMB_CONF_UPDATED, NULL);
1029         messaging_deregister(winbind_messaging_context(),
1030                              MSG_SHUTDOWN, NULL);
1031         messaging_deregister(winbind_messaging_context(),
1032                              MSG_WINBIND_OFFLINE, NULL);
1033         messaging_deregister(winbind_messaging_context(),
1034                              MSG_WINBIND_ONLINE, NULL);
1035         messaging_deregister(winbind_messaging_context(),
1036                              MSG_WINBIND_ONLINESTATUS, NULL);
1037         messaging_deregister(winbind_messaging_context(),
1038                              MSG_DUMP_EVENT_LIST, NULL);
1039         messaging_deregister(winbind_messaging_context(),
1040                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1041
1042         /* Handle online/offline messages. */
1043         messaging_register(winbind_messaging_context(), NULL,
1044                            MSG_WINBIND_OFFLINE, child_msg_offline);
1045         messaging_register(winbind_messaging_context(), NULL,
1046                            MSG_WINBIND_ONLINE, child_msg_online);
1047         messaging_register(winbind_messaging_context(), NULL,
1048                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
1049         messaging_register(winbind_messaging_context(), NULL,
1050                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1051
1052         if ( child->domain ) {
1053                 child->domain->startup = True;
1054                 child->domain->startup_time = time(NULL);
1055         }
1056
1057         /* Ensure we have no pending check_online events other
1058            than one for this domain. */
1059
1060         for (domain = domain_list(); domain; domain = domain->next) {
1061                 if (domain != child->domain) {
1062                         TALLOC_FREE(domain->check_online_event);
1063                 }
1064         }
1065
1066         /* Ensure we're not handling an event inherited from
1067            our parent. */
1068
1069         cancel_named_event(winbind_event_context(),
1070                            "krb5_ticket_refresh_handler");
1071
1072         /* We might be in the idmap child...*/
1073         if (child->domain && !(child->domain->internal) &&
1074             lp_winbind_offline_logon()) {
1075
1076                 set_domain_online_request(child->domain);
1077
1078                 child->lockout_policy_event = event_add_timed(
1079                         winbind_event_context(), NULL, timeval_zero(),
1080                         "account_lockout_policy_handler",
1081                         account_lockout_policy_handler,
1082                         child);
1083         }
1084
1085         /* Special case for Winbindd on a Samba DC,
1086          * We want to make sure the child can connect to smbd
1087          * but not the main daemon */
1088
1089         if (child->domain && child->domain->internal && IS_DC) {
1090                 child->domain->internal = False;
1091                 child->domain->methods = &cache_methods;
1092                 child->domain->online = False;
1093         }
1094
1095         while (1) {
1096
1097                 int ret;
1098                 fd_set read_fds;
1099                 struct timeval t;
1100                 struct timeval *tp;
1101                 struct timeval now;
1102                 TALLOC_CTX *frame = talloc_stackframe();
1103
1104                 run_events(winbind_event_context(), 0, NULL, NULL);
1105
1106                 GetTimeOfDay(&now);
1107
1108                 if (child->domain && child->domain->startup &&
1109                                 (now.tv_sec > child->domain->startup_time + 30)) {
1110                         /* No longer in "startup" mode. */
1111                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1112                                 child->domain->name ));
1113                         child->domain->startup = False;
1114                 }
1115
1116                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1117                 if (tp) {
1118                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1119                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1120                 }
1121
1122                 /* Handle messages */
1123
1124                 message_dispatch(winbind_messaging_context());
1125
1126                 FD_ZERO(&read_fds);
1127                 FD_SET(state.sock, &read_fds);
1128
1129                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
1130
1131                 if (ret == 0) {
1132                         DEBUG(11,("nothing is ready yet, continue\n"));
1133                         TALLOC_FREE(frame);
1134                         continue;
1135                 }
1136
1137                 if (ret == -1 && errno == EINTR) {
1138                         /* We got a signal - continue. */
1139                         TALLOC_FREE(frame);
1140                         continue;
1141                 }
1142
1143                 if (ret == -1 && errno != EINTR) {
1144                         DEBUG(0,("select error occured\n"));
1145                         TALLOC_FREE(frame);
1146                         perror("select");
1147                         return False;
1148                 }
1149
1150                 /* fetch a request from the main daemon */
1151                 child_read_request(&state);
1152
1153                 if (state.finished) {
1154                         /* we lost contact with our parent */
1155                         exit(0);
1156                 }
1157
1158                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1159
1160                 ZERO_STRUCT(state.response);
1161                 state.request.null_term = '\0';
1162                 child_process_request(child, &state);
1163
1164                 SAFE_FREE(state.request.extra_data.data);
1165
1166                 cache_store_response(sys_getpid(), &state.response);
1167
1168                 SAFE_FREE(state.response.extra_data.data);
1169
1170                 /* We just send the result code back, the result
1171                  * structure needs to be fetched via the
1172                  * winbindd_cache. Hmm. That needs fixing... */
1173
1174                 if (write_data(state.sock,
1175                                (const char *)&state.response.result,
1176                                sizeof(state.response.result)) !=
1177                     sizeof(state.response.result)) {
1178                         DEBUG(0, ("Could not write result\n"));
1179                         exit(1);
1180                 }
1181                 TALLOC_FREE(frame);
1182         }
1183 }