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