s3-includes: only include ntdomain.h where needed.
[kai/samba.git] / source3 / winbindd / winbindd_dual.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind child daemons
5
6    Copyright (C) Andrew Tridgell 2002
7    Copyright (C) Volker Lendecke 2004,2005
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  * We fork a child per domain to be able to act non-blocking in the main
25  * winbind daemon. A domain controller thousands of miles away being being
26  * slow replying with a 10.000 user list should not hold up netlogon calls
27  * that can be handled locally.
28  */
29
30 #include "includes.h"
31 #include "winbindd.h"
32 #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 "ntdomain.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
515 /* Ensure any negative cache entries with the netbios or realm names are removed. */
516
517 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
518 {
519         flush_negative_conn_cache_for_domain(domain->name);
520         if (*domain->alt_name) {
521                 flush_negative_conn_cache_for_domain(domain->alt_name);
522         }
523 }
524
525 /* 
526  * Parent winbindd process sets its own debug level first and then
527  * sends a message to all the winbindd children to adjust their debug
528  * level to that of parents.
529  */
530
531 void winbind_msg_debug(struct messaging_context *msg_ctx,
532                          void *private_data,
533                          uint32_t msg_type,
534                          struct server_id server_id,
535                          DATA_BLOB *data)
536 {
537         struct winbindd_child *child;
538
539         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
540
541         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
542
543         for (child = winbindd_children; child != NULL; child = child->next) {
544
545                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
546                         (unsigned int)child->pid));
547
548                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
549                            MSG_DEBUG,
550                            data->data,
551                            strlen((char *) data->data) + 1);
552         }
553 }
554
555 /* Set our domains as offline and forward the offline message to our children. */
556
557 void winbind_msg_offline(struct messaging_context *msg_ctx,
558                          void *private_data,
559                          uint32_t msg_type,
560                          struct server_id server_id,
561                          DATA_BLOB *data)
562 {
563         struct winbindd_child *child;
564         struct winbindd_domain *domain;
565
566         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
567
568         if (!lp_winbind_offline_logon()) {
569                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
570                 return;
571         }
572
573         /* Set our global state as offline. */
574         if (!set_global_winbindd_state_offline()) {
575                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
576                 return;
577         }
578
579         /* Set all our domains as offline. */
580         for (domain = domain_list(); domain; domain = domain->next) {
581                 if (domain->internal) {
582                         continue;
583                 }
584                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
585                 set_domain_offline(domain);
586         }
587
588         for (child = winbindd_children; child != NULL; child = child->next) {
589                 /* Don't send message to internal children.  We've already
590                    done so above. */
591                 if (!child->domain || winbindd_internal_child(child)) {
592                         continue;
593                 }
594
595                 /* Or internal domains (this should not be possible....) */
596                 if (child->domain->internal) {
597                         continue;
598                 }
599
600                 /* Each winbindd child should only process requests for one domain - make sure
601                    we only set it online / offline for that domain. */
602
603                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
604                         (unsigned int)child->pid, domain->name ));
605
606                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
607                                    MSG_WINBIND_OFFLINE,
608                                    (uint8 *)child->domain->name,
609                                    strlen(child->domain->name)+1);
610         }
611 }
612
613 /* Set our domains as online and forward the online message to our children. */
614
615 void winbind_msg_online(struct messaging_context *msg_ctx,
616                         void *private_data,
617                         uint32_t msg_type,
618                         struct server_id server_id,
619                         DATA_BLOB *data)
620 {
621         struct winbindd_child *child;
622         struct winbindd_domain *domain;
623
624         DEBUG(10,("winbind_msg_online: got online message.\n"));
625
626         if (!lp_winbind_offline_logon()) {
627                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
628                 return;
629         }
630
631         /* Set our global state as online. */
632         set_global_winbindd_state_online();
633
634         smb_nscd_flush_user_cache();
635         smb_nscd_flush_group_cache();
636
637         /* Set all our domains as online. */
638         for (domain = domain_list(); domain; domain = domain->next) {
639                 if (domain->internal) {
640                         continue;
641                 }
642                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
643
644                 winbindd_flush_negative_conn_cache(domain);
645                 set_domain_online_request(domain);
646
647                 /* Send an online message to the idmap child when our
648                    primary domain comes back online */
649
650                 if ( domain->primary ) {
651                         struct winbindd_child *idmap = idmap_child();
652
653                         if ( idmap->pid != 0 ) {
654                                 messaging_send_buf(msg_ctx,
655                                                    pid_to_procid(idmap->pid), 
656                                                    MSG_WINBIND_ONLINE,
657                                                    (uint8 *)domain->name,
658                                                    strlen(domain->name)+1);
659                         }
660                 }
661         }
662
663         for (child = winbindd_children; child != NULL; child = child->next) {
664                 /* Don't send message to internal childs. */
665                 if (!child->domain || winbindd_internal_child(child)) {
666                         continue;
667                 }
668
669                 /* Or internal domains (this should not be possible....) */
670                 if (child->domain->internal) {
671                         continue;
672                 }
673
674                 /* Each winbindd child should only process requests for one domain - make sure
675                    we only set it online / offline for that domain. */
676
677                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
678                         (unsigned int)child->pid, child->domain->name ));
679
680                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
681                                    MSG_WINBIND_ONLINE,
682                                    (uint8 *)child->domain->name,
683                                    strlen(child->domain->name)+1);
684         }
685 }
686
687 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
688 {
689         struct winbindd_domain *domain;
690         char *buf = NULL;
691
692         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
693                                    get_global_winbindd_state_offline() ? 
694                                    "Offline":"Online")) == NULL) {
695                 return NULL;
696         }
697
698         for (domain = domain_list(); domain; domain = domain->next) {
699                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
700                                                   domain->name, 
701                                                   domain->online ?
702                                                   "Online":"Offline")) == NULL) {
703                         return NULL;
704                 }
705         }
706
707         buf = talloc_asprintf_append_buffer(buf, "\n");
708
709         DEBUG(5,("collect_onlinestatus: %s", buf));
710
711         return buf;
712 }
713
714 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
715                               void *private_data,
716                               uint32_t msg_type,
717                               struct server_id server_id,
718                               DATA_BLOB *data)
719 {
720         TALLOC_CTX *mem_ctx;
721         const char *message;
722         struct server_id *sender;
723
724         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
725
726         if (!data->data) {
727                 return;
728         }
729
730         sender = (struct server_id *)data->data;
731
732         mem_ctx = talloc_init("winbind_msg_onlinestatus");
733         if (mem_ctx == NULL) {
734                 return;
735         }
736
737         message = collect_onlinestatus(mem_ctx);
738         if (message == NULL) {
739                 talloc_destroy(mem_ctx);
740                 return;
741         }
742
743         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
744                            (uint8 *)message, strlen(message) + 1);
745
746         talloc_destroy(mem_ctx);
747 }
748
749 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
750                                  void *private_data,
751                                  uint32_t msg_type,
752                                  struct server_id server_id,
753                                  DATA_BLOB *data)
754 {
755         struct winbindd_child *child;
756
757         DEBUG(10,("winbind_msg_dump_event_list received\n"));
758
759         dump_event_list(winbind_event_context());
760
761         for (child = winbindd_children; child != NULL; child = child->next) {
762
763                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
764                         (unsigned int)child->pid));
765
766                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
767                                    MSG_DUMP_EVENT_LIST,
768                                    NULL, 0);
769         }
770
771 }
772
773 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
774                                   void *private_data,
775                                   uint32_t msg_type,
776                                   struct server_id server_id,
777                                   DATA_BLOB *data)
778 {
779         TALLOC_CTX *mem_ctx;
780         const char *message = NULL;
781         struct server_id *sender = NULL;
782         const char *domain = NULL;
783         char *s = NULL;
784         NTSTATUS status;
785         struct winbindd_domain *dom = NULL;
786
787         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
788
789         if (!data || !data->data) {
790                 return;
791         }
792
793         if (data->length < sizeof(struct server_id)) {
794                 return;
795         }
796
797         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
798         if (!mem_ctx) {
799                 return;
800         }
801
802         sender = (struct server_id *)data->data;
803         if (data->length > sizeof(struct server_id)) {
804                 domain = (const char *)data->data+sizeof(struct server_id);
805         }
806
807         if (domain) {
808
809                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
810                         domain));
811
812                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
813                                                   find_domain_from_name_noinit(domain));
814                 if (!message) {
815                         talloc_destroy(mem_ctx);
816                         return;
817                 }
818
819                 messaging_send_buf(msg_ctx, *sender,
820                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
821                                    (uint8_t *)message, strlen(message) + 1);
822
823                 talloc_destroy(mem_ctx);
824
825                 return;
826         }
827
828         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
829
830         for (dom = domain_list(); dom; dom=dom->next) {
831                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
832                 if (!message) {
833                         talloc_destroy(mem_ctx);
834                         return;
835                 }
836
837                 s = talloc_asprintf_append(s, "%s\n", message);
838                 if (!s) {
839                         talloc_destroy(mem_ctx);
840                         return;
841                 }
842         }
843
844         status = messaging_send_buf(msg_ctx, *sender,
845                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
846                                     (uint8_t *)s, strlen(s) + 1);
847         if (!NT_STATUS_IS_OK(status)) {
848                 DEBUG(0,("failed to send message: %s\n",
849                 nt_errstr(status)));
850         }
851
852         talloc_destroy(mem_ctx);
853 }
854
855 static void account_lockout_policy_handler(struct event_context *ctx,
856                                            struct timed_event *te,
857                                            struct timeval now,
858                                            void *private_data)
859 {
860         struct winbindd_child *child =
861                 (struct winbindd_child *)private_data;
862         TALLOC_CTX *mem_ctx = NULL;
863         struct winbindd_methods *methods;
864         struct samr_DomInfo12 lockout_policy;
865         NTSTATUS result;
866
867         DEBUG(10,("account_lockout_policy_handler called\n"));
868
869         TALLOC_FREE(child->lockout_policy_event);
870
871         if ( !winbindd_can_contact_domain( child->domain ) ) {
872                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
873                           "do not have an incoming trust to domain %s\n", 
874                           child->domain->name));
875
876                 return;         
877         }
878
879         methods = child->domain->methods;
880
881         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
882         if (!mem_ctx) {
883                 result = NT_STATUS_NO_MEMORY;
884         } else {
885                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
886         }
887         TALLOC_FREE(mem_ctx);
888
889         if (!NT_STATUS_IS_OK(result)) {
890                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
891                          nt_errstr(result)));
892         }
893
894         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
895                                                       timeval_current_ofs(3600, 0),
896                                                       account_lockout_policy_handler,
897                                                       child);
898 }
899
900 static time_t get_machine_password_timeout(void)
901 {
902         /* until we have gpo support use lp setting */
903         return lp_machine_password_timeout();
904 }
905
906 static bool calculate_next_machine_pwd_change(const char *domain,
907                                               struct timeval *t)
908 {
909         time_t pass_last_set_time;
910         time_t timeout;
911         time_t next_change;
912         struct timeval tv;
913         char *pw;
914
915         pw = secrets_fetch_machine_password(domain,
916                                             &pass_last_set_time,
917                                             NULL);
918
919         if (pw == NULL) {
920                 DEBUG(0,("cannot fetch own machine password ????"));
921                 return false;
922         }
923
924         SAFE_FREE(pw);
925
926         timeout = get_machine_password_timeout();
927         if (timeout == 0) {
928                 DEBUG(10,("machine password never expires\n"));
929                 return false;
930         }
931
932         tv.tv_sec = pass_last_set_time;
933         DEBUG(10, ("password last changed %s\n",
934                    timeval_string(talloc_tos(), &tv, false)));
935         tv.tv_sec += timeout;
936         DEBUGADD(10, ("password valid until %s\n",
937                       timeval_string(talloc_tos(), &tv, false)));
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
945                 if (lp_clustering()) {
946                         uint8_t randbuf;
947                         /*
948                          * When having a cluster, we have several
949                          * winbinds racing for the password change. In
950                          * the machine_password_change_handler()
951                          * function we check if someone else was
952                          * faster when the event triggers. We add a
953                          * 255-second random delay here, so that we
954                          * don't run to change the password at the
955                          * exact same moment.
956                          */
957                         generate_random_buffer(&randbuf, sizeof(randbuf));
958                         DEBUG(10, ("adding %d seconds randomness\n",
959                                    (int)randbuf));
960                         t->tv_sec += randbuf;
961                 }
962                 return true;
963         }
964
965         DEBUG(10,("machine password expired, needs immediate change\n"));
966
967         *t = timeval_zero();
968
969         return true;
970 }
971
972 static void machine_password_change_handler(struct event_context *ctx,
973                                             struct timed_event *te,
974                                             struct timeval now,
975                                             void *private_data)
976 {
977         struct winbindd_child *child =
978                 (struct winbindd_child *)private_data;
979         struct rpc_pipe_client *netlogon_pipe = NULL;
980         TALLOC_CTX *frame;
981         NTSTATUS result;
982         struct timeval next_change;
983
984         DEBUG(10,("machine_password_change_handler called\n"));
985
986         TALLOC_FREE(child->machine_password_change_event);
987
988         if (!calculate_next_machine_pwd_change(child->domain->name,
989                                                &next_change)) {
990                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
991                 return;
992         }
993
994         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
995                    timeval_string(talloc_tos(), &next_change, false)));
996
997         if (!timeval_expired(&next_change)) {
998                 DEBUG(10, ("Someone else has already changed the pw\n"));
999                 goto done;
1000         }
1001
1002         if (!winbindd_can_contact_domain(child->domain)) {
1003                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
1004                           "do not have an incoming trust to domain %s\n",
1005                           child->domain->name));
1006                 return;
1007         }
1008
1009         result = cm_connect_netlogon(child->domain, &netlogon_pipe);
1010         if (!NT_STATUS_IS_OK(result)) {
1011                 DEBUG(10,("machine_password_change_handler: "
1012                         "failed to connect netlogon pipe: %s\n",
1013                          nt_errstr(result)));
1014                 return;
1015         }
1016
1017         frame = talloc_stackframe();
1018
1019         result = trust_pw_find_change_and_store_it(netlogon_pipe,
1020                                                    frame,
1021                                                    child->domain->name);
1022         TALLOC_FREE(frame);
1023
1024         DEBUG(10, ("machine_password_change_handler: "
1025                    "trust_pw_find_change_and_store_it returned %s\n",
1026                    nt_errstr(result)));
1027
1028         if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) {
1029                 DEBUG(3,("machine_password_change_handler: password set returned "
1030                          "ACCESS_DENIED.  Maybe the trust account "
1031                          "password was changed and we didn't know it. "
1032                          "Killing connections to domain %s\n",
1033                          child->domain->name));
1034                 TALLOC_FREE(child->domain->conn.netlogon_pipe);
1035         }
1036
1037         if (!calculate_next_machine_pwd_change(child->domain->name,
1038                                                &next_change)) {
1039                 DEBUG(10, ("calculate_next_machine_pwd_change failed\n"));
1040                 return;
1041         }
1042
1043         DEBUG(10, ("calculate_next_machine_pwd_change returned %s\n",
1044                    timeval_string(talloc_tos(), &next_change, false)));
1045
1046         if (!NT_STATUS_IS_OK(result)) {
1047                 struct timeval tmp;
1048                 /*
1049                  * In case of failure, give the DC a minute to recover
1050                  */
1051                 tmp = timeval_current_ofs(60, 0);
1052                 next_change = timeval_max(&next_change, &tmp);
1053         }
1054
1055 done:
1056         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
1057                                                               next_change,
1058                                                               machine_password_change_handler,
1059                                                               child);
1060 }
1061
1062 /* Deal with a request to go offline. */
1063
1064 static void child_msg_offline(struct messaging_context *msg,
1065                               void *private_data,
1066                               uint32_t msg_type,
1067                               struct server_id server_id,
1068                               DATA_BLOB *data)
1069 {
1070         struct winbindd_domain *domain;
1071         struct winbindd_domain *primary_domain = NULL;
1072         const char *domainname = (const char *)data->data;
1073
1074         if (data->data == NULL || data->length == 0) {
1075                 return;
1076         }
1077
1078         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
1079
1080         if (!lp_winbind_offline_logon()) {
1081                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
1082                 return;
1083         }
1084
1085         primary_domain = find_our_domain();
1086
1087         /* Mark the requested domain offline. */
1088
1089         for (domain = domain_list(); domain; domain = domain->next) {
1090                 if (domain->internal) {
1091                         continue;
1092                 }
1093                 if (strequal(domain->name, domainname)) {
1094                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
1095                         set_domain_offline(domain);
1096                         /* we are in the trusted domain, set the primary domain 
1097                          * offline too */
1098                         if (domain != primary_domain) {
1099                                 set_domain_offline(primary_domain);
1100                         }
1101                 }
1102         }
1103 }
1104
1105 /* Deal with a request to go online. */
1106
1107 static void child_msg_online(struct messaging_context *msg,
1108                              void *private_data,
1109                              uint32_t msg_type,
1110                              struct server_id server_id,
1111                              DATA_BLOB *data)
1112 {
1113         struct winbindd_domain *domain;
1114         struct winbindd_domain *primary_domain = NULL;
1115         const char *domainname = (const char *)data->data;
1116
1117         if (data->data == NULL || data->length == 0) {
1118                 return;
1119         }
1120
1121         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
1122
1123         if (!lp_winbind_offline_logon()) {
1124                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
1125                 return;
1126         }
1127
1128         primary_domain = find_our_domain();
1129
1130         /* Set our global state as online. */
1131         set_global_winbindd_state_online();
1132
1133         /* Try and mark everything online - delete any negative cache entries
1134            to force a reconnect now. */
1135
1136         for (domain = domain_list(); domain; domain = domain->next) {
1137                 if (domain->internal) {
1138                         continue;
1139                 }
1140                 if (strequal(domain->name, domainname)) {
1141                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1142                         winbindd_flush_negative_conn_cache(domain);
1143                         set_domain_online_request(domain);
1144
1145                         /* we can be in trusted domain, which will contact primary domain
1146                          * we have to bring primary domain online in trusted domain process
1147                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1148                          * --> contact_domain = find_our_domain()
1149                          * */
1150                         if (domain != primary_domain) {
1151                                 winbindd_flush_negative_conn_cache(primary_domain);
1152                                 set_domain_online_request(primary_domain);
1153                         }
1154                 }
1155         }
1156 }
1157
1158 static void child_msg_dump_event_list(struct messaging_context *msg,
1159                                       void *private_data,
1160                                       uint32_t msg_type,
1161                                       struct server_id server_id,
1162                                       DATA_BLOB *data)
1163 {
1164         DEBUG(5,("child_msg_dump_event_list received\n"));
1165
1166         dump_event_list(winbind_event_context());
1167 }
1168
1169 bool winbindd_reinit_after_fork(const char *logfilename)
1170 {
1171         struct winbindd_domain *domain;
1172         struct winbindd_child *cl;
1173         NTSTATUS status;
1174
1175         status = reinit_after_fork(
1176                 winbind_messaging_context(),
1177                 winbind_event_context(),
1178                 procid_self(),
1179                 true);
1180         if (!NT_STATUS_IS_OK(status)) {
1181                 DEBUG(0,("reinit_after_fork() failed\n"));
1182                 return false;
1183         }
1184
1185         close_conns_after_fork();
1186
1187         if (!override_logfile && logfilename) {
1188                 lp_set_logfile(logfilename);
1189                 reopen_logs();
1190         }
1191
1192         if (!winbindd_setup_sig_term_handler(false))
1193                 return false;
1194         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1195                                             logfilename))
1196                 return false;
1197
1198         /* Stop zombies in children */
1199         CatchChild();
1200
1201         /* Don't handle the same messages as our parent. */
1202         messaging_deregister(winbind_messaging_context(),
1203                              MSG_SMB_CONF_UPDATED, NULL);
1204         messaging_deregister(winbind_messaging_context(),
1205                              MSG_SHUTDOWN, NULL);
1206         messaging_deregister(winbind_messaging_context(),
1207                              MSG_WINBIND_OFFLINE, NULL);
1208         messaging_deregister(winbind_messaging_context(),
1209                              MSG_WINBIND_ONLINE, NULL);
1210         messaging_deregister(winbind_messaging_context(),
1211                              MSG_WINBIND_ONLINESTATUS, NULL);
1212         messaging_deregister(winbind_messaging_context(),
1213                              MSG_DUMP_EVENT_LIST, NULL);
1214         messaging_deregister(winbind_messaging_context(),
1215                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1216         messaging_deregister(winbind_messaging_context(),
1217                              MSG_DEBUG, NULL);
1218
1219         /* We have destroyed all events in the winbindd_event_context
1220          * in reinit_after_fork(), so clean out all possible pending
1221          * event pointers. */
1222
1223         /* Deal with check_online_events. */
1224
1225         for (domain = domain_list(); domain; domain = domain->next) {
1226                 TALLOC_FREE(domain->check_online_event);
1227         }
1228
1229         /* Ensure we're not handling a credential cache event inherited
1230          * from our parent. */
1231
1232         ccache_remove_all_after_fork();
1233
1234         /* Destroy all possible events in child list. */
1235         for (cl = winbindd_children; cl != NULL; cl = cl->next) {
1236                 TALLOC_FREE(cl->lockout_policy_event);
1237                 TALLOC_FREE(cl->machine_password_change_event);
1238
1239                 /* Children should never be able to send
1240                  * each other messages, all messages must
1241                  * go through the parent.
1242                  */
1243                 cl->pid = (pid_t)0;
1244         }
1245         /*
1246          * This is a little tricky, children must not
1247          * send an MSG_WINBIND_ONLINE message to idmap_child().
1248          * If we are in a child of our primary domain or
1249          * in the process created by fork_child_dc_connect(),
1250          * and the primary domain cannot go online,
1251          * fork_child_dc_connection() sends MSG_WINBIND_ONLINE
1252          * periodically to idmap_child().
1253          *
1254          * The sequence is, fork_child_dc_connect() ---> getdcs() --->
1255          * get_dc_name_via_netlogon() ---> cm_connect_netlogon()
1256          * ---> init_dc_connection() ---> cm_open_connection --->
1257          * set_domain_online(), sends MSG_WINBIND_ONLINE to
1258          * idmap_child(). Disallow children sending messages
1259          * to each other, all messages must go through the parent.
1260          */
1261         cl = idmap_child();
1262         cl->pid = (pid_t)0;
1263
1264         return true;
1265 }
1266
1267 /*
1268  * In a child there will be only one domain, reference that here.
1269  */
1270 static struct winbindd_domain *child_domain;
1271
1272 struct winbindd_domain *wb_child_domain(void)
1273 {
1274         return child_domain;
1275 }
1276
1277 static bool fork_domain_child(struct winbindd_child *child)
1278 {
1279         int fdpair[2];
1280         struct winbindd_cli_state state;
1281         struct winbindd_request request;
1282         struct winbindd_response response;
1283         struct winbindd_domain *primary_domain = NULL;
1284
1285         if (child->domain) {
1286                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1287                            child->domain->name));
1288         } else {
1289                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1290         }
1291
1292         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1293                 DEBUG(0, ("Could not open child pipe: %s\n",
1294                           strerror(errno)));
1295                 return False;
1296         }
1297
1298         ZERO_STRUCT(state);
1299         state.pid = sys_getpid();
1300         state.request = &request;
1301         state.response = &response;
1302
1303         child->pid = sys_fork();
1304
1305         if (child->pid == -1) {
1306                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1307                 return False;
1308         }
1309
1310         if (child->pid != 0) {
1311                 /* Parent */
1312                 close(fdpair[0]);
1313                 child->next = child->prev = NULL;
1314                 DLIST_ADD(winbindd_children, child);
1315                 child->sock = fdpair[1];
1316                 return True;
1317         }
1318
1319         /* Child */
1320         child_domain = child->domain;
1321
1322         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1323
1324         state.sock = fdpair[0];
1325         close(fdpair[1]);
1326
1327         if (!winbindd_reinit_after_fork(child->logfilename)) {
1328                 _exit(0);
1329         }
1330
1331         /* Handle online/offline messages. */
1332         messaging_register(winbind_messaging_context(), NULL,
1333                            MSG_WINBIND_OFFLINE, child_msg_offline);
1334         messaging_register(winbind_messaging_context(), NULL,
1335                            MSG_WINBIND_ONLINE, child_msg_online);
1336         messaging_register(winbind_messaging_context(), NULL,
1337                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1338         messaging_register(winbind_messaging_context(), NULL,
1339                            MSG_DEBUG, debug_message);
1340         messaging_register(winbind_messaging_context(), NULL,
1341                            MSG_WINBIND_IP_DROPPED,
1342                            winbind_msg_ip_dropped);
1343
1344
1345         primary_domain = find_our_domain();
1346
1347         if (primary_domain == NULL) {
1348                 smb_panic("no primary domain found");
1349         }
1350
1351         /* It doesn't matter if we allow cache login,
1352          * try to bring domain online after fork. */
1353         if ( child->domain ) {
1354                 child->domain->startup = True;
1355                 child->domain->startup_time = time_mono(NULL);
1356                 /* we can be in primary domain or in trusted domain
1357                  * If we are in trusted domain, set the primary domain
1358                  * in start-up mode */
1359                 if (!(child->domain->internal)) {
1360                         set_domain_online_request(child->domain);
1361                         if (!(child->domain->primary)) {
1362                                 primary_domain->startup = True;
1363                                 primary_domain->startup_time = time_mono(NULL);
1364                                 set_domain_online_request(primary_domain);
1365                         }
1366                 }
1367         }
1368
1369         /*
1370          * We are in idmap child, make sure that we set the
1371          * check_online_event to bring primary domain online.
1372          */
1373         if (child == idmap_child()) {
1374                 set_domain_online_request(primary_domain);
1375         }
1376
1377         /* We might be in the idmap child...*/
1378         if (child->domain && !(child->domain->internal) &&
1379             lp_winbind_offline_logon()) {
1380
1381                 set_domain_online_request(child->domain);
1382
1383                 if (primary_domain && (primary_domain != child->domain)) {
1384                         /* We need to talk to the primary
1385                          * domain as well as the trusted
1386                          * domain inside a trusted domain
1387                          * child.
1388                          * See the code in :
1389                          * set_dc_type_and_flags_trustinfo()
1390                          * for details.
1391                          */
1392                         set_domain_online_request(primary_domain);
1393                 }
1394
1395                 child->lockout_policy_event = event_add_timed(
1396                         winbind_event_context(), NULL, timeval_zero(),
1397                         account_lockout_policy_handler,
1398                         child);
1399         }
1400
1401         if (child->domain && child->domain->primary &&
1402             !USE_KERBEROS_KEYTAB &&
1403             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1404
1405                 struct timeval next_change;
1406
1407                 if (calculate_next_machine_pwd_change(child->domain->name,
1408                                                        &next_change)) {
1409                         child->machine_password_change_event = event_add_timed(
1410                                 winbind_event_context(), NULL, next_change,
1411                                 machine_password_change_handler,
1412                                 child);
1413                 }
1414         }
1415
1416         while (1) {
1417
1418                 int ret;
1419                 struct pollfd *pfds;
1420                 int num_pfds;
1421                 int timeout;
1422                 struct timeval t;
1423                 struct timeval *tp;
1424                 TALLOC_CTX *frame = talloc_stackframe();
1425                 struct iovec iov[2];
1426                 int iov_count;
1427                 NTSTATUS status;
1428
1429                 if (run_events_poll(winbind_event_context(), 0, NULL, 0)) {
1430                         TALLOC_FREE(frame);
1431                         continue;
1432                 }
1433
1434                 if (child->domain && child->domain->startup &&
1435                                 (time_mono(NULL) > child->domain->startup_time + 30)) {
1436                         /* No longer in "startup" mode. */
1437                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1438                                 child->domain->name ));
1439                         child->domain->startup = False;
1440                 }
1441
1442                 pfds = TALLOC_ZERO_P(talloc_tos(), struct pollfd);
1443                 if (pfds == NULL) {
1444                         DEBUG(1, ("talloc failed\n"));
1445                         _exit(1);
1446                 }
1447
1448                 pfds->fd = state.sock;
1449                 pfds->events = POLLIN|POLLHUP;
1450                 num_pfds = 1;
1451
1452                 timeout = INT_MAX;
1453
1454                 if (!event_add_to_poll_args(
1455                             winbind_event_context(), talloc_tos(),
1456                             &pfds, &num_pfds, &timeout)) {
1457                         DEBUG(1, ("event_add_to_poll_args failed\n"));
1458                         _exit(1);
1459                 }
1460                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1461                 if (tp) {
1462                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1463                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1464                 }
1465
1466                 ret = sys_poll(pfds, num_pfds, timeout);
1467
1468                 if (run_events_poll(winbind_event_context(), ret,
1469                                     pfds, num_pfds)) {
1470                         /* We got a signal - continue. */
1471                         TALLOC_FREE(frame);
1472                         continue;
1473                 }
1474
1475                 TALLOC_FREE(pfds);
1476
1477                 if (ret == 0) {
1478                         DEBUG(11,("nothing is ready yet, continue\n"));
1479                         TALLOC_FREE(frame);
1480                         continue;
1481                 }
1482
1483                 if (ret == -1 && errno == EINTR) {
1484                         /* We got a signal - continue. */
1485                         TALLOC_FREE(frame);
1486                         continue;
1487                 }
1488
1489                 if (ret == -1 && errno != EINTR) {
1490                         DEBUG(0,("poll error occured\n"));
1491                         TALLOC_FREE(frame);
1492                         perror("poll");
1493                         _exit(1);
1494                 }
1495
1496                 /* fetch a request from the main daemon */
1497                 status = child_read_request(&state);
1498
1499                 if (!NT_STATUS_IS_OK(status)) {
1500                         /* we lost contact with our parent */
1501                         _exit(0);
1502                 }
1503
1504                 DEBUG(4,("child daemon request %d\n", (int)state.request->cmd));
1505
1506                 ZERO_STRUCTP(state.response);
1507                 state.request->null_term = '\0';
1508                 state.mem_ctx = frame;
1509                 child_process_request(child, &state);
1510
1511                 DEBUG(4, ("Finished processing child request %d\n",
1512                           (int)state.request->cmd));
1513
1514                 SAFE_FREE(state.request->extra_data.data);
1515
1516                 iov[0].iov_base = (void *)state.response;
1517                 iov[0].iov_len = sizeof(struct winbindd_response);
1518                 iov_count = 1;
1519
1520                 if (state.response->length > sizeof(struct winbindd_response)) {
1521                         iov[1].iov_base =
1522                                 (void *)state.response->extra_data.data;
1523                         iov[1].iov_len = state.response->length-iov[0].iov_len;
1524                         iov_count = 2;
1525                 }
1526
1527                 DEBUG(10, ("Writing %d bytes to parent\n",
1528                            (int)state.response->length));
1529
1530                 if (write_data_iov(state.sock, iov, iov_count) !=
1531                     state.response->length) {
1532                         DEBUG(0, ("Could not write result\n"));
1533                         exit(1);
1534                 }
1535                 TALLOC_FREE(frame);
1536         }
1537 }
1538
1539 void winbind_msg_ip_dropped_parent(struct messaging_context *msg_ctx,
1540                                    void *private_data,
1541                                    uint32_t msg_type,
1542                                    struct server_id server_id,
1543                                    DATA_BLOB *data)
1544 {
1545         struct winbindd_child *child;
1546
1547         winbind_msg_ip_dropped(msg_ctx, private_data, msg_type,
1548                                server_id, data);
1549
1550
1551         for (child = winbindd_children; child != NULL; child = child->next) {
1552                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
1553                                    msg_type, data->data, data->length);
1554         }
1555 }