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