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