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