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