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