Fix broken krb5 refresh chain
[kamenim/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 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         NTSTATUS status;
44
45         /* Read data */
46
47         status = read_data(state->sock, (char *)&state->request,
48                            sizeof(state->request));
49
50         if (!NT_STATUS_IS_OK(status)) {
51                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
52                           nt_errstr(status)));
53                 state->finished = True;
54                 return;
55         }
56
57         if (state->request.extra_len == 0) {
58                 state->request.extra_data.data = NULL;
59                 return;
60         }
61
62         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request.extra_len));
63
64         state->request.extra_data.data =
65                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
66
67         if (state->request.extra_data.data == NULL) {
68                 DEBUG(0, ("malloc failed\n"));
69                 state->finished = True;
70                 return;
71         }
72
73         /* Ensure null termination */
74         state->request.extra_data.data[state->request.extra_len] = '\0';
75
76         status= read_data(state->sock, state->request.extra_data.data,
77                           state->request.extra_len);
78
79         if (!NT_STATUS_IS_OK(status)) {
80                 DEBUG(0, ("Could not read extra data: %s\n",
81                           nt_errstr(status)));
82                 state->finished = True;
83                 return;
84         }
85 }
86
87 /*
88  * Machinery for async requests sent to children. You set up a
89  * winbindd_request, select a child to query, and issue a async_request
90  * call. When the request is completed, the callback function you specified is
91  * called back with the private pointer you gave to async_request.
92  */
93
94 struct winbindd_async_request {
95         struct winbindd_async_request *next, *prev;
96         TALLOC_CTX *mem_ctx;
97         struct winbindd_child *child;
98         struct winbindd_request *request;
99         struct winbindd_response *response;
100         void (*continuation)(void *private_data, bool success);
101         struct timed_event *reply_timeout_event;
102         pid_t child_pid; /* pid of the child we're waiting on. Used to detect
103                             a restart of the child (child->pid != child_pid). */
104         void *private_data;
105 };
106
107 static void async_request_fail(struct winbindd_async_request *state);
108 static void async_main_request_sent(void *private_data, bool success);
109 static void async_request_sent(void *private_data, bool success);
110 static void async_reply_recv(void *private_data, bool success);
111 static void schedule_async_request(struct winbindd_child *child);
112
113 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
114                    struct winbindd_request *request,
115                    struct winbindd_response *response,
116                    void (*continuation)(void *private_data, bool success),
117                    void *private_data)
118 {
119         struct winbindd_async_request *state;
120
121         SMB_ASSERT(continuation != NULL);
122
123         DEBUG(10, ("Sending request to child pid %d (domain=%s)\n",
124                    (int)child->pid,
125                    (child->domain != NULL) ? child->domain->name : "''"));
126
127         state = TALLOC_P(mem_ctx, struct winbindd_async_request);
128
129         if (state == NULL) {
130                 DEBUG(0, ("talloc failed\n"));
131                 continuation(private_data, False);
132                 return;
133         }
134
135         state->mem_ctx = mem_ctx;
136         state->child = child;
137         state->reply_timeout_event = NULL;
138         state->request = request;
139         state->response = response;
140         state->continuation = continuation;
141         state->private_data = private_data;
142
143         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
144
145         schedule_async_request(child);
146
147         return;
148 }
149
150 static void async_main_request_sent(void *private_data, bool success)
151 {
152         struct winbindd_async_request *state =
153                 talloc_get_type_abort(private_data, struct winbindd_async_request);
154
155         if (!success) {
156                 DEBUG(5, ("Could not send async request\n"));
157                 async_request_fail(state);
158                 return;
159         }
160
161         if (state->request->extra_len == 0) {
162                 async_request_sent(private_data, True);
163                 return;
164         }
165
166         setup_async_write(&state->child->event, state->request->extra_data.data,
167                           state->request->extra_len,
168                           async_request_sent, state);
169 }
170
171 /****************************************************************
172  Handler triggered if the child winbindd doesn't respond within
173  a given timeout.
174 ****************************************************************/
175
176 static void async_request_timeout_handler(struct event_context *ctx,
177                                         struct timed_event *te,
178                                         const struct timeval *now,
179                                         void *private_data)
180 {
181         struct winbindd_async_request *state =
182                 talloc_get_type_abort(private_data, struct winbindd_async_request);
183
184         DEBUG(0,("async_request_timeout_handler: child pid %u is not responding. "
185                 "Closing connection to it.\n",
186                 state->child_pid ));
187
188         /* Deal with the reply - set to error. */
189         async_reply_recv(private_data, False);
190 }
191
192 /**************************************************************
193  Common function called on both async send and recv fail.
194  Cleans up the child and schedules the next request.
195 **************************************************************/
196
197 static void async_request_fail(struct winbindd_async_request *state)
198 {
199         DLIST_REMOVE(state->child->requests, state);
200
201         TALLOC_FREE(state->reply_timeout_event);
202
203         /* If child exists and is not already reaped,
204            send kill signal to child. */
205
206         if ((state->child->pid != (pid_t)0) &&
207                         (state->child->pid != (pid_t)-1) &&
208                         (state->child->pid == state->child_pid)) {
209                 kill(state->child_pid, SIGTERM);
210
211                 /* 
212                  * Close the socket to the child.
213                  */
214                 winbind_child_died(state->child_pid);
215         }
216
217         state->response->length = sizeof(struct winbindd_response);
218         state->response->result = WINBINDD_ERROR;
219         state->continuation(state->private_data, False);
220 }
221
222 static void async_request_sent(void *private_data_data, bool success)
223 {
224         struct winbindd_async_request *state =
225                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
226
227         if (!success) {
228                 DEBUG(5, ("Could not send async request to child pid %u\n",
229                         (unsigned int)state->child_pid ));
230                 async_request_fail(state);
231                 return;
232         }
233
234         /* Request successfully sent to the child, setup the wait for reply */
235
236         setup_async_read(&state->child->event,
237                          &state->response->result,
238                          sizeof(state->response->result),
239                          async_reply_recv, state);
240
241         /* 
242          * Set up a timeout of 300 seconds for the response.
243          * If we don't get it close the child socket and
244          * report failure.
245          */
246
247         state->reply_timeout_event = event_add_timed(winbind_event_context(),
248                                                         NULL,
249                                                         timeval_current_ofs(300,0),
250                                                         "async_request_timeout",
251                                                         async_request_timeout_handler,
252                                                         state);
253         if (!state->reply_timeout_event) {
254                 smb_panic("async_request_sent: failed to add timeout handler.\n");
255         }
256 }
257
258 static void async_reply_recv(void *private_data, bool success)
259 {
260         struct winbindd_async_request *state =
261                 talloc_get_type_abort(private_data, struct winbindd_async_request);
262         struct winbindd_child *child = state->child;
263
264         TALLOC_FREE(state->reply_timeout_event);
265
266         state->response->length = sizeof(struct winbindd_response);
267
268         if (!success) {
269                 DEBUG(5, ("Could not receive async reply from child pid %u\n",
270                         (unsigned int)state->child_pid ));
271
272                 cache_cleanup_response(state->child_pid);
273                 async_request_fail(state);
274                 return;
275         }
276
277         SMB_ASSERT(cache_retrieve_response(state->child_pid,
278                                            state->response));
279
280         cache_cleanup_response(state->child_pid);
281         
282         DLIST_REMOVE(child->requests, state);
283
284         schedule_async_request(child);
285
286         state->continuation(state->private_data, True);
287 }
288
289 static bool fork_domain_child(struct winbindd_child *child);
290
291 static void schedule_async_request(struct winbindd_child *child)
292 {
293         struct winbindd_async_request *request = child->requests;
294
295         if (request == NULL) {
296                 return;
297         }
298
299         if (child->event.flags != 0) {
300                 return;         /* Busy */
301         }
302
303         /*
304          * This may be a reschedule, so we might
305          * have an existing timeout event pending on
306          * the first entry in the child->requests list
307          * (we only send one request at a time).
308          * Ensure we free it before we reschedule.
309          * Bug #5814, from hargagan <shargagan@novell.com>.
310          * JRA.
311          */
312
313         TALLOC_FREE(request->reply_timeout_event);
314
315         if ((child->pid == 0) && (!fork_domain_child(child))) {
316                 /* fork_domain_child failed.
317                    Cancel all outstanding requests */
318
319                 while (request != NULL) {
320                         /* request might be free'd in the continuation */
321                         struct winbindd_async_request *next = request->next;
322
323                         async_request_fail(request);
324                         request = next;
325                 }
326                 return;
327         }
328
329         /* Now we know who we're sending to - remember the pid. */
330         request->child_pid = child->pid;
331
332         setup_async_write(&child->event, request->request,
333                           sizeof(*request->request),
334                           async_main_request_sent, request);
335
336         return;
337 }
338
339 struct domain_request_state {
340         TALLOC_CTX *mem_ctx;
341         struct winbindd_domain *domain;
342         struct winbindd_request *request;
343         struct winbindd_response *response;
344         void (*continuation)(void *private_data_data, bool success);
345         void *private_data_data;
346 };
347
348 static void domain_init_recv(void *private_data_data, bool success);
349
350 void async_domain_request(TALLOC_CTX *mem_ctx,
351                           struct winbindd_domain *domain,
352                           struct winbindd_request *request,
353                           struct winbindd_response *response,
354                           void (*continuation)(void *private_data_data, bool success),
355                           void *private_data_data)
356 {
357         struct domain_request_state *state;
358
359         if (domain->initialized) {
360                 async_request(mem_ctx, &domain->child, request, response,
361                               continuation, private_data_data);
362                 return;
363         }
364
365         state = TALLOC_P(mem_ctx, struct domain_request_state);
366         if (state == NULL) {
367                 DEBUG(0, ("talloc failed\n"));
368                 continuation(private_data_data, False);
369                 return;
370         }
371
372         state->mem_ctx = mem_ctx;
373         state->domain = domain;
374         state->request = request;
375         state->response = response;
376         state->continuation = continuation;
377         state->private_data_data = private_data_data;
378
379         init_child_connection(domain, domain_init_recv, state);
380 }
381
382 static void domain_init_recv(void *private_data_data, bool success)
383 {
384         struct domain_request_state *state =
385                 talloc_get_type_abort(private_data_data, struct domain_request_state);
386
387         if (!success) {
388                 DEBUG(5, ("Domain init returned an error\n"));
389                 state->continuation(state->private_data_data, False);
390                 return;
391         }
392
393         async_request(state->mem_ctx, &state->domain->child,
394                       state->request, state->response,
395                       state->continuation, state->private_data_data);
396 }
397
398 static void recvfrom_child(void *private_data_data, bool success)
399 {
400         struct winbindd_cli_state *state =
401                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
402         enum winbindd_result result = state->response.result;
403
404         /* This is an optimization: The child has written directly to the
405          * response buffer. The request itself is still in pending state,
406          * state that in the result code. */
407
408         state->response.result = WINBINDD_PENDING;
409
410         if ((!success) || (result != WINBINDD_OK)) {
411                 request_error(state);
412                 return;
413         }
414
415         request_ok(state);
416 }
417
418 void sendto_child(struct winbindd_cli_state *state,
419                   struct winbindd_child *child)
420 {
421         async_request(state->mem_ctx, child, &state->request,
422                       &state->response, recvfrom_child, state);
423 }
424
425 void sendto_domain(struct winbindd_cli_state *state,
426                    struct winbindd_domain *domain)
427 {
428         async_domain_request(state->mem_ctx, domain,
429                              &state->request, &state->response,
430                              recvfrom_child, state);
431 }
432
433 static void child_process_request(struct winbindd_child *child,
434                                   struct winbindd_cli_state *state)
435 {
436         struct winbindd_domain *domain = child->domain;
437         const struct winbindd_child_dispatch_table *table = child->table;
438
439         /* Free response data - we may be interrupted and receive another
440            command before being able to send this data off. */
441
442         state->response.result = WINBINDD_ERROR;
443         state->response.length = sizeof(struct winbindd_response);
444
445         /* as all requests in the child are sync, we can use talloc_tos() */
446         state->mem_ctx = talloc_tos();
447
448         /* Process command */
449
450         for (; table->name; table++) {
451                 if (state->request.cmd == table->struct_cmd) {
452                         DEBUG(10,("child_process_request: request fn %s\n",
453                                   table->name));
454                         state->response.result = table->struct_fn(domain, state);
455                         return;
456                 }
457         }
458
459         DEBUG(1 ,("child_process_request: unknown request fn number %d\n",
460                   (int)state->request.cmd));
461         state->response.result = WINBINDD_ERROR;
462 }
463
464 void setup_child(struct winbindd_child *child,
465                  const struct winbindd_child_dispatch_table *table,
466                  const char *logprefix,
467                  const char *logname)
468 {
469         if (logprefix && logname) {
470                 if (asprintf(&child->logfilename, "%s/%s-%s",
471                              get_dyn_LOGFILEBASE(), logprefix, logname) < 0) {
472                         smb_panic("Internal error: asprintf failed");
473                 }
474         } else {
475                 smb_panic("Internal error: logprefix == NULL && "
476                           "logname == NULL");
477         }
478
479         child->domain = NULL;
480         child->table = table;
481 }
482
483 struct winbindd_child *children = NULL;
484
485 void winbind_child_died(pid_t pid)
486 {
487         struct winbindd_child *child;
488
489         for (child = children; child != NULL; child = child->next) {
490                 if (child->pid == pid) {
491                         break;
492                 }
493         }
494
495         if (child == NULL) {
496                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
497                 return;
498         }
499
500         /* This will be re-added in fork_domain_child() */
501
502         DLIST_REMOVE(children, child);
503         
504         remove_fd_event(&child->event);
505         close(child->event.fd);
506         child->event.fd = 0;
507         child->event.flags = 0;
508         child->pid = 0;
509
510         if (child->requests) {
511                 /*
512                  * schedule_async_request() will also
513                  * clear this event but the call is
514                  * idempotent so it doesn't hurt to
515                  * cover all possible future code
516                  * paths. JRA.
517                  */
518                 TALLOC_FREE(child->requests->reply_timeout_event);
519         }
520
521         schedule_async_request(child);
522 }
523
524 /* Ensure any negative cache entries with the netbios or realm names are removed. */
525
526 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
527 {
528         flush_negative_conn_cache_for_domain(domain->name);
529         if (*domain->alt_name) {
530                 flush_negative_conn_cache_for_domain(domain->alt_name);
531         }
532 }
533
534 /* 
535  * Parent winbindd process sets its own debug level first and then
536  * sends a message to all the winbindd children to adjust their debug
537  * level to that of parents.
538  */
539
540 void winbind_msg_debug(struct messaging_context *msg_ctx,
541                          void *private_data,
542                          uint32_t msg_type,
543                          struct server_id server_id,
544                          DATA_BLOB *data)
545 {
546         struct winbindd_child *child;
547
548         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
549         
550         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
551
552         for (child = children; child != NULL; child = child->next) {
553
554                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
555                         (unsigned int)child->pid));
556
557                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
558                            MSG_DEBUG,
559                            data->data,
560                            strlen((char *) data->data) + 1);
561         }
562 }
563
564 /* Set our domains as offline and forward the offline message to our children. */
565
566 void winbind_msg_offline(struct messaging_context *msg_ctx,
567                          void *private_data,
568                          uint32_t msg_type,
569                          struct server_id server_id,
570                          DATA_BLOB *data)
571 {
572         struct winbindd_child *child;
573         struct winbindd_domain *domain;
574
575         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
576
577         if (!lp_winbind_offline_logon()) {
578                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
579                 return;
580         }
581
582         /* Set our global state as offline. */
583         if (!set_global_winbindd_state_offline()) {
584                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
585                 return;
586         }
587
588         /* Set all our domains as offline. */
589         for (domain = domain_list(); domain; domain = domain->next) {
590                 if (domain->internal) {
591                         continue;
592                 }
593                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
594                 set_domain_offline(domain);
595         }
596
597         for (child = children; child != NULL; child = child->next) {
598                 /* Don't send message to internal childs.  We've already
599                    done so above. */
600                 if (!child->domain || winbindd_internal_child(child)) {
601                         continue;
602                 }
603
604                 /* Or internal domains (this should not be possible....) */
605                 if (child->domain->internal) {
606                         continue;
607                 }
608
609                 /* Each winbindd child should only process requests for one domain - make sure
610                    we only set it online / offline for that domain. */
611
612                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
613                         (unsigned int)child->pid, domain->name ));
614
615                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
616                                    MSG_WINBIND_OFFLINE,
617                                    (uint8 *)child->domain->name,
618                                    strlen(child->domain->name)+1);
619         }
620 }
621
622 /* Set our domains as online and forward the online message to our children. */
623
624 void winbind_msg_online(struct messaging_context *msg_ctx,
625                         void *private_data,
626                         uint32_t msg_type,
627                         struct server_id server_id,
628                         DATA_BLOB *data)
629 {
630         struct winbindd_child *child;
631         struct winbindd_domain *domain;
632
633         DEBUG(10,("winbind_msg_online: got online message.\n"));
634
635         if (!lp_winbind_offline_logon()) {
636                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
637                 return;
638         }
639
640         /* Set our global state as online. */
641         set_global_winbindd_state_online();
642
643         smb_nscd_flush_user_cache();
644         smb_nscd_flush_group_cache();
645
646         /* Set all our domains as online. */
647         for (domain = domain_list(); domain; domain = domain->next) {
648                 if (domain->internal) {
649                         continue;
650                 }
651                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
652
653                 winbindd_flush_negative_conn_cache(domain);
654                 set_domain_online_request(domain);
655
656                 /* Send an online message to the idmap child when our
657                    primary domain comes back online */
658
659                 if ( domain->primary ) {
660                         struct winbindd_child *idmap = idmap_child();
661                         
662                         if ( idmap->pid != 0 ) {
663                                 messaging_send_buf(msg_ctx,
664                                                    pid_to_procid(idmap->pid), 
665                                                    MSG_WINBIND_ONLINE,
666                                                    (uint8 *)domain->name,
667                                                    strlen(domain->name)+1);
668                         }
669                         
670                 }
671         }
672
673         for (child = children; child != NULL; child = child->next) {
674                 /* Don't send message to internal childs. */
675                 if (!child->domain || winbindd_internal_child(child)) {
676                         continue;
677                 }
678
679                 /* Or internal domains (this should not be possible....) */
680                 if (child->domain->internal) {
681                         continue;
682                 }
683
684                 /* Each winbindd child should only process requests for one domain - make sure
685                    we only set it online / offline for that domain. */
686
687                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
688                         (unsigned int)child->pid, child->domain->name ));
689
690                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
691                                    MSG_WINBIND_ONLINE,
692                                    (uint8 *)child->domain->name,
693                                    strlen(child->domain->name)+1);
694         }
695 }
696
697 /* Forward the online/offline messages to our children. */
698 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
699                               void *private_data,
700                               uint32_t msg_type,
701                               struct server_id server_id,
702                               DATA_BLOB *data)
703 {
704         struct winbindd_child *child;
705
706         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
707
708         for (child = children; child != NULL; child = child->next) {
709                 if (child->domain && child->domain->primary) {
710                         DEBUG(10,("winbind_msg_onlinestatus: "
711                                   "sending message to pid %u of primary domain.\n",
712                                   (unsigned int)child->pid));
713                         messaging_send_buf(msg_ctx, pid_to_procid(child->pid), 
714                                            MSG_WINBIND_ONLINESTATUS,
715                                            (uint8 *)data->data,
716                                            data->length);
717                         break;
718                 }
719         }
720 }
721
722 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
723                                  void *private_data,
724                                  uint32_t msg_type,
725                                  struct server_id server_id,
726                                  DATA_BLOB *data)
727 {
728         struct winbindd_child *child;
729
730         DEBUG(10,("winbind_msg_dump_event_list received\n"));
731
732         dump_event_list(winbind_event_context());
733
734         for (child = children; child != NULL; child = child->next) {
735
736                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
737                         (unsigned int)child->pid));
738
739                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
740                                    MSG_DUMP_EVENT_LIST,
741                                    NULL, 0);
742         }
743
744 }
745
746 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
747                                   void *private_data,
748                                   uint32_t msg_type,
749                                   struct server_id server_id,
750                                   DATA_BLOB *data)
751 {
752         TALLOC_CTX *mem_ctx;
753         const char *message = NULL;
754         struct server_id *sender = NULL;
755         const char *domain = NULL;
756         char *s = NULL;
757         NTSTATUS status;
758         struct winbindd_domain *dom = NULL;
759
760         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
761
762         if (!data || !data->data) {
763                 return;
764         }
765
766         if (data->length < sizeof(struct server_id)) {
767                 return;
768         }
769
770         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
771         if (!mem_ctx) {
772                 return;
773         }
774
775         sender = (struct server_id *)data->data;
776         if (data->length > sizeof(struct server_id)) {
777                 domain = (const char *)data->data+sizeof(struct server_id);
778         }
779
780         if (domain) {
781
782                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
783                         domain));
784
785                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
786                                                   find_domain_from_name_noinit(domain));
787                 if (!message) {
788                         talloc_destroy(mem_ctx);
789                         return;
790                 }
791
792                 messaging_send_buf(msg_ctx, *sender,
793                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
794                                    (uint8_t *)message, strlen(message) + 1);
795
796                 talloc_destroy(mem_ctx);
797
798                 return;
799         }
800
801         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
802
803         for (dom = domain_list(); dom; dom=dom->next) {
804                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
805                 if (!message) {
806                         talloc_destroy(mem_ctx);
807                         return;
808                 }
809
810                 s = talloc_asprintf_append(s, "%s\n", message);
811                 if (!s) {
812                         talloc_destroy(mem_ctx);
813                         return;
814                 }
815         }
816
817         status = messaging_send_buf(msg_ctx, *sender,
818                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
819                                     (uint8_t *)s, strlen(s) + 1);
820         if (!NT_STATUS_IS_OK(status)) {
821                 DEBUG(0,("failed to send message: %s\n",
822                 nt_errstr(status)));
823         }
824
825         talloc_destroy(mem_ctx);
826 }
827
828 static void account_lockout_policy_handler(struct event_context *ctx,
829                                            struct timed_event *te,
830                                            const struct timeval *now,
831                                            void *private_data)
832 {
833         struct winbindd_child *child =
834                 (struct winbindd_child *)private_data;
835         TALLOC_CTX *mem_ctx = NULL;
836         struct winbindd_methods *methods;
837         struct samr_DomInfo12 lockout_policy;
838         NTSTATUS result;
839
840         DEBUG(10,("account_lockout_policy_handler called\n"));
841
842         TALLOC_FREE(child->lockout_policy_event);
843
844         if ( !winbindd_can_contact_domain( child->domain ) ) {
845                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
846                           "do not have an incoming trust to domain %s\n", 
847                           child->domain->name));
848
849                 return;         
850         }
851
852         methods = child->domain->methods;
853
854         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
855         if (!mem_ctx) {
856                 result = NT_STATUS_NO_MEMORY;
857         } else {
858                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
859         }
860         TALLOC_FREE(mem_ctx);
861
862         if (!NT_STATUS_IS_OK(result)) {
863                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
864                          nt_errstr(result)));
865         }
866
867         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
868                                                       timeval_current_ofs(3600, 0),
869                                                       "account_lockout_policy_handler",
870                                                       account_lockout_policy_handler,
871                                                       child);
872 }
873
874 static time_t get_machine_password_timeout(void)
875 {
876         /* until we have gpo support use lp setting */
877         return lp_machine_password_timeout();
878 }
879
880 static bool calculate_next_machine_pwd_change(const char *domain,
881                                               struct timeval *t)
882 {
883         time_t pass_last_set_time;
884         time_t timeout;
885         time_t next_change;
886         char *pw;
887
888         pw = secrets_fetch_machine_password(domain,
889                                             &pass_last_set_time,
890                                             NULL);
891
892         if (pw == NULL) {
893                 DEBUG(0,("cannot fetch own machine password ????"));
894                 return false;
895         }
896
897         SAFE_FREE(pw);
898
899         timeout = get_machine_password_timeout();
900         if (timeout == 0) {
901                 DEBUG(10,("machine password never expires\n"));
902                 return false;
903         }
904
905         if (time(NULL) < (pass_last_set_time + timeout)) {
906                 next_change = pass_last_set_time + timeout;
907                 DEBUG(10,("machine password still valid until: %s\n",
908                         http_timestring(talloc_tos(), next_change)));
909                 *t = timeval_set(next_change, 0);
910                 return true;
911         }
912
913         DEBUG(10,("machine password expired, needs immediate change\n"));
914
915         *t = timeval_zero();
916
917         return true;
918 }
919
920 static void machine_password_change_handler(struct event_context *ctx,
921                                             struct timed_event *te,
922                                             const struct timeval *now,
923                                             void *private_data)
924 {
925         struct winbindd_child *child =
926                 (struct winbindd_child *)private_data;
927         struct rpc_pipe_client *netlogon_pipe = NULL;
928         TALLOC_CTX *frame;
929         NTSTATUS result;
930         struct timeval next_change;
931
932         DEBUG(10,("machine_password_change_handler called\n"));
933
934         TALLOC_FREE(child->machine_password_change_event);
935
936         if (!calculate_next_machine_pwd_change(child->domain->name,
937                                                &next_change)) {
938                 return;
939         }
940
941         if (!winbindd_can_contact_domain(child->domain)) {
942                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
943                           "do not have an incoming trust to domain %s\n",
944                           child->domain->name));
945                 return;
946         }
947
948         result = cm_connect_netlogon(child->domain, &netlogon_pipe);
949         if (!NT_STATUS_IS_OK(result)) {
950                 DEBUG(10,("machine_password_change_handler: "
951                         "failed to connect netlogon pipe: %s\n",
952                          nt_errstr(result)));
953                 return;
954         }
955
956         frame = talloc_stackframe();
957
958         result = trust_pw_find_change_and_store_it(netlogon_pipe,
959                                                    frame,
960                                                    child->domain->name);
961         TALLOC_FREE(frame);
962
963         if (!NT_STATUS_IS_OK(result)) {
964                 DEBUG(10,("machine_password_change_handler: "
965                         "failed to change machine password: %s\n",
966                          nt_errstr(result)));
967         } else {
968                 DEBUG(10,("machine_password_change_handler: "
969                         "successfully changed machine password\n"));
970         }
971
972         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
973                                                               next_change,
974                                                               "machine_password_change_handler",
975                                                               machine_password_change_handler,
976                                                               child);
977 }
978
979 /* Deal with a request to go offline. */
980
981 static void child_msg_offline(struct messaging_context *msg,
982                               void *private_data,
983                               uint32_t msg_type,
984                               struct server_id server_id,
985                               DATA_BLOB *data)
986 {
987         struct winbindd_domain *domain;
988         struct winbindd_domain *primary_domain = NULL;
989         const char *domainname = (const char *)data->data;
990
991         if (data->data == NULL || data->length == 0) {
992                 return;
993         }
994
995         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
996
997         if (!lp_winbind_offline_logon()) {
998                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
999                 return;
1000         }
1001
1002         primary_domain = find_our_domain();
1003
1004         /* Mark the requested domain offline. */
1005
1006         for (domain = domain_list(); domain; domain = domain->next) {
1007                 if (domain->internal) {
1008                         continue;
1009                 }
1010                 if (strequal(domain->name, domainname)) {
1011                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1012                         set_domain_offline(domain);
1013                         /* we are in the trusted domain, set the primary domain 
1014                          * offline too */
1015                         if (domain != primary_domain) {
1016                                 set_domain_offline(primary_domain);
1017                         }
1018                 }
1019         }
1020 }
1021
1022 /* Deal with a request to go online. */
1023
1024 static void child_msg_online(struct messaging_context *msg,
1025                              void *private_data,
1026                              uint32_t msg_type,
1027                              struct server_id server_id,
1028                              DATA_BLOB *data)
1029 {
1030         struct winbindd_domain *domain;
1031         struct winbindd_domain *primary_domain = NULL;
1032         const char *domainname = (const char *)data->data;
1033
1034         if (data->data == NULL || data->length == 0) {
1035                 return;
1036         }
1037
1038         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1039
1040         if (!lp_winbind_offline_logon()) {
1041                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1042                 return;
1043         }
1044
1045         primary_domain = find_our_domain();
1046
1047         /* Set our global state as online. */
1048         set_global_winbindd_state_online();
1049
1050         /* Try and mark everything online - delete any negative cache entries
1051            to force a reconnect now. */
1052
1053         for (domain = domain_list(); domain; domain = domain->next) {
1054                 if (domain->internal) {
1055                         continue;
1056                 }
1057                 if (strequal(domain->name, domainname)) {
1058                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1059                         winbindd_flush_negative_conn_cache(domain);
1060                         set_domain_online_request(domain);
1061
1062                         /* we can be in trusted domain, which will contact primary domain
1063                          * we have to bring primary domain online in trusted domain process
1064                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1065                          * --> contact_domain = find_our_domain()
1066                          * */
1067                         if (domain != primary_domain) {
1068                                 winbindd_flush_negative_conn_cache(primary_domain);
1069                                 set_domain_online_request(primary_domain);
1070                         }
1071                 }
1072         }
1073 }
1074
1075 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
1076 {
1077         struct winbindd_domain *domain;
1078         char *buf = NULL;
1079
1080         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
1081                                    get_global_winbindd_state_offline() ? 
1082                                    "Offline":"Online")) == NULL) {
1083                 return NULL;
1084         }
1085
1086         for (domain = domain_list(); domain; domain = domain->next) {
1087                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
1088                                                   domain->name, 
1089                                                   domain->online ?
1090                                                   "Online":"Offline")) == NULL) {
1091                         return NULL;
1092                 }
1093         }
1094
1095         buf = talloc_asprintf_append_buffer(buf, "\n");
1096
1097         DEBUG(5,("collect_onlinestatus: %s", buf));
1098
1099         return buf;
1100 }
1101
1102 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
1103                                    void *private_data,
1104                                    uint32_t msg_type,
1105                                    struct server_id server_id,
1106                                    DATA_BLOB *data)
1107 {
1108         TALLOC_CTX *mem_ctx;
1109         const char *message;
1110         struct server_id *sender;
1111         
1112         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
1113
1114         if (!data->data) {
1115                 return;
1116         }
1117
1118         sender = (struct server_id *)data->data;
1119
1120         mem_ctx = talloc_init("winbind_msg_onlinestatus");
1121         if (mem_ctx == NULL) {
1122                 return;
1123         }
1124         
1125         message = collect_onlinestatus(mem_ctx);
1126         if (message == NULL) {
1127                 talloc_destroy(mem_ctx);
1128                 return;
1129         }
1130
1131         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
1132                            (uint8 *)message, strlen(message) + 1);
1133
1134         talloc_destroy(mem_ctx);
1135 }
1136
1137 static void child_msg_dump_event_list(struct messaging_context *msg,
1138                                       void *private_data,
1139                                       uint32_t msg_type,
1140                                       struct server_id server_id,
1141                                       DATA_BLOB *data)
1142 {
1143         DEBUG(5,("child_msg_dump_event_list received\n"));
1144
1145         dump_event_list(winbind_event_context());
1146 }
1147
1148
1149 static bool fork_domain_child(struct winbindd_child *child)
1150 {
1151         int fdpair[2];
1152         struct winbindd_cli_state state;
1153         struct winbindd_domain *domain;
1154         struct winbindd_domain *primary_domain = NULL;
1155
1156         if (child->domain) {
1157                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1158                            child->domain->name));
1159         } else {
1160                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1161         }
1162
1163         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1164                 DEBUG(0, ("Could not open child pipe: %s\n",
1165                           strerror(errno)));
1166                 return False;
1167         }
1168
1169         ZERO_STRUCT(state);
1170         state.pid = sys_getpid();
1171
1172         child->pid = sys_fork();
1173
1174         if (child->pid == -1) {
1175                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1176                 return False;
1177         }
1178
1179         if (child->pid != 0) {
1180                 /* Parent */
1181                 close(fdpair[0]);
1182                 child->next = child->prev = NULL;
1183                 DLIST_ADD(children, child);
1184                 child->event.fd = fdpair[1];
1185                 child->event.flags = 0;
1186                 child->requests = NULL;
1187                 add_fd_event(&child->event);
1188                 return True;
1189         }
1190
1191         /* Child */
1192
1193         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1194
1195         /* Stop zombies in children */
1196         CatchChild();
1197
1198         state.sock = fdpair[0];
1199         close(fdpair[1]);
1200
1201         if (!reinit_after_fork(winbind_messaging_context(),
1202                                winbind_event_context(), true)) {
1203                 DEBUG(0,("reinit_after_fork() failed\n"));
1204                 _exit(0);
1205         }
1206
1207         close_conns_after_fork();
1208
1209         if (!override_logfile) {
1210                 lp_set_logfile(child->logfilename);
1211                 reopen_logs();
1212         }
1213
1214         /* Don't handle the same messages as our parent. */
1215         messaging_deregister(winbind_messaging_context(),
1216                              MSG_SMB_CONF_UPDATED, NULL);
1217         messaging_deregister(winbind_messaging_context(),
1218                              MSG_SHUTDOWN, NULL);
1219         messaging_deregister(winbind_messaging_context(),
1220                              MSG_WINBIND_OFFLINE, NULL);
1221         messaging_deregister(winbind_messaging_context(),
1222                              MSG_WINBIND_ONLINE, NULL);
1223         messaging_deregister(winbind_messaging_context(),
1224                              MSG_WINBIND_ONLINESTATUS, NULL);
1225         messaging_deregister(winbind_messaging_context(),
1226                              MSG_DUMP_EVENT_LIST, NULL);
1227         messaging_deregister(winbind_messaging_context(),
1228                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1229         messaging_deregister(winbind_messaging_context(),
1230                              MSG_DEBUG, NULL);
1231
1232         /* Handle online/offline messages. */
1233         messaging_register(winbind_messaging_context(), NULL,
1234                            MSG_WINBIND_OFFLINE, child_msg_offline);
1235         messaging_register(winbind_messaging_context(), NULL,
1236                            MSG_WINBIND_ONLINE, child_msg_online);
1237         messaging_register(winbind_messaging_context(), NULL,
1238                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
1239         messaging_register(winbind_messaging_context(), NULL,
1240                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1241         messaging_register(winbind_messaging_context(), NULL,
1242                            MSG_DEBUG, debug_message);
1243
1244         primary_domain = find_our_domain();
1245
1246         if (primary_domain == NULL) {
1247                 smb_panic("no primary domain found");
1248         }
1249         /* we have destroy all time event in reinit_after_fork()
1250          * set check_online_event to NULL */
1251         for (domain = domain_list(); domain; domain = domain->next) {
1252                 domain->check_online_event = NULL;
1253         }
1254         /* It doesn't matter if we allow cache login,
1255          * try to bring domain online after fork. */
1256         if ( child->domain ) {
1257                 child->domain->startup = True;
1258                 child->domain->startup_time = time(NULL);
1259                 /* we can be in primary domain or in trusted domain
1260                  * If we are in trusted domain, set the primary domain
1261                  * in start-up mode */
1262                 if (!(child->domain->internal)) {
1263                         set_domain_online_request(child->domain);
1264                         if (!(child->domain->primary)) {
1265                                 primary_domain->startup = True;
1266                                 primary_domain->startup_time = time(NULL);
1267                                 set_domain_online_request(primary_domain);
1268                         }
1269                 }
1270         }
1271
1272         /* Ensure we're not handling an event inherited from
1273            our parent. */
1274
1275         cancel_named_event(winbind_event_context(),
1276                            "krb5_ticket_refresh_handler");
1277
1278         /* We might be in the idmap child...*/
1279         if (child->domain && !(child->domain->internal) &&
1280             lp_winbind_offline_logon()) {
1281
1282                 set_domain_online_request(child->domain);
1283
1284                 if (primary_domain && (primary_domain != child->domain)) {
1285                         /* We need to talk to the primary
1286                          * domain as well as the trusted
1287                          * domain inside a trusted domain
1288                          * child.
1289                          * See the code in :
1290                          * set_dc_type_and_flags_trustinfo()
1291                          * for details.
1292                          */
1293                         set_domain_online_request(primary_domain);
1294                 }
1295
1296                 child->lockout_policy_event = event_add_timed(
1297                         winbind_event_context(), NULL, timeval_zero(),
1298                         "account_lockout_policy_handler",
1299                         account_lockout_policy_handler,
1300                         child);
1301         }
1302
1303         if (child->domain && child->domain->primary &&
1304             !lp_use_kerberos_keytab() &&
1305             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1306
1307                 struct timeval next_change;
1308
1309                 if (calculate_next_machine_pwd_change(child->domain->name,
1310                                                        &next_change)) {
1311                         child->machine_password_change_event = event_add_timed(
1312                                 winbind_event_context(), NULL, next_change,
1313                                 "machine_password_change_handler",
1314                                 machine_password_change_handler,
1315                                 child);
1316                 }
1317         }
1318
1319         while (1) {
1320
1321                 int ret;
1322                 fd_set read_fds;
1323                 struct timeval t;
1324                 struct timeval *tp;
1325                 struct timeval now;
1326                 TALLOC_CTX *frame = talloc_stackframe();
1327
1328                 /* check for signals */
1329                 winbind_check_sigterm(false);
1330                 winbind_check_sighup(override_logfile ? NULL :
1331                                 child->logfilename);
1332
1333                 run_events(winbind_event_context(), 0, NULL, NULL);
1334
1335                 GetTimeOfDay(&now);
1336
1337                 if (child->domain && child->domain->startup &&
1338                                 (now.tv_sec > child->domain->startup_time + 30)) {
1339                         /* No longer in "startup" mode. */
1340                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1341                                 child->domain->name ));
1342                         child->domain->startup = False;
1343                 }
1344
1345                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1346                 if (tp) {
1347                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1348                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1349                 }
1350
1351                 /* Handle messages */
1352
1353                 message_dispatch(winbind_messaging_context());
1354
1355                 FD_ZERO(&read_fds);
1356                 FD_SET(state.sock, &read_fds);
1357
1358                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
1359
1360                 if (ret == 0) {
1361                         DEBUG(11,("nothing is ready yet, continue\n"));
1362                         TALLOC_FREE(frame);
1363                         continue;
1364                 }
1365
1366                 if (ret == -1 && errno == EINTR) {
1367                         /* We got a signal - continue. */
1368                         TALLOC_FREE(frame);
1369                         continue;
1370                 }
1371
1372                 if (ret == -1 && errno != EINTR) {
1373                         DEBUG(0,("select error occured\n"));
1374                         TALLOC_FREE(frame);
1375                         perror("select");
1376                         return False;
1377                 }
1378
1379                 /* fetch a request from the main daemon */
1380                 child_read_request(&state);
1381
1382                 if (state.finished) {
1383                         /* we lost contact with our parent */
1384                         exit(0);
1385                 }
1386
1387                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1388
1389                 ZERO_STRUCT(state.response);
1390                 state.request.null_term = '\0';
1391                 child_process_request(child, &state);
1392
1393                 SAFE_FREE(state.request.extra_data.data);
1394
1395                 cache_store_response(sys_getpid(), &state.response);
1396
1397                 SAFE_FREE(state.response.extra_data.data);
1398
1399                 /* We just send the result code back, the result
1400                  * structure needs to be fetched via the
1401                  * winbindd_cache. Hmm. That needs fixing... */
1402
1403                 if (write_data(state.sock,
1404                                (const char *)&state.response.result,
1405                                sizeof(state.response.result)) !=
1406                     sizeof(state.response.result)) {
1407                         DEBUG(0, ("Could not write result\n"));
1408                         exit(1);
1409                 }
1410                 TALLOC_FREE(frame);
1411         }
1412 }