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