s3-talloc Change TALLOC_ZERO_P() to talloc_zero()
[nivanova/samba-autobuild/.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 #include "nsswitch/wb_reqtrans.h"
33 #include "secrets.h"
34 #include "../lib/util/select.h"
35 #include "../libcli/security/security.h"
36 #include "system/select.h"
37 #include "messages.h"
38 #include "../lib/util/tevent_unix.h"
39
40 #undef DBGC_CLASS
41 #define DBGC_CLASS DBGC_WINBIND
42
43 extern bool override_logfile;
44 extern struct winbindd_methods cache_methods;
45
46 /* Read some data from a client connection */
47
48 static NTSTATUS child_read_request(struct winbindd_cli_state *state)
49 {
50         NTSTATUS status;
51
52         /* Read data */
53
54         status = read_data(state->sock, (char *)state->request,
55                            sizeof(*state->request));
56
57         if (!NT_STATUS_IS_OK(status)) {
58                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
59                           nt_errstr(status)));
60                 return status;
61         }
62
63         if (state->request->extra_len == 0) {
64                 state->request->extra_data.data = NULL;
65                 return NT_STATUS_OK;
66         }
67
68         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request->extra_len));
69
70         state->request->extra_data.data =
71                 SMB_MALLOC_ARRAY(char, state->request->extra_len + 1);
72
73         if (state->request->extra_data.data == NULL) {
74                 DEBUG(0, ("malloc failed\n"));
75                 return NT_STATUS_NO_MEMORY;
76         }
77
78         /* Ensure null termination */
79         state->request->extra_data.data[state->request->extra_len] = '\0';
80
81         status= read_data(state->sock, state->request->extra_data.data,
82                           state->request->extra_len);
83
84         if (!NT_STATUS_IS_OK(status)) {
85                 DEBUG(0, ("Could not read extra data: %s\n",
86                           nt_errstr(status)));
87         }
88         return status;
89 }
90
91 /*
92  * Do winbind child async request. This is not simply wb_simple_trans. We have
93  * to do the queueing ourselves because while a request is queued, the child
94  * might have crashed, and we have to re-fork it in the _trigger function.
95  */
96
97 struct wb_child_request_state {
98         struct tevent_context *ev;
99         struct winbindd_child *child;
100         struct winbindd_request *request;
101         struct winbindd_response *response;
102 };
103
104 static bool fork_domain_child(struct winbindd_child *child);
105
106 static void wb_child_request_trigger(struct tevent_req *req,
107                                             void *private_data);
108 static void wb_child_request_done(struct tevent_req *subreq);
109
110 struct tevent_req *wb_child_request_send(TALLOC_CTX *mem_ctx,
111                                          struct tevent_context *ev,
112                                          struct winbindd_child *child,
113                                          struct winbindd_request *request)
114 {
115         struct tevent_req *req;
116         struct wb_child_request_state *state;
117
118         req = tevent_req_create(mem_ctx, &state,
119                                 struct wb_child_request_state);
120         if (req == NULL) {
121                 return NULL;
122         }
123
124         state->ev = ev;
125         state->child = child;
126         state->request = request;
127
128         if (!tevent_queue_add(child->queue, ev, req,
129                               wb_child_request_trigger, NULL)) {
130                 tevent_req_nomem(NULL, req);
131                 return tevent_req_post(req, ev);
132         }
133         return req;
134 }
135
136 static void wb_child_request_trigger(struct tevent_req *req,
137                                      void *private_data)
138 {
139         struct wb_child_request_state *state = tevent_req_data(
140                 req, struct wb_child_request_state);
141         struct tevent_req *subreq;
142
143         if ((state->child->sock == -1) && (!fork_domain_child(state->child))) {
144                 tevent_req_error(req, errno);
145                 return;
146         }
147
148         subreq = wb_simple_trans_send(state, winbind_event_context(), NULL,
149                                       state->child->sock, state->request);
150         if (tevent_req_nomem(subreq, req)) {
151                 return;
152         }
153         tevent_req_set_callback(subreq, wb_child_request_done, req);
154         tevent_req_set_endtime(req, state->ev, timeval_current_ofs(300, 0));
155 }
156
157 static void wb_child_request_done(struct tevent_req *subreq)
158 {
159         struct tevent_req *req = tevent_req_callback_data(
160                 subreq, struct tevent_req);
161         struct wb_child_request_state *state = tevent_req_data(
162                 req, struct wb_child_request_state);
163         int ret, err;
164
165         ret = wb_simple_trans_recv(subreq, state, &state->response, &err);
166         TALLOC_FREE(subreq);
167         if (ret == -1) {
168                 /*
169                  * The basic parent/child communication broke, close
170                  * our socket
171                  */
172                 close(state->child->sock);
173                 state->child->sock = -1;
174                 tevent_req_error(req, err);
175                 return;
176         }
177         tevent_req_done(req);
178 }
179
180 int wb_child_request_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
181                           struct winbindd_response **presponse, int *err)
182 {
183         struct wb_child_request_state *state = tevent_req_data(
184                 req, struct wb_child_request_state);
185
186         if (tevent_req_is_unix_error(req, err)) {
187                 return -1;
188         }
189         *presponse = talloc_move(mem_ctx, &state->response);
190         return 0;
191 }
192
193 static bool winbindd_child_busy(struct winbindd_child *child)
194 {
195         return tevent_queue_length(child->queue) > 0;
196 }
197
198 static struct winbindd_child *find_idle_child(struct winbindd_domain *domain)
199 {
200         int i;
201
202         for (i=0; i<lp_winbind_max_domain_connections(); i++) {
203                 if (!winbindd_child_busy(&domain->children[i])) {
204                         return &domain->children[i];
205                 }
206         }
207
208         return NULL;
209 }
210
211 struct winbindd_child *choose_domain_child(struct winbindd_domain *domain)
212 {
213         struct winbindd_child *result;
214
215         result = find_idle_child(domain);
216         if (result != NULL) {
217                 return result;
218         }
219         return &domain->children[rand() % lp_winbind_max_domain_connections()];
220 }
221
222 struct dcerpc_binding_handle *dom_child_handle(struct winbindd_domain *domain)
223 {
224         struct winbindd_child *child;
225
226         child = choose_domain_child(domain);
227         return child->binding_handle;
228 }
229
230 struct wb_domain_request_state {
231         struct tevent_context *ev;
232         struct winbindd_domain *domain;
233         struct winbindd_child *child;
234         struct winbindd_request *request;
235         struct winbindd_request *init_req;
236         struct winbindd_response *response;
237 };
238
239 static void wb_domain_request_gotdc(struct tevent_req *subreq);
240 static void wb_domain_request_initialized(struct tevent_req *subreq);
241 static void wb_domain_request_done(struct tevent_req *subreq);
242
243 struct tevent_req *wb_domain_request_send(TALLOC_CTX *mem_ctx,
244                                           struct tevent_context *ev,
245                                           struct winbindd_domain *domain,
246                                           struct winbindd_request *request)
247 {
248         struct tevent_req *req, *subreq;
249         struct wb_domain_request_state *state;
250
251         req = tevent_req_create(mem_ctx, &state,
252                                 struct wb_domain_request_state);
253         if (req == NULL) {
254                 return NULL;
255         }
256
257         state->child = choose_domain_child(domain);
258
259         if (domain->initialized) {
260                 subreq = wb_child_request_send(state, ev, state->child,
261                                                request);
262                 if (tevent_req_nomem(subreq, req)) {
263                         return tevent_req_post(req, ev);
264                 }
265                 tevent_req_set_callback(subreq, wb_domain_request_done, req);
266                 return req;
267         }
268
269         state->domain = domain;
270         state->ev = ev;
271         state->request = request;
272
273         state->init_req = talloc_zero(state, struct winbindd_request);
274         if (tevent_req_nomem(state->init_req, req)) {
275                 return tevent_req_post(req, ev);
276         }
277
278         if (IS_DC || domain->primary || domain->internal) {
279                 /* The primary domain has to find the DC name itself */
280                 state->init_req->cmd = WINBINDD_INIT_CONNECTION;
281                 fstrcpy(state->init_req->domain_name, domain->name);
282                 state->init_req->data.init_conn.is_primary = domain->primary;
283                 fstrcpy(state->init_req->data.init_conn.dcname, "");
284
285                 subreq = wb_child_request_send(state, ev, state->child,
286                                                state->init_req);
287                 if (tevent_req_nomem(subreq, req)) {
288                         return tevent_req_post(req, ev);
289                 }
290                 tevent_req_set_callback(subreq, wb_domain_request_initialized,
291                                         req);
292                 return req;
293         }
294
295         /*
296          * Ask our DC for a DC name
297          */
298         domain = find_our_domain();
299
300         /* This is *not* the primary domain, let's ask our DC about a DC
301          * name */
302
303         state->init_req->cmd = WINBINDD_GETDCNAME;
304         fstrcpy(state->init_req->domain_name, domain->name);
305
306         subreq = wb_child_request_send(state, ev, state->child, request);
307         if (tevent_req_nomem(subreq, req)) {
308                 return tevent_req_post(req, ev);
309         }
310         tevent_req_set_callback(subreq, wb_domain_request_gotdc, req);
311         return req;
312 }
313
314 static void wb_domain_request_gotdc(struct tevent_req *subreq)
315 {
316         struct tevent_req *req = tevent_req_callback_data(
317                 subreq, struct tevent_req);
318         struct wb_domain_request_state *state = tevent_req_data(
319                 req, struct wb_domain_request_state);
320         struct winbindd_response *response;
321         int ret, err;
322
323         ret = wb_child_request_recv(subreq, talloc_tos(), &response, &err);
324         TALLOC_FREE(subreq);
325         if (ret == -1) {
326                 tevent_req_error(req, err);
327                 return;
328         }
329         state->init_req->cmd = WINBINDD_INIT_CONNECTION;
330         fstrcpy(state->init_req->domain_name, state->domain->name);
331         state->init_req->data.init_conn.is_primary = False;
332         fstrcpy(state->init_req->data.init_conn.dcname,
333                 response->data.dc_name);
334
335         TALLOC_FREE(response);
336
337         subreq = wb_child_request_send(state, state->ev, state->child,
338                                        state->init_req);
339         if (tevent_req_nomem(subreq, req)) {
340                 return;
341         }
342         tevent_req_set_callback(subreq, wb_domain_request_initialized, req);
343 }
344
345 static void wb_domain_request_initialized(struct tevent_req *subreq)
346 {
347         struct tevent_req *req = tevent_req_callback_data(
348                 subreq, struct tevent_req);
349         struct wb_domain_request_state *state = tevent_req_data(
350                 req, struct wb_domain_request_state);
351         struct winbindd_response *response;
352         int ret, err;
353
354         ret = wb_child_request_recv(subreq, talloc_tos(), &response, &err);
355         TALLOC_FREE(subreq);
356         if (ret == -1) {
357                 tevent_req_error(req, err);
358                 return;
359         }
360
361         if (!string_to_sid(&state->domain->sid,
362                            response->data.domain_info.sid)) {
363                 DEBUG(1,("init_child_recv: Could not convert sid %s "
364                         "from string\n", response->data.domain_info.sid));
365                 tevent_req_error(req, EINVAL);
366                 return;
367         }
368         fstrcpy(state->domain->name, response->data.domain_info.name);
369         fstrcpy(state->domain->alt_name, response->data.domain_info.alt_name);
370         state->domain->native_mode = response->data.domain_info.native_mode;
371         state->domain->active_directory =
372                 response->data.domain_info.active_directory;
373         state->domain->initialized = true;
374
375         TALLOC_FREE(response);
376
377         subreq = wb_child_request_send(state, state->ev, state->child,
378                                        state->request);
379         if (tevent_req_nomem(subreq, req)) {
380                 return;
381         }
382         tevent_req_set_callback(subreq, wb_domain_request_done, req);
383 }
384
385 static void wb_domain_request_done(struct tevent_req *subreq)
386 {
387         struct tevent_req *req = tevent_req_callback_data(
388                 subreq, struct tevent_req);
389         struct wb_domain_request_state *state = tevent_req_data(
390                 req, struct wb_domain_request_state);
391         int ret, err;
392
393         ret = wb_child_request_recv(subreq, talloc_tos(), &state->response,
394                                     &err);
395         TALLOC_FREE(subreq);
396         if (ret == -1) {
397                 tevent_req_error(req, err);
398                 return;
399         }
400         tevent_req_done(req);
401 }
402
403 int wb_domain_request_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
404                            struct winbindd_response **presponse, int *err)
405 {
406         struct wb_domain_request_state *state = tevent_req_data(
407                 req, struct wb_domain_request_state);
408
409         if (tevent_req_is_unix_error(req, err)) {
410                 return -1;
411         }
412         *presponse = talloc_move(mem_ctx, &state->response);
413         return 0;
414 }
415
416 static void child_process_request(struct winbindd_child *child,
417                                   struct winbindd_cli_state *state)
418 {
419         struct winbindd_domain *domain = child->domain;
420         const struct winbindd_child_dispatch_table *table = child->table;
421
422         /* Free response data - we may be interrupted and receive another
423            command before being able to send this data off. */
424
425         state->response->result = WINBINDD_ERROR;
426         state->response->length = sizeof(struct winbindd_response);
427
428         /* as all requests in the child are sync, we can use talloc_tos() */
429         state->mem_ctx = talloc_tos();
430
431         /* Process command */
432
433         for (; table->name; table++) {
434                 if (state->request->cmd == table->struct_cmd) {
435                         DEBUG(10,("child_process_request: request fn %s\n",
436                                   table->name));
437                         state->response->result = table->struct_fn(domain, state);
438                         return;
439                 }
440         }
441
442         DEBUG(1, ("child_process_request: unknown request fn number %d\n",
443                   (int)state->request->cmd));
444         state->response->result = WINBINDD_ERROR;
445 }
446
447 void setup_child(struct winbindd_domain *domain, struct winbindd_child *child,
448                  const struct winbindd_child_dispatch_table *table,
449                  const char *logprefix,
450                  const char *logname)
451 {
452         if (logprefix && logname) {
453                 char *logbase = NULL;
454
455                 if (*lp_logfile()) {
456                         char *end = NULL;
457
458                         if (asprintf(&logbase, "%s", lp_logfile()) < 0) {
459                                 smb_panic("Internal error: asprintf failed");
460                         }
461
462                         if ((end = strrchr_m(logbase, '/'))) {
463                                 *end = '\0';
464                         }
465                 } else {
466                         if (asprintf(&logbase, "%s", get_dyn_LOGFILEBASE()) < 0) {
467                                 smb_panic("Internal error: asprintf failed");
468                         }
469                 }
470
471                 if (asprintf(&child->logfilename, "%s/%s-%s",
472                              logbase, logprefix, logname) < 0) {
473                         SAFE_FREE(logbase);
474                         smb_panic("Internal error: asprintf failed");
475                 }
476
477                 SAFE_FREE(logbase);
478         } else {
479                 smb_panic("Internal error: logprefix == NULL && "
480                           "logname == NULL");
481         }
482
483         child->sock = -1;
484         child->domain = domain;
485         child->table = table;
486         child->queue = tevent_queue_create(NULL, "winbind_child");
487         SMB_ASSERT(child->queue != NULL);
488         child->binding_handle = wbint_binding_handle(NULL, domain, child);
489         SMB_ASSERT(child->binding_handle != NULL);
490 }
491
492 static struct winbindd_child *winbindd_children = NULL;
493
494 void winbind_child_died(pid_t pid)
495 {
496         struct winbindd_child *child;
497
498         for (child = winbindd_children; child != NULL; child = child->next) {
499                 if (child->pid == pid) {
500                         break;
501                 }
502         }
503
504         if (child == NULL) {
505                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
506                 return;
507         }
508
509         /* This will be re-added in fork_domain_child() */
510
511         DLIST_REMOVE(winbindd_children, child);
512         child->pid = 0;
513
514         if (child->sock != -1) {
515                 close(child->sock);
516                 child->sock = -1;
517         }
518 }
519
520 /* Ensure any negative cache entries with the netbios or realm names are removed. */
521
522 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
523 {
524         flush_negative_conn_cache_for_domain(domain->name);
525         if (*domain->alt_name) {
526                 flush_negative_conn_cache_for_domain(domain->alt_name);
527         }
528 }
529
530 /* 
531  * Parent winbindd process sets its own debug level first and then
532  * sends a message to all the winbindd children to adjust their debug
533  * level to that of parents.
534  */
535
536 void winbind_msg_debug(struct messaging_context *msg_ctx,
537                          void *private_data,
538                          uint32_t msg_type,
539                          struct server_id server_id,
540                          DATA_BLOB *data)
541 {
542         struct winbindd_child *child;
543
544         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
545
546         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
547
548         for (child = winbindd_children; child != NULL; child = child->next) {
549
550                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
551                         (unsigned int)child->pid));
552
553                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
554                            MSG_DEBUG,
555                            data->data,
556                            strlen((char *) data->data) + 1);
557         }
558 }
559
560 /* Set our domains as offline and forward the offline message to our children. */
561
562 void winbind_msg_offline(struct messaging_context *msg_ctx,
563                          void *private_data,
564                          uint32_t msg_type,
565                          struct server_id server_id,
566                          DATA_BLOB *data)
567 {
568         struct winbindd_child *child;
569         struct winbindd_domain *domain;
570
571         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
572
573         if (!lp_winbind_offline_logon()) {
574                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
575                 return;
576         }
577
578         /* Set our global state as offline. */
579         if (!set_global_winbindd_state_offline()) {
580                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
581                 return;
582         }
583
584         /* Set all our domains as offline. */
585         for (domain = domain_list(); domain; domain = domain->next) {
586                 if (domain->internal) {
587                         continue;
588                 }
589                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
590                 set_domain_offline(domain);
591         }
592
593         for (child = winbindd_children; child != NULL; child = child->next) {
594                 /* Don't send message to internal children.  We've already
595                    done so above. */
596                 if (!child->domain || winbindd_internal_child(child)) {
597                         continue;
598                 }
599
600                 /* Or internal domains (this should not be possible....) */
601                 if (child->domain->internal) {
602                         continue;
603                 }
604
605                 /* Each winbindd child should only process requests for one domain - make sure
606                    we only set it online / offline for that domain. */
607
608                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
609                         (unsigned int)child->pid, domain->name ));
610
611                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
612                                    MSG_WINBIND_OFFLINE,
613                                    (uint8 *)child->domain->name,
614                                    strlen(child->domain->name)+1);
615         }
616 }
617
618 /* Set our domains as online and forward the online message to our children. */
619
620 void winbind_msg_online(struct messaging_context *msg_ctx,
621                         void *private_data,
622                         uint32_t msg_type,
623                         struct server_id server_id,
624                         DATA_BLOB *data)
625 {
626         struct winbindd_child *child;
627         struct winbindd_domain *domain;
628
629         DEBUG(10,("winbind_msg_online: got online message.\n"));
630
631         if (!lp_winbind_offline_logon()) {
632                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
633                 return;
634         }
635
636         /* Set our global state as online. */
637         set_global_winbindd_state_online();
638
639         smb_nscd_flush_user_cache();
640         smb_nscd_flush_group_cache();
641
642         /* Set all our domains as online. */
643         for (domain = domain_list(); domain; domain = domain->next) {
644                 if (domain->internal) {
645                         continue;
646                 }
647                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
648
649                 winbindd_flush_negative_conn_cache(domain);
650                 set_domain_online_request(domain);
651
652                 /* Send an online message to the idmap child when our
653                    primary domain comes back online */
654
655                 if ( domain->primary ) {
656                         struct winbindd_child *idmap = idmap_child();
657
658                         if ( idmap->pid != 0 ) {
659                                 messaging_send_buf(msg_ctx,
660                                                    pid_to_procid(idmap->pid), 
661                                                    MSG_WINBIND_ONLINE,
662                                                    (uint8 *)domain->name,
663                                                    strlen(domain->name)+1);
664                         }
665                 }
666         }
667
668         for (child = winbindd_children; child != NULL; child = child->next) {
669                 /* Don't send message to internal childs. */
670                 if (!child->domain || winbindd_internal_child(child)) {
671                         continue;
672                 }
673
674                 /* Or internal domains (this should not be possible....) */
675                 if (child->domain->internal) {
676                         continue;
677                 }
678
679                 /* Each winbindd child should only process requests for one domain - make sure
680                    we only set it online / offline for that domain. */
681
682                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
683                         (unsigned int)child->pid, child->domain->name ));
684
685                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
686                                    MSG_WINBIND_ONLINE,
687                                    (uint8 *)child->domain->name,
688                                    strlen(child->domain->name)+1);
689         }
690 }
691
692 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
693 {
694         struct winbindd_domain *domain;
695         char *buf = NULL;
696
697         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
698                                    get_global_winbindd_state_offline() ? 
699                                    "Offline":"Online")) == NULL) {
700                 return NULL;
701         }
702
703         for (domain = domain_list(); domain; domain = domain->next) {
704                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
705                                                   domain->name, 
706                                                   domain->online ?
707                                                   "Online":"Offline")) == NULL) {
708                         return NULL;
709                 }
710         }
711
712         buf = talloc_asprintf_append_buffer(buf, "\n");
713
714         DEBUG(5,("collect_onlinestatus: %s", buf));
715
716         return buf;
717 }
718
719 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
720                               void *private_data,
721                               uint32_t msg_type,
722                               struct server_id server_id,
723                               DATA_BLOB *data)
724 {
725         TALLOC_CTX *mem_ctx;
726         const char *message;
727         struct server_id *sender;
728
729         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
730
731         if (!data->data) {
732                 return;
733         }
734
735         sender = (struct server_id *)data->data;
736
737         mem_ctx = talloc_init("winbind_msg_onlinestatus");
738         if (mem_ctx == NULL) {
739                 return;
740         }
741
742         message = collect_onlinestatus(mem_ctx);
743         if (message == NULL) {
744                 talloc_destroy(mem_ctx);
745                 return;
746         }
747
748         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
749                            (const uint8 *)message, strlen(message) + 1);
750
751         talloc_destroy(mem_ctx);
752 }
753
754 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
755                                  void *private_data,
756                                  uint32_t msg_type,
757                                  struct server_id server_id,
758                                  DATA_BLOB *data)
759 {
760         struct winbindd_child *child;
761
762         DEBUG(10,("winbind_msg_dump_event_list received\n"));
763
764         dump_event_list(winbind_event_context());
765
766         for (child = winbindd_children; child != NULL; child = child->next) {
767
768                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
769                         (unsigned int)child->pid));
770
771                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
772                                    MSG_DUMP_EVENT_LIST,
773                                    NULL, 0);
774         }
775
776 }
777
778 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
779                                   void *private_data,
780                                   uint32_t msg_type,
781                                   struct server_id server_id,
782                                   DATA_BLOB *data)
783 {
784         TALLOC_CTX *mem_ctx;
785         const char *message = NULL;
786         struct server_id *sender = NULL;
787         const char *domain = NULL;
788         char *s = NULL;
789         NTSTATUS status;
790         struct winbindd_domain *dom = NULL;
791
792         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
793
794         if (!data || !data->data) {
795                 return;
796         }
797
798         if (data->length < sizeof(struct server_id)) {
799                 return;
800         }
801
802         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
803         if (!mem_ctx) {
804                 return;
805         }
806
807         sender = (struct server_id *)data->data;
808         if (data->length > sizeof(struct server_id)) {
809                 domain = (const char *)data->data+sizeof(struct server_id);
810         }
811
812         if (domain) {
813
814                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
815                         domain));
816
817                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
818                                                   find_domain_from_name_noinit(domain));
819                 if (!message) {
820                         talloc_destroy(mem_ctx);
821                         return;
822                 }
823
824                 messaging_send_buf(msg_ctx, *sender,
825                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
826                                    (const uint8_t *)message, strlen(message) + 1);
827
828                 talloc_destroy(mem_ctx);
829
830                 return;
831         }
832
833         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
834
835         for (dom = domain_list(); dom; dom=dom->next) {
836                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
837                 if (!message) {
838                         talloc_destroy(mem_ctx);
839                         return;
840                 }
841
842                 s = talloc_asprintf_append(s, "%s\n", message);
843                 if (!s) {
844                         talloc_destroy(mem_ctx);
845                         return;
846                 }
847         }
848
849         status = messaging_send_buf(msg_ctx, *sender,
850                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
851                                     (uint8_t *)s, strlen(s) + 1);
852         if (!NT_STATUS_IS_OK(status)) {
853                 DEBUG(0,("failed to send message: %s\n",
854                 nt_errstr(status)));
855         }
856
857         talloc_destroy(mem_ctx);
858 }
859
860 static void account_lockout_policy_handler(struct event_context *ctx,
861                                            struct timed_event *te,
862                                            struct timeval now,
863                                            void *private_data)
864 {
865         struct winbindd_child *child =
866                 (struct winbindd_child *)private_data;
867         TALLOC_CTX *mem_ctx = NULL;
868         struct winbindd_methods *methods;
869         struct samr_DomInfo12 lockout_policy;
870         NTSTATUS result;
871
872         DEBUG(10,("account_lockout_policy_handler called\n"));
873
874         TALLOC_FREE(child->lockout_policy_event);
875
876         if ( !winbindd_can_contact_domain( child->domain ) ) {
877                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
878                           "do not have an incoming trust to domain %s\n", 
879                           child->domain->name));
880
881                 return;         
882         }
883
884         methods = child->domain->methods;
885
886         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
887         if (!mem_ctx) {
888                 result = NT_STATUS_NO_MEMORY;
889         } else {
890                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
891         }
892         TALLOC_FREE(mem_ctx);
893
894         if (!NT_STATUS_IS_OK(result)) {
895                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
896                          nt_errstr(result)));
897         }
898
899         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
900                                                       timeval_current_ofs(3600, 0),
901                                                       account_lockout_policy_handler,
902                                                       child);
903 }
904
905 static time_t get_machine_password_timeout(void)
906 {
907         /* until we have gpo support use lp setting */
908         return lp_machine_password_timeout();
909 }
910
911 static bool calculate_next_machine_pwd_change(const char *domain,
912                                               struct timeval *t)
913 {
914         time_t pass_last_set_time;
915         time_t timeout;
916         time_t next_change;
917         struct timeval tv;
918         char *pw;
919
920         pw = secrets_fetch_machine_password(domain,
921                                             &pass_last_set_time,
922                                             NULL);
923
924         if (pw == NULL) {
925                 DEBUG(0,("cannot fetch own machine password ????"));
926                 return false;
927         }
928
929         SAFE_FREE(pw);
930
931         timeout = get_machine_password_timeout();
932         if (timeout == 0) {
933                 DEBUG(10,("machine password never expires\n"));
934                 return false;
935         }
936
937         tv.tv_sec = pass_last_set_time;
938         DEBUG(10, ("password last changed %s\n",
939                    timeval_string(talloc_tos(), &tv, false)));
940         tv.tv_sec += timeout;
941         DEBUGADD(10, ("password valid until %s\n",
942                       timeval_string(talloc_tos(), &tv, false)));
943
944         if (time(NULL) < (pass_last_set_time + timeout)) {
945                 next_change = pass_last_set_time + timeout;
946                 DEBUG(10,("machine password still valid until: %s\n",
947                         http_timestring(talloc_tos(), next_change)));
948                 *t = timeval_set(next_change, 0);
949
950                 if (lp_clustering()) {
951                         uint8_t randbuf;
952                         /*
953                          * When having a cluster, we have several
954                          * winbinds racing for the password change. In
955                          * the machine_password_change_handler()
956                          * function we check if someone else was
957                          * faster when the event triggers. We add a
958                          * 255-second random delay here, so that we
959                          * don't run to change the password at the
960                          * exact same moment.
961                          */
962                         generate_random_buffer(&randbuf, sizeof(randbuf));
963                         DEBUG(10, ("adding %d seconds randomness\n",
964                                    (int)randbuf));
965                         t->tv_sec += randbuf;
966                 }
967                 return true;
968         }
969
970         DEBUG(10,("machine password expired, needs immediate change\n"));
971
972         *t = timeval_zero();
973
974         return true;
975 }
976
977 static void machine_password_change_handler(struct event_context *ctx,
978                                             struct timed_event *te,
979                                             struct timeval now,
980                                             void *private_data)
981 {
982         struct winbindd_child *child =
983                 (struct winbindd_child *)private_data;
984         struct rpc_pipe_client *netlogon_pipe = NULL;
985         TALLOC_CTX *frame;
986         NTSTATUS result;
987         struct timeval next_change;
988
989         DEBUG(10,("machine_password_change_handler called\n"));
990
991         TALLOC_FREE(child->machine_password_change_event);
992
993         if (!calculate_next_machine_pwd_change(child->domain->name,
994                                                &next_change)) {
995                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
996                 return;
997         }
998
999         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1000                    timeval_string(talloc_tos(), &next_change, false)));
1001
1002         if (!timeval_expired(&next_change)) {
1003                 DEBUG(10, ("Someone else has already changed the pw\n"));
1004                 goto done;
1005         }
1006
1007         if (!winbindd_can_contact_domain(child->domain)) {
1008                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
1009                           "do not have an incoming trust to domain %s\n",
1010                           child->domain->name));
1011                 return;
1012         }
1013
1014         result = cm_connect_netlogon(child->domain, &netlogon_pipe);
1015         if (!NT_STATUS_IS_OK(result)) {
1016                 DEBUG(10,("machine_password_change_handler: "
1017                         "failed to connect netlogon pipe: %s\n",
1018                          nt_errstr(result)));
1019                 return;
1020         }
1021
1022         frame = talloc_stackframe();
1023
1024         result = trust_pw_find_change_and_store_it(netlogon_pipe,
1025                                                    frame,
1026                                                    child->domain->name);
1027         TALLOC_FREE(frame);
1028
1029         DEBUG(10, ("machine_password_change_handler: "
1030                    "trust_pw_find_change_and_store_it returned %s\n",
1031                    nt_errstr(result)));
1032
1033         if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1034                 DEBUG(3,("machine_password_change_handler: password set returned "
1035                          "ACCESS_DENIED.  Maybe the trust account "
1036                          "password was changed and we didn't know it. "
1037                          "Killing connections to domain %s\n",
1038                          child->domain->name));
1039                 TALLOC_FREE(child->domain->conn.netlogon_pipe);
1040         }
1041
1042         if (!calculate_next_machine_pwd_change(child->domain->name,
1043                                                &next_change)) {
1044                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1045                 return;
1046         }
1047
1048         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1049                    timeval_string(talloc_tos(), &next_change, false)));
1050
1051         if (!NT_STATUS_IS_OK(result)) {
1052                 struct timeval tmp;
1053                 /*
1054                  * In case of failure, give the DC a minute to recover
1055                  */
1056                 tmp = timeval_current_ofs(60, 0);
1057                 next_change = timeval_max(&next_change, &tmp);
1058         }
1059
1060 done:
1061         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
1062                                                               next_change,
1063                                                               machine_password_change_handler,
1064                                                               child);
1065 }
1066
1067 /* Deal with a request to go offline. */
1068
1069 static void child_msg_offline(struct messaging_context *msg,
1070                               void *private_data,
1071                               uint32_t msg_type,
1072                               struct server_id server_id,
1073                               DATA_BLOB *data)
1074 {
1075         struct winbindd_domain *domain;
1076         struct winbindd_domain *primary_domain = NULL;
1077         const char *domainname = (const char *)data->data;
1078
1079         if (data->data == NULL || data->length == 0) {
1080                 return;
1081         }
1082
1083         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
1084
1085         if (!lp_winbind_offline_logon()) {
1086                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
1087                 return;
1088         }
1089
1090         primary_domain = find_our_domain();
1091
1092         /* Mark the requested domain offline. */
1093
1094         for (domain = domain_list(); domain; domain = domain->next) {
1095                 if (domain->internal) {
1096                         continue;
1097                 }
1098                 if (strequal(domain->name, domainname)) {
1099                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1100                         set_domain_offline(domain);
1101                         /* we are in the trusted domain, set the primary domain 
1102                          * offline too */
1103                         if (domain != primary_domain) {
1104                                 set_domain_offline(primary_domain);
1105                         }
1106                 }
1107         }
1108 }
1109
1110 /* Deal with a request to go online. */
1111
1112 static void child_msg_online(struct messaging_context *msg,
1113                              void *private_data,
1114                              uint32_t msg_type,
1115                              struct server_id server_id,
1116                              DATA_BLOB *data)
1117 {
1118         struct winbindd_domain *domain;
1119         struct winbindd_domain *primary_domain = NULL;
1120         const char *domainname = (const char *)data->data;
1121
1122         if (data->data == NULL || data->length == 0) {
1123                 return;
1124         }
1125
1126         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1127
1128         if (!lp_winbind_offline_logon()) {
1129                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1130                 return;
1131         }
1132
1133         primary_domain = find_our_domain();
1134
1135         /* Set our global state as online. */
1136         set_global_winbindd_state_online();
1137
1138         /* Try and mark everything online - delete any negative cache entries
1139            to force a reconnect now. */
1140
1141         for (domain = domain_list(); domain; domain = domain->next) {
1142                 if (domain->internal) {
1143                         continue;
1144                 }
1145                 if (strequal(domain->name, domainname)) {
1146                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1147                         winbindd_flush_negative_conn_cache(domain);
1148                         set_domain_online_request(domain);
1149
1150                         /* we can be in trusted domain, which will contact primary domain
1151                          * we have to bring primary domain online in trusted domain process
1152                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1153                          * --> contact_domain = find_our_domain()
1154                          * */
1155                         if (domain != primary_domain) {
1156                                 winbindd_flush_negative_conn_cache(primary_domain);
1157                                 set_domain_online_request(primary_domain);
1158                         }
1159                 }
1160         }
1161 }
1162
1163 static void child_msg_dump_event_list(struct messaging_context *msg,
1164                                       void *private_data,
1165                                       uint32_t msg_type,
1166                                       struct server_id server_id,
1167                                       DATA_BLOB *data)
1168 {
1169         DEBUG(5,("child_msg_dump_event_list received\n"));
1170
1171         dump_event_list(winbind_event_context());
1172 }
1173
1174 NTSTATUS winbindd_reinit_after_fork(const struct winbindd_child *myself,
1175                                     const char *logfilename)
1176 {
1177         struct winbindd_domain *domain;
1178         struct winbindd_child *cl;
1179         NTSTATUS status;
1180
1181         status = reinit_after_fork(
1182                 winbind_messaging_context(),
1183                 winbind_event_context(),
1184                 procid_self(),
1185                 true);
1186         if (!NT_STATUS_IS_OK(status)) {
1187                 DEBUG(0,("reinit_after_fork() failed\n"));
1188                 return status;
1189         }
1190
1191         close_conns_after_fork();
1192
1193         if (!override_logfile && logfilename) {
1194                 lp_set_logfile(logfilename);
1195                 reopen_logs();
1196         }
1197
1198         if (!winbindd_setup_sig_term_handler(false))
1199                 return NT_STATUS_NO_MEMORY;
1200         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1201                                             logfilename))
1202                 return NT_STATUS_NO_MEMORY;
1203
1204         /* Stop zombies in children */
1205         CatchChild();
1206
1207         /* Don't handle the same messages as our parent. */
1208         messaging_deregister(winbind_messaging_context(),
1209                              MSG_SMB_CONF_UPDATED, NULL);
1210         messaging_deregister(winbind_messaging_context(),
1211                              MSG_SHUTDOWN, NULL);
1212         messaging_deregister(winbind_messaging_context(),
1213                              MSG_WINBIND_OFFLINE, NULL);
1214         messaging_deregister(winbind_messaging_context(),
1215                              MSG_WINBIND_ONLINE, NULL);
1216         messaging_deregister(winbind_messaging_context(),
1217                              MSG_WINBIND_ONLINESTATUS, NULL);
1218         messaging_deregister(winbind_messaging_context(),
1219                              MSG_DUMP_EVENT_LIST, NULL);
1220         messaging_deregister(winbind_messaging_context(),
1221                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1222         messaging_deregister(winbind_messaging_context(),
1223                              MSG_DEBUG, NULL);
1224
1225         /* We have destroyed all events in the winbindd_event_context
1226          * in reinit_after_fork(), so clean out all possible pending
1227          * event pointers. */
1228
1229         /* Deal with check_online_events. */
1230
1231         for (domain = domain_list(); domain; domain = domain->next) {
1232                 TALLOC_FREE(domain->check_online_event);
1233         }
1234
1235         /* Ensure we're not handling a credential cache event inherited
1236          * from our parent. */
1237
1238         ccache_remove_all_after_fork();
1239
1240         /* Destroy all possible events in child list. */
1241         for (cl = winbindd_children; cl != NULL; cl = cl->next) {
1242                 TALLOC_FREE(cl->lockout_policy_event);
1243                 TALLOC_FREE(cl->machine_password_change_event);
1244
1245                 /* Children should never be able to send
1246                  * each other messages, all messages must
1247                  * go through the parent.
1248                  */
1249                 cl->pid = (pid_t)0;
1250
1251                 /*
1252                  * Close service sockets to all other children
1253                  */
1254                 if ((cl != myself) && (cl->sock != -1)) {
1255                         close(cl->sock);
1256                         cl->sock = -1;
1257                 }
1258         }
1259         /*
1260          * This is a little tricky, children must not
1261          * send an MSG_WINBIND_ONLINE message to idmap_child().
1262          * If we are in a child of our primary domain or
1263          * in the process created by fork_child_dc_connect(),
1264          * and the primary domain cannot go online,
1265          * fork_child_dc_connection() sends MSG_WINBIND_ONLINE
1266          * periodically to idmap_child().
1267          *
1268          * The sequence is, fork_child_dc_connect() ---> getdcs() --->
1269          * get_dc_name_via_netlogon() ---> cm_connect_netlogon()
1270          * ---> init_dc_connection() ---> cm_open_connection --->
1271          * set_domain_online(), sends MSG_WINBIND_ONLINE to
1272          * idmap_child(). Disallow children sending messages
1273          * to each other, all messages must go through the parent.
1274          */
1275         cl = idmap_child();
1276         cl->pid = (pid_t)0;
1277
1278         return NT_STATUS_OK;
1279 }
1280
1281 /*
1282  * In a child there will be only one domain, reference that here.
1283  */
1284 static struct winbindd_domain *child_domain;
1285
1286 struct winbindd_domain *wb_child_domain(void)
1287 {
1288         return child_domain;
1289 }
1290
1291 static bool fork_domain_child(struct winbindd_child *child)
1292 {
1293         int fdpair[2];
1294         struct winbindd_cli_state state;
1295         struct winbindd_request request;
1296         struct winbindd_response response;
1297         struct winbindd_domain *primary_domain = NULL;
1298         NTSTATUS status;
1299         ssize_t nwritten;
1300
1301         if (child->domain) {
1302                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1303                            child->domain->name));
1304         } else {
1305                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1306         }
1307
1308         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1309                 DEBUG(0, ("Could not open child pipe: %s\n",
1310                           strerror(errno)));
1311                 return False;
1312         }
1313
1314         ZERO_STRUCT(state);
1315         state.pid = sys_getpid();
1316         state.request = &request;
1317         state.response = &response;
1318
1319         child->pid = sys_fork();
1320
1321         if (child->pid == -1) {
1322                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1323                 return False;
1324         }
1325
1326         if (child->pid != 0) {
1327                 /* Parent */
1328                 ssize_t nread;
1329
1330                 close(fdpair[0]);
1331
1332                 nread = read(fdpair[1], &status, sizeof(status));
1333                 if (nread != sizeof(status)) {
1334                         DEBUG(1, ("fork_domain_child: Could not read child status: "
1335                                   "nread=%d, error=%s\n", (int)nread,
1336                                   strerror(errno)));
1337                         close(fdpair[1]);
1338                         return false;
1339                 }
1340                 if (!NT_STATUS_IS_OK(status)) {
1341                         DEBUG(1, ("fork_domain_child: Child status is %s\n",
1342                                   nt_errstr(status)));
1343                         close(fdpair[1]);
1344                         return false;
1345                 }
1346
1347                 child->next = child->prev = NULL;
1348                 DLIST_ADD(winbindd_children, child);
1349                 child->sock = fdpair[1];
1350                 return True;
1351         }
1352
1353         /* Child */
1354         child_domain = child->domain;
1355
1356         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1357
1358         state.sock = fdpair[0];
1359         close(fdpair[1]);
1360
1361         status = winbindd_reinit_after_fork(child, child->logfilename);
1362
1363         nwritten = write(state.sock, &status, sizeof(status));
1364         if (nwritten != sizeof(status)) {
1365                 DEBUG(1, ("fork_domain_child: Could not write status: "
1366                           "nwritten=%d, error=%s\n", (int)nwritten,
1367                           strerror(errno)));
1368                 _exit(0);
1369         }
1370         if (!NT_STATUS_IS_OK(status)) {
1371                 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
1372                           nt_errstr(status)));
1373                 _exit(0);
1374         }
1375
1376         /* Handle online/offline messages. */
1377         messaging_register(winbind_messaging_context(), NULL,
1378                            MSG_WINBIND_OFFLINE, child_msg_offline);
1379         messaging_register(winbind_messaging_context(), NULL,
1380                            MSG_WINBIND_ONLINE, child_msg_online);
1381         messaging_register(winbind_messaging_context(), NULL,
1382                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1383         messaging_register(winbind_messaging_context(), NULL,
1384                            MSG_DEBUG, debug_message);
1385         messaging_register(winbind_messaging_context(), NULL,
1386                            MSG_WINBIND_IP_DROPPED,
1387                            winbind_msg_ip_dropped);
1388
1389
1390         primary_domain = find_our_domain();
1391
1392         if (primary_domain == NULL) {
1393                 smb_panic("no primary domain found");
1394         }
1395
1396         /* It doesn't matter if we allow cache login,
1397          * try to bring domain online after fork. */
1398         if ( child->domain ) {
1399                 child->domain->startup = True;
1400                 child->domain->startup_time = time_mono(NULL);
1401                 /* we can be in primary domain or in trusted domain
1402                  * If we are in trusted domain, set the primary domain
1403                  * in start-up mode */
1404                 if (!(child->domain->internal)) {
1405                         set_domain_online_request(child->domain);
1406                         if (!(child->domain->primary)) {
1407                                 primary_domain->startup = True;
1408                                 primary_domain->startup_time = time_mono(NULL);
1409                                 set_domain_online_request(primary_domain);
1410                         }
1411                 }
1412         }
1413
1414         /*
1415          * We are in idmap child, make sure that we set the
1416          * check_online_event to bring primary domain online.
1417          */
1418         if (child == idmap_child()) {
1419                 set_domain_online_request(primary_domain);
1420         }
1421
1422         /* We might be in the idmap child...*/
1423         if (child->domain && !(child->domain->internal) &&
1424             lp_winbind_offline_logon()) {
1425
1426                 set_domain_online_request(child->domain);
1427
1428                 if (primary_domain && (primary_domain != child->domain)) {
1429                         /* We need to talk to the primary
1430                          * domain as well as the trusted
1431                          * domain inside a trusted domain
1432                          * child.
1433                          * See the code in :
1434                          * set_dc_type_and_flags_trustinfo()
1435                          * for details.
1436                          */
1437                         set_domain_online_request(primary_domain);
1438                 }
1439
1440                 child->lockout_policy_event = event_add_timed(
1441                         winbind_event_context(), NULL, timeval_zero(),
1442                         account_lockout_policy_handler,
1443                         child);
1444         }
1445
1446         if (child->domain && child->domain->primary &&
1447             !USE_KERBEROS_KEYTAB &&
1448             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1449
1450                 struct timeval next_change;
1451
1452                 if (calculate_next_machine_pwd_change(child->domain->name,
1453                                                        &next_change)) {
1454                         child->machine_password_change_event = event_add_timed(
1455                                 winbind_event_context(), NULL, next_change,
1456                                 machine_password_change_handler,
1457                                 child);
1458                 }
1459         }
1460
1461         while (1) {
1462
1463                 int ret;
1464                 struct pollfd *pfds;
1465                 int num_pfds;
1466                 int timeout;
1467                 struct timeval t;
1468                 struct timeval *tp;
1469                 TALLOC_CTX *frame = talloc_stackframe();
1470                 struct iovec iov[2];
1471                 int iov_count;
1472
1473                 if (run_events_poll(winbind_event_context(), 0, NULL, 0)) {
1474                         TALLOC_FREE(frame);
1475                         continue;
1476                 }
1477
1478                 if (child->domain && child->domain->startup &&
1479                                 (time_mono(NULL) > child->domain->startup_time + 30)) {
1480                         /* No longer in "startup" mode. */
1481                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1482                                 child->domain->name ));
1483                         child->domain->startup = False;
1484                 }
1485
1486                 pfds = talloc_zero(talloc_tos(), struct pollfd);
1487                 if (pfds == NULL) {
1488                         DEBUG(1, ("talloc failed\n"));
1489                         _exit(1);
1490                 }
1491
1492                 pfds->fd = state.sock;
1493                 pfds->events = POLLIN|POLLHUP;
1494                 num_pfds = 1;
1495
1496                 timeout = INT_MAX;
1497
1498                 if (!event_add_to_poll_args(
1499                             winbind_event_context(), talloc_tos(),
1500                             &pfds, &num_pfds, &timeout)) {
1501                         DEBUG(1, ("event_add_to_poll_args failed\n"));
1502                         _exit(1);
1503                 }
1504                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1505                 if (tp) {
1506                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1507                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1508                 }
1509
1510                 ret = sys_poll(pfds, num_pfds, timeout);
1511
1512                 if (run_events_poll(winbind_event_context(), ret,
1513                                     pfds, num_pfds)) {
1514                         /* We got a signal - continue. */
1515                         TALLOC_FREE(frame);
1516                         continue;
1517                 }
1518
1519                 TALLOC_FREE(pfds);
1520
1521                 if (ret == 0) {
1522                         DEBUG(11,("nothing is ready yet, continue\n"));
1523                         TALLOC_FREE(frame);
1524                         continue;
1525                 }
1526
1527                 if (ret == -1 && errno == EINTR) {
1528                         /* We got a signal - continue. */
1529                         TALLOC_FREE(frame);
1530                         continue;
1531                 }
1532
1533                 if (ret == -1 && errno != EINTR) {
1534                         DEBUG(0,("poll error occured\n"));
1535                         TALLOC_FREE(frame);
1536                         perror("poll");
1537                         _exit(1);
1538                 }
1539
1540                 /* fetch a request from the main daemon */
1541                 status = child_read_request(&state);
1542
1543                 if (!NT_STATUS_IS_OK(status)) {
1544                         /* we lost contact with our parent */
1545                         _exit(0);
1546                 }
1547
1548                 DEBUG(4,("child daemon request %d\n", (int)state.request->cmd));
1549
1550                 ZERO_STRUCTP(state.response);
1551                 state.request->null_term = '\0';
1552                 state.mem_ctx = frame;
1553                 child_process_request(child, &state);
1554
1555                 DEBUG(4, ("Finished processing child request %d\n",
1556                           (int)state.request->cmd));
1557
1558                 SAFE_FREE(state.request->extra_data.data);
1559
1560                 iov[0].iov_base = (void *)state.response;
1561                 iov[0].iov_len = sizeof(struct winbindd_response);
1562                 iov_count = 1;
1563
1564                 if (state.response->length > sizeof(struct winbindd_response)) {
1565                         iov[1].iov_base =
1566                                 (void *)state.response->extra_data.data;
1567                         iov[1].iov_len = state.response->length-iov[0].iov_len;
1568                         iov_count = 2;
1569                 }
1570
1571                 DEBUG(10, ("Writing %d bytes to parent\n",
1572                            (int)state.response->length));
1573
1574                 if (write_data_iov(state.sock, iov, iov_count) !=
1575                     state.response->length) {
1576                         DEBUG(0, ("Could not write result\n"));
1577                         exit(1);
1578                 }
1579                 TALLOC_FREE(frame);
1580         }
1581 }
1582
1583 void winbind_msg_ip_dropped_parent(struct messaging_context *msg_ctx,
1584                                    void *private_data,
1585                                    uint32_t msg_type,
1586                                    struct server_id server_id,
1587                                    DATA_BLOB *data)
1588 {
1589         struct winbindd_child *child;
1590
1591         winbind_msg_ip_dropped(msg_ctx, private_data, msg_type,
1592                                server_id, data);
1593
1594
1595         for (child = winbindd_children; child != NULL; child = child->next) {
1596                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
1597                                    msg_type, data->data, data->length);
1598         }
1599 }