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