]> git.samba.org - samba.git/blob - source3/winbindd/winbindd_dual.c
Convert the winbind parent->child communication to wb_reqtrans
[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 "../../nsswitch/libwbclient/wbc_async.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_WINBIND
36
37 extern bool override_logfile;
38 extern struct winbindd_methods cache_methods;
39
40 /* Read some data from a client connection */
41
42 static void child_read_request(struct winbindd_cli_state *state)
43 {
44         NTSTATUS status;
45
46         /* Read data */
47
48         status = read_data(state->sock, (char *)state->request,
49                            sizeof(*state->request));
50
51         if (!NT_STATUS_IS_OK(status)) {
52                 DEBUG(3, ("child_read_request: read_data failed: %s\n",
53                           nt_errstr(status)));
54                 state->finished = True;
55                 return;
56         }
57
58         if (state->request->extra_len == 0) {
59                 state->request->extra_data.data = NULL;
60                 return;
61         }
62
63         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request->extra_len));
64
65         state->request->extra_data.data =
66                 SMB_MALLOC_ARRAY(char, state->request->extra_len + 1);
67
68         if (state->request->extra_data.data == NULL) {
69                 DEBUG(0, ("malloc failed\n"));
70                 state->finished = True;
71                 return;
72         }
73
74         /* Ensure null termination */
75         state->request->extra_data.data[state->request->extra_len] = '\0';
76
77         status= read_data(state->sock, state->request->extra_data.data,
78                           state->request->extra_len);
79
80         if (!NT_STATUS_IS_OK(status)) {
81                 DEBUG(0, ("Could not read extra data: %s\n",
82                           nt_errstr(status)));
83                 state->finished = True;
84                 return;
85         }
86 }
87
88 /*
89  * Do winbind child async request. This is not simply wb_simple_trans. We have
90  * to do the queueing ourselves because while a request is queued, the child
91  * might have crashed, and we have to re-fork it in the _trigger function.
92  */
93
94 struct wb_child_request_state {
95         struct tevent_context *ev;
96         struct winbindd_child *child;
97         struct winbindd_request *request;
98         struct winbindd_response *response;
99 };
100
101 static bool fork_domain_child(struct winbindd_child *child);
102
103 static void wb_child_request_trigger(struct tevent_req *req,
104                                             void *private_data);
105 static void wb_child_request_done(struct tevent_req *subreq);
106
107 struct tevent_req *wb_child_request_send(TALLOC_CTX *mem_ctx,
108                                          struct tevent_context *ev,
109                                          struct winbindd_child *child,
110                                          struct winbindd_request *request)
111 {
112         struct tevent_req *req;
113         struct wb_child_request_state *state;
114
115         req = tevent_req_create(mem_ctx, &state,
116                                 struct wb_child_request_state);
117         if (req == NULL) {
118                 return NULL;
119         }
120
121         state->ev = ev;
122         state->child = child;
123         state->request = request;
124
125         if (!tevent_queue_add(child->queue, ev, req,
126                               wb_child_request_trigger, NULL)) {
127                 tevent_req_nomem(NULL, req);
128                 return tevent_req_post(req, ev);
129         }
130         return req;
131 }
132
133 static void wb_child_request_trigger(struct tevent_req *req,
134                                      void *private_data)
135 {
136         struct wb_child_request_state *state = tevent_req_data(
137                 req, struct wb_child_request_state);
138         struct tevent_req *subreq;
139
140         if ((state->child->pid == 0) && (!fork_domain_child(state->child))) {
141                 tevent_req_error(req, errno);
142                 return;
143         }
144
145         subreq = wb_simple_trans_send(state, winbind_event_context(), NULL,
146                                       state->child->sock, state->request);
147         if (tevent_req_nomem(subreq, req)) {
148                 return;
149         }
150         tevent_req_set_callback(subreq, wb_child_request_done, req);
151
152         if (!tevent_req_set_endtime(req, state->ev,
153                                     timeval_current_ofs(300, 0))) {
154                 tevent_req_nomem(NULL, req);
155                 return;
156         }
157 }
158
159 static void wb_child_request_done(struct tevent_req *subreq)
160 {
161         struct tevent_req *req = tevent_req_callback_data(
162                 subreq, struct tevent_req);
163         struct wb_child_request_state *state = tevent_req_data(
164                 req, struct wb_child_request_state);
165         int ret, err;
166
167         ret = wb_simple_trans_recv(subreq, state, &state->response, &err);
168         TALLOC_FREE(subreq);
169         if (ret == -1) {
170                 tevent_req_error(req, err);
171                 return;
172         }
173         tevent_req_done(req);
174 }
175
176 int wb_child_request_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
177                           struct winbindd_response **presponse, int *err)
178 {
179         struct wb_child_request_state *state = tevent_req_data(
180                 req, struct wb_child_request_state);
181
182         if (tevent_req_is_unix_error(req, err)) {
183                 return -1;
184         }
185         if (state->response->result != WINBINDD_OK) {
186                 *err = EIO; /* EIO doesn't fit, but what would be better? */
187                 return -1;
188         }
189         *presponse = talloc_move(mem_ctx, &state->response);
190         return 0;
191 }
192
193 /*
194  * Machinery for async requests sent to children. You set up a
195  * winbindd_request, select a child to query, and issue a async_request
196  * call. When the request is completed, the callback function you specified is
197  * called back with the private pointer you gave to async_request.
198  */
199
200 struct winbindd_async_request {
201         struct winbindd_async_request *next, *prev;
202         TALLOC_CTX *mem_ctx;
203         struct winbindd_child *child;
204         struct winbindd_response *response;
205         void (*continuation)(void *private_data, bool success);
206         struct timed_event *reply_timeout_event;
207         pid_t child_pid; /* pid of the child we're waiting on. Used to detect
208                             a restart of the child (child->pid != child_pid). */
209         void *private_data;
210 };
211
212 static bool fork_domain_child(struct winbindd_child *child);
213 static void async_request_done(struct tevent_req *req);
214
215 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
216                    struct winbindd_request *request,
217                    struct winbindd_response *response,
218                    void (*continuation)(void *private_data, bool success),
219                    void *private_data)
220 {
221         struct winbindd_async_request *state;
222         struct tevent_req *req;
223
224         DEBUG(10, ("Sending request to child pid %d (domain=%s)\n",
225                    (int)child->pid,
226                    (child->domain != NULL) ? child->domain->name : "''"));
227
228         state = talloc(mem_ctx, struct winbindd_async_request);
229         if (state == NULL) {
230                 DEBUG(0, ("talloc failed\n"));
231                 continuation(private_data, False);
232                 return;
233         }
234
235         state->mem_ctx = mem_ctx;
236         state->child = child;
237         state->reply_timeout_event = NULL;
238         state->response = response;
239         state->continuation = continuation;
240         state->private_data = private_data;
241
242         request->pid = child->pid;
243
244         req = wb_child_request_send(state, winbind_event_context(),
245                                            child, request);
246         if (req == NULL) {
247                 DEBUG(0, ("wb_child_request_send failed\n"));
248                 continuation(private_data, false);
249                 return;
250         }
251         tevent_req_set_callback(req, async_request_done, state);
252 }
253
254 static void async_request_done(struct tevent_req *req)
255 {
256         struct winbindd_async_request *state = tevent_req_callback_data(
257                 req, struct winbindd_async_request);
258         struct winbindd_response *response;
259         int ret, err;
260
261         ret = wb_child_request_recv(req, state, &response, &err);
262         TALLOC_FREE(req);
263         if (ret == -1) {
264                 DEBUG(2, ("wb_child_request_recv failed: %s\n",
265                           strerror(err)));
266                 state->continuation(state->private_data, false);
267                 return;
268         }
269         *state->response = *response;
270         state->continuation(state->private_data, true);
271 }
272
273 struct domain_request_state {
274         TALLOC_CTX *mem_ctx;
275         struct winbindd_domain *domain;
276         struct winbindd_request *request;
277         struct winbindd_response *response;
278         void (*continuation)(void *private_data_data, bool success);
279         void *private_data_data;
280 };
281
282 static void domain_init_recv(void *private_data_data, bool success);
283
284 void async_domain_request(TALLOC_CTX *mem_ctx,
285                           struct winbindd_domain *domain,
286                           struct winbindd_request *request,
287                           struct winbindd_response *response,
288                           void (*continuation)(void *private_data_data, bool success),
289                           void *private_data_data)
290 {
291         struct domain_request_state *state;
292
293         if (domain->initialized) {
294                 async_request(mem_ctx, &domain->child, request, response,
295                               continuation, private_data_data);
296                 return;
297         }
298
299         state = TALLOC_P(mem_ctx, struct domain_request_state);
300         if (state == NULL) {
301                 DEBUG(0, ("talloc failed\n"));
302                 continuation(private_data_data, False);
303                 return;
304         }
305
306         state->mem_ctx = mem_ctx;
307         state->domain = domain;
308         state->request = request;
309         state->response = response;
310         state->continuation = continuation;
311         state->private_data_data = private_data_data;
312
313         init_child_connection(domain, domain_init_recv, state);
314 }
315
316 static void domain_init_recv(void *private_data_data, bool success)
317 {
318         struct domain_request_state *state =
319                 talloc_get_type_abort(private_data_data, struct domain_request_state);
320
321         if (!success) {
322                 DEBUG(5, ("Domain init returned an error\n"));
323                 state->continuation(state->private_data_data, False);
324                 return;
325         }
326
327         async_request(state->mem_ctx, &state->domain->child,
328                       state->request, state->response,
329                       state->continuation, state->private_data_data);
330 }
331
332 static void recvfrom_child(void *private_data_data, bool success)
333 {
334         struct winbindd_cli_state *state =
335                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
336         enum winbindd_result result = state->response.result;
337
338         /* This is an optimization: The child has written directly to the
339          * response buffer. The request itself is still in pending state,
340          * state that in the result code. */
341
342         state->response.result = WINBINDD_PENDING;
343
344         if ((!success) || (result != WINBINDD_OK)) {
345                 request_error(state);
346                 return;
347         }
348
349         request_ok(state);
350 }
351
352 void sendto_child(struct winbindd_cli_state *state,
353                   struct winbindd_child *child)
354 {
355         async_request(state->mem_ctx, child, state->request,
356                       &state->response, recvfrom_child, state);
357 }
358
359 void sendto_domain(struct winbindd_cli_state *state,
360                    struct winbindd_domain *domain)
361 {
362         async_domain_request(state->mem_ctx, domain,
363                              state->request, &state->response,
364                              recvfrom_child, state);
365 }
366
367 static void child_process_request(struct winbindd_child *child,
368                                   struct winbindd_cli_state *state)
369 {
370         struct winbindd_domain *domain = child->domain;
371         const struct winbindd_child_dispatch_table *table = child->table;
372
373         /* Free response data - we may be interrupted and receive another
374            command before being able to send this data off. */
375
376         state->response.result = WINBINDD_ERROR;
377         state->response.length = sizeof(struct winbindd_response);
378
379         /* as all requests in the child are sync, we can use talloc_tos() */
380         state->mem_ctx = talloc_tos();
381
382         /* Process command */
383
384         for (; table->name; table++) {
385                 if (state->request->cmd == table->struct_cmd) {
386                         DEBUG(10,("child_process_request: request fn %s\n",
387                                   table->name));
388                         state->response.result = table->struct_fn(domain, state);
389                         return;
390                 }
391         }
392
393         DEBUG(1 ,("child_process_request: unknown request fn number %d\n",
394                   (int)state->request->cmd));
395         state->response.result = WINBINDD_ERROR;
396 }
397
398 void setup_child(struct winbindd_child *child,
399                  const struct winbindd_child_dispatch_table *table,
400                  const char *logprefix,
401                  const char *logname)
402 {
403         if (logprefix && logname) {
404                 if (asprintf(&child->logfilename, "%s/%s-%s",
405                              get_dyn_LOGFILEBASE(), logprefix, logname) < 0) {
406                         smb_panic("Internal error: asprintf failed");
407                 }
408         } else {
409                 smb_panic("Internal error: logprefix == NULL && "
410                           "logname == NULL");
411         }
412
413         child->domain = NULL;
414         child->table = table;
415         child->queue = tevent_queue_create(NULL, "winbind_child");
416         SMB_ASSERT(child->queue != NULL);
417 }
418
419 struct winbindd_child *children = NULL;
420
421 void winbind_child_died(pid_t pid)
422 {
423         struct winbindd_child *child;
424
425         for (child = children; child != NULL; child = child->next) {
426                 if (child->pid == pid) {
427                         break;
428                 }
429         }
430
431         if (child == NULL) {
432                 DEBUG(5, ("Already reaped child %u died\n", (unsigned int)pid));
433                 return;
434         }
435
436         /* This will be re-added in fork_domain_child() */
437
438         DLIST_REMOVE(children, child);
439
440         close(child->sock);
441         child->sock = -1;
442         child->pid = 0;
443 }
444
445 /* Ensure any negative cache entries with the netbios or realm names are removed. */
446
447 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
448 {
449         flush_negative_conn_cache_for_domain(domain->name);
450         if (*domain->alt_name) {
451                 flush_negative_conn_cache_for_domain(domain->alt_name);
452         }
453 }
454
455 /* 
456  * Parent winbindd process sets its own debug level first and then
457  * sends a message to all the winbindd children to adjust their debug
458  * level to that of parents.
459  */
460
461 void winbind_msg_debug(struct messaging_context *msg_ctx,
462                          void *private_data,
463                          uint32_t msg_type,
464                          struct server_id server_id,
465                          DATA_BLOB *data)
466 {
467         struct winbindd_child *child;
468
469         DEBUG(10,("winbind_msg_debug: got debug message.\n"));
470
471         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
472
473         for (child = children; child != NULL; child = child->next) {
474
475                 DEBUG(10,("winbind_msg_debug: sending message to pid %u.\n",
476                         (unsigned int)child->pid));
477
478                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
479                            MSG_DEBUG,
480                            data->data,
481                            strlen((char *) data->data) + 1);
482         }
483 }
484
485 /* Set our domains as offline and forward the offline message to our children. */
486
487 void winbind_msg_offline(struct messaging_context *msg_ctx,
488                          void *private_data,
489                          uint32_t msg_type,
490                          struct server_id server_id,
491                          DATA_BLOB *data)
492 {
493         struct winbindd_child *child;
494         struct winbindd_domain *domain;
495
496         DEBUG(10,("winbind_msg_offline: got offline message.\n"));
497
498         if (!lp_winbind_offline_logon()) {
499                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
500                 return;
501         }
502
503         /* Set our global state as offline. */
504         if (!set_global_winbindd_state_offline()) {
505                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
506                 return;
507         }
508
509         /* Set all our domains as offline. */
510         for (domain = domain_list(); domain; domain = domain->next) {
511                 if (domain->internal) {
512                         continue;
513                 }
514                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
515                 set_domain_offline(domain);
516         }
517
518         for (child = children; child != NULL; child = child->next) {
519                 /* Don't send message to internal childs.  We've already
520                    done so above. */
521                 if (!child->domain || winbindd_internal_child(child)) {
522                         continue;
523                 }
524
525                 /* Or internal domains (this should not be possible....) */
526                 if (child->domain->internal) {
527                         continue;
528                 }
529
530                 /* Each winbindd child should only process requests for one domain - make sure
531                    we only set it online / offline for that domain. */
532
533                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
534                         (unsigned int)child->pid, domain->name ));
535
536                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
537                                    MSG_WINBIND_OFFLINE,
538                                    (uint8 *)child->domain->name,
539                                    strlen(child->domain->name)+1);
540         }
541 }
542
543 /* Set our domains as online and forward the online message to our children. */
544
545 void winbind_msg_online(struct messaging_context *msg_ctx,
546                         void *private_data,
547                         uint32_t msg_type,
548                         struct server_id server_id,
549                         DATA_BLOB *data)
550 {
551         struct winbindd_child *child;
552         struct winbindd_domain *domain;
553
554         DEBUG(10,("winbind_msg_online: got online message.\n"));
555
556         if (!lp_winbind_offline_logon()) {
557                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
558                 return;
559         }
560
561         /* Set our global state as online. */
562         set_global_winbindd_state_online();
563
564         smb_nscd_flush_user_cache();
565         smb_nscd_flush_group_cache();
566
567         /* Set all our domains as online. */
568         for (domain = domain_list(); domain; domain = domain->next) {
569                 if (domain->internal) {
570                         continue;
571                 }
572                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
573
574                 winbindd_flush_negative_conn_cache(domain);
575                 set_domain_online_request(domain);
576
577                 /* Send an online message to the idmap child when our
578                    primary domain comes back online */
579
580                 if ( domain->primary ) {
581                         struct winbindd_child *idmap = idmap_child();
582
583                         if ( idmap->pid != 0 ) {
584                                 messaging_send_buf(msg_ctx,
585                                                    pid_to_procid(idmap->pid), 
586                                                    MSG_WINBIND_ONLINE,
587                                                    (uint8 *)domain->name,
588                                                    strlen(domain->name)+1);
589                         }
590                 }
591         }
592
593         for (child = children; child != NULL; child = child->next) {
594                 /* Don't send message to internal childs. */
595                 if (!child->domain || winbindd_internal_child(child)) {
596                         continue;
597                 }
598
599                 /* Or internal domains (this should not be possible....) */
600                 if (child->domain->internal) {
601                         continue;
602                 }
603
604                 /* Each winbindd child should only process requests for one domain - make sure
605                    we only set it online / offline for that domain. */
606
607                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
608                         (unsigned int)child->pid, child->domain->name ));
609
610                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
611                                    MSG_WINBIND_ONLINE,
612                                    (uint8 *)child->domain->name,
613                                    strlen(child->domain->name)+1);
614         }
615 }
616
617 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
618 {
619         struct winbindd_domain *domain;
620         char *buf = NULL;
621
622         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
623                                    get_global_winbindd_state_offline() ? 
624                                    "Offline":"Online")) == NULL) {
625                 return NULL;
626         }
627
628         for (domain = domain_list(); domain; domain = domain->next) {
629                 if ((buf = talloc_asprintf_append_buffer(buf, "%s:%s ", 
630                                                   domain->name, 
631                                                   domain->online ?
632                                                   "Online":"Offline")) == NULL) {
633                         return NULL;
634                 }
635         }
636
637         buf = talloc_asprintf_append_buffer(buf, "\n");
638
639         DEBUG(5,("collect_onlinestatus: %s", buf));
640
641         return buf;
642 }
643
644 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
645                               void *private_data,
646                               uint32_t msg_type,
647                               struct server_id server_id,
648                               DATA_BLOB *data)
649 {
650         TALLOC_CTX *mem_ctx;
651         const char *message;
652         struct server_id *sender;
653         
654         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
655
656         if (!data->data) {
657                 return;
658         }
659
660         sender = (struct server_id *)data->data;
661
662         mem_ctx = talloc_init("winbind_msg_onlinestatus");
663         if (mem_ctx == NULL) {
664                 return;
665         }
666         
667         message = collect_onlinestatus(mem_ctx);
668         if (message == NULL) {
669                 talloc_destroy(mem_ctx);
670                 return;
671         }
672
673         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
674                            (uint8 *)message, strlen(message) + 1);
675
676         talloc_destroy(mem_ctx);
677 }
678
679 void winbind_msg_dump_event_list(struct messaging_context *msg_ctx,
680                                  void *private_data,
681                                  uint32_t msg_type,
682                                  struct server_id server_id,
683                                  DATA_BLOB *data)
684 {
685         struct winbindd_child *child;
686
687         DEBUG(10,("winbind_msg_dump_event_list received\n"));
688
689         dump_event_list(winbind_event_context());
690
691         for (child = children; child != NULL; child = child->next) {
692
693                 DEBUG(10,("winbind_msg_dump_event_list: sending message to pid %u\n",
694                         (unsigned int)child->pid));
695
696                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
697                                    MSG_DUMP_EVENT_LIST,
698                                    NULL, 0);
699         }
700
701 }
702
703 void winbind_msg_dump_domain_list(struct messaging_context *msg_ctx,
704                                   void *private_data,
705                                   uint32_t msg_type,
706                                   struct server_id server_id,
707                                   DATA_BLOB *data)
708 {
709         TALLOC_CTX *mem_ctx;
710         const char *message = NULL;
711         struct server_id *sender = NULL;
712         const char *domain = NULL;
713         char *s = NULL;
714         NTSTATUS status;
715         struct winbindd_domain *dom = NULL;
716
717         DEBUG(5,("winbind_msg_dump_domain_list received.\n"));
718
719         if (!data || !data->data) {
720                 return;
721         }
722
723         if (data->length < sizeof(struct server_id)) {
724                 return;
725         }
726
727         mem_ctx = talloc_init("winbind_msg_dump_domain_list");
728         if (!mem_ctx) {
729                 return;
730         }
731
732         sender = (struct server_id *)data->data;
733         if (data->length > sizeof(struct server_id)) {
734                 domain = (const char *)data->data+sizeof(struct server_id);
735         }
736
737         if (domain) {
738
739                 DEBUG(5,("winbind_msg_dump_domain_list for domain: %s\n",
740                         domain));
741
742                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain,
743                                                   find_domain_from_name_noinit(domain));
744                 if (!message) {
745                         talloc_destroy(mem_ctx);
746                         return;
747                 }
748
749                 messaging_send_buf(msg_ctx, *sender,
750                                    MSG_WINBIND_DUMP_DOMAIN_LIST,
751                                    (uint8_t *)message, strlen(message) + 1);
752
753                 talloc_destroy(mem_ctx);
754
755                 return;
756         }
757
758         DEBUG(5,("winbind_msg_dump_domain_list all domains\n"));
759
760         for (dom = domain_list(); dom; dom=dom->next) {
761                 message = NDR_PRINT_STRUCT_STRING(mem_ctx, winbindd_domain, dom);
762                 if (!message) {
763                         talloc_destroy(mem_ctx);
764                         return;
765                 }
766
767                 s = talloc_asprintf_append(s, "%s\n", message);
768                 if (!s) {
769                         talloc_destroy(mem_ctx);
770                         return;
771                 }
772         }
773
774         status = messaging_send_buf(msg_ctx, *sender,
775                                     MSG_WINBIND_DUMP_DOMAIN_LIST,
776                                     (uint8_t *)s, strlen(s) + 1);
777         if (!NT_STATUS_IS_OK(status)) {
778                 DEBUG(0,("failed to send message: %s\n",
779                 nt_errstr(status)));
780         }
781
782         talloc_destroy(mem_ctx);
783 }
784
785 static void account_lockout_policy_handler(struct event_context *ctx,
786                                            struct timed_event *te,
787                                            struct timeval now,
788                                            void *private_data)
789 {
790         struct winbindd_child *child =
791                 (struct winbindd_child *)private_data;
792         TALLOC_CTX *mem_ctx = NULL;
793         struct winbindd_methods *methods;
794         struct samr_DomInfo12 lockout_policy;
795         NTSTATUS result;
796
797         DEBUG(10,("account_lockout_policy_handler called\n"));
798
799         TALLOC_FREE(child->lockout_policy_event);
800
801         if ( !winbindd_can_contact_domain( child->domain ) ) {
802                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
803                           "do not have an incoming trust to domain %s\n", 
804                           child->domain->name));
805
806                 return;         
807         }
808
809         methods = child->domain->methods;
810
811         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
812         if (!mem_ctx) {
813                 result = NT_STATUS_NO_MEMORY;
814         } else {
815                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
816         }
817         TALLOC_FREE(mem_ctx);
818
819         if (!NT_STATUS_IS_OK(result)) {
820                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
821                          nt_errstr(result)));
822         }
823
824         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
825                                                       timeval_current_ofs(3600, 0),
826                                                       account_lockout_policy_handler,
827                                                       child);
828 }
829
830 static time_t get_machine_password_timeout(void)
831 {
832         /* until we have gpo support use lp setting */
833         return lp_machine_password_timeout();
834 }
835
836 static bool calculate_next_machine_pwd_change(const char *domain,
837                                               struct timeval *t)
838 {
839         time_t pass_last_set_time;
840         time_t timeout;
841         time_t next_change;
842         char *pw;
843
844         pw = secrets_fetch_machine_password(domain,
845                                             &pass_last_set_time,
846                                             NULL);
847
848         if (pw == NULL) {
849                 DEBUG(0,("cannot fetch own machine password ????"));
850                 return false;
851         }
852
853         SAFE_FREE(pw);
854
855         timeout = get_machine_password_timeout();
856         if (timeout == 0) {
857                 DEBUG(10,("machine password never expires\n"));
858                 return false;
859         }
860
861         if (time(NULL) < (pass_last_set_time + timeout)) {
862                 next_change = pass_last_set_time + timeout;
863                 DEBUG(10,("machine password still valid until: %s\n",
864                         http_timestring(talloc_tos(), next_change)));
865                 *t = timeval_set(next_change, 0);
866                 return true;
867         }
868
869         DEBUG(10,("machine password expired, needs immediate change\n"));
870
871         *t = timeval_zero();
872
873         return true;
874 }
875
876 static void machine_password_change_handler(struct event_context *ctx,
877                                             struct timed_event *te,
878                                             struct timeval now,
879                                             void *private_data)
880 {
881         struct winbindd_child *child =
882                 (struct winbindd_child *)private_data;
883         struct rpc_pipe_client *netlogon_pipe = NULL;
884         TALLOC_CTX *frame;
885         NTSTATUS result;
886         struct timeval next_change;
887
888         DEBUG(10,("machine_password_change_handler called\n"));
889
890         TALLOC_FREE(child->machine_password_change_event);
891
892         if (!calculate_next_machine_pwd_change(child->domain->name,
893                                                &next_change)) {
894                 return;
895         }
896
897         if (!winbindd_can_contact_domain(child->domain)) {
898                 DEBUG(10,("machine_password_change_handler: Removing myself since I "
899                           "do not have an incoming trust to domain %s\n",
900                           child->domain->name));
901                 return;
902         }
903
904         result = cm_connect_netlogon(child->domain, &netlogon_pipe);
905         if (!NT_STATUS_IS_OK(result)) {
906                 DEBUG(10,("machine_password_change_handler: "
907                         "failed to connect netlogon pipe: %s\n",
908                          nt_errstr(result)));
909                 return;
910         }
911
912         frame = talloc_stackframe();
913
914         result = trust_pw_find_change_and_store_it(netlogon_pipe,
915                                                    frame,
916                                                    child->domain->name);
917         TALLOC_FREE(frame);
918
919         if (!NT_STATUS_IS_OK(result)) {
920                 DEBUG(10,("machine_password_change_handler: "
921                         "failed to change machine password: %s\n",
922                          nt_errstr(result)));
923         } else {
924                 DEBUG(10,("machine_password_change_handler: "
925                         "successfully changed machine password\n"));
926         }
927
928         child->machine_password_change_event = event_add_timed(winbind_event_context(), NULL,
929                                                               next_change,
930                                                               machine_password_change_handler,
931                                                               child);
932 }
933
934 /* Deal with a request to go offline. */
935
936 static void child_msg_offline(struct messaging_context *msg,
937                               void *private_data,
938                               uint32_t msg_type,
939                               struct server_id server_id,
940                               DATA_BLOB *data)
941 {
942         struct winbindd_domain *domain;
943         struct winbindd_domain *primary_domain = NULL;
944         const char *domainname = (const char *)data->data;
945
946         if (data->data == NULL || data->length == 0) {
947                 return;
948         }
949
950         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
951
952         if (!lp_winbind_offline_logon()) {
953                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
954                 return;
955         }
956
957         primary_domain = find_our_domain();
958
959         /* Mark the requested domain offline. */
960
961         for (domain = domain_list(); domain; domain = domain->next) {
962                 if (domain->internal) {
963                         continue;
964                 }
965                 if (strequal(domain->name, domainname)) {
966                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
967                         set_domain_offline(domain);
968                         /* we are in the trusted domain, set the primary domain 
969                          * offline too */
970                         if (domain != primary_domain) {
971                                 set_domain_offline(primary_domain);
972                         }
973                 }
974         }
975 }
976
977 /* Deal with a request to go online. */
978
979 static void child_msg_online(struct messaging_context *msg,
980                              void *private_data,
981                              uint32_t msg_type,
982                              struct server_id server_id,
983                              DATA_BLOB *data)
984 {
985         struct winbindd_domain *domain;
986         struct winbindd_domain *primary_domain = NULL;
987         const char *domainname = (const char *)data->data;
988
989         if (data->data == NULL || data->length == 0) {
990                 return;
991         }
992
993         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
994
995         if (!lp_winbind_offline_logon()) {
996                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
997                 return;
998         }
999
1000         primary_domain = find_our_domain();
1001
1002         /* Set our global state as online. */
1003         set_global_winbindd_state_online();
1004
1005         /* Try and mark everything online - delete any negative cache entries
1006            to force a reconnect now. */
1007
1008         for (domain = domain_list(); domain; domain = domain->next) {
1009                 if (domain->internal) {
1010                         continue;
1011                 }
1012                 if (strequal(domain->name, domainname)) {
1013                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
1014                         winbindd_flush_negative_conn_cache(domain);
1015                         set_domain_online_request(domain);
1016
1017                         /* we can be in trusted domain, which will contact primary domain
1018                          * we have to bring primary domain online in trusted domain process
1019                          * see, winbindd_dual_pam_auth() --> winbindd_dual_pam_auth_samlogon()
1020                          * --> contact_domain = find_our_domain()
1021                          * */
1022                         if (domain != primary_domain) {
1023                                 winbindd_flush_negative_conn_cache(primary_domain);
1024                                 set_domain_online_request(primary_domain);
1025                         }
1026                 }
1027         }
1028 }
1029
1030 static void child_msg_dump_event_list(struct messaging_context *msg,
1031                                       void *private_data,
1032                                       uint32_t msg_type,
1033                                       struct server_id server_id,
1034                                       DATA_BLOB *data)
1035 {
1036         DEBUG(5,("child_msg_dump_event_list received\n"));
1037
1038         dump_event_list(winbind_event_context());
1039 }
1040
1041 bool winbindd_reinit_after_fork(const char *logfilename)
1042 {
1043         struct winbindd_domain *domain;
1044         struct winbindd_child *cl;
1045
1046         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1047                                                winbind_event_context(),
1048                                                true))) {
1049                 DEBUG(0,("reinit_after_fork() failed\n"));
1050                 return false;
1051         }
1052
1053         close_conns_after_fork();
1054
1055         if (!override_logfile && logfilename) {
1056                 lp_set_logfile(logfilename);
1057                 reopen_logs();
1058         }
1059
1060         if (!winbindd_setup_sig_term_handler(false))
1061                 return false;
1062         if (!winbindd_setup_sig_hup_handler(override_logfile ? NULL :
1063                                             logfilename))
1064                 return false;
1065
1066         /* Don't handle the same messages as our parent. */
1067         messaging_deregister(winbind_messaging_context(),
1068                              MSG_SMB_CONF_UPDATED, NULL);
1069         messaging_deregister(winbind_messaging_context(),
1070                              MSG_SHUTDOWN, NULL);
1071         messaging_deregister(winbind_messaging_context(),
1072                              MSG_WINBIND_OFFLINE, NULL);
1073         messaging_deregister(winbind_messaging_context(),
1074                              MSG_WINBIND_ONLINE, NULL);
1075         messaging_deregister(winbind_messaging_context(),
1076                              MSG_WINBIND_ONLINESTATUS, NULL);
1077         messaging_deregister(winbind_messaging_context(),
1078                              MSG_DUMP_EVENT_LIST, NULL);
1079         messaging_deregister(winbind_messaging_context(),
1080                              MSG_WINBIND_DUMP_DOMAIN_LIST, NULL);
1081         messaging_deregister(winbind_messaging_context(),
1082                              MSG_DEBUG, NULL);
1083
1084         /* We have destroyed all events in the winbindd_event_context
1085          * in reinit_after_fork(), so clean out all possible pending
1086          * event pointers. */
1087
1088         /* Deal with check_online_events. */
1089
1090         for (domain = domain_list(); domain; domain = domain->next) {
1091                 TALLOC_FREE(domain->check_online_event);
1092         }
1093
1094         /* Ensure we're not handling a credential cache event inherited
1095          * from our parent. */
1096
1097         ccache_remove_all_after_fork();
1098
1099         /* Destroy all possible events in child list. */
1100         for (cl = children; cl != NULL; cl = cl->next) {
1101                 TALLOC_FREE(cl->lockout_policy_event);
1102                 TALLOC_FREE(cl->machine_password_change_event);
1103
1104                 /* Children should never be able to send
1105                  * each other messages, all messages must
1106                  * go through the parent.
1107                  */
1108                 cl->pid = (pid_t)0;
1109         }
1110         /*
1111          * This is a little tricky, children must not
1112          * send an MSG_WINBIND_ONLINE message to idmap_child().
1113          * If we are in a child of our primary domain or
1114          * in the process created by fork_child_dc_connect(),
1115          * and the primary domain cannot go online,
1116          * fork_child_dc_connection() sends MSG_WINBIND_ONLINE
1117          * periodically to idmap_child().
1118          *
1119          * The sequence is, fork_child_dc_connect() ---> getdcs() --->
1120          * get_dc_name_via_netlogon() ---> cm_connect_netlogon()
1121          * ---> init_dc_connection() ---> cm_open_connection --->
1122          * set_domain_online(), sends MSG_WINBIND_ONLINE to
1123          * idmap_child(). Disallow children sending messages
1124          * to each other, all messages must go through the parent.
1125          */
1126         cl = idmap_child();
1127         cl->pid = (pid_t)0;
1128
1129         return true;
1130 }
1131
1132 static bool fork_domain_child(struct winbindd_child *child)
1133 {
1134         int fdpair[2];
1135         struct winbindd_cli_state state;
1136         struct winbindd_domain *primary_domain = NULL;
1137
1138         if (child->domain) {
1139                 DEBUG(10, ("fork_domain_child called for domain '%s'\n",
1140                            child->domain->name));
1141         } else {
1142                 DEBUG(10, ("fork_domain_child called without domain.\n"));
1143         }
1144
1145         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
1146                 DEBUG(0, ("Could not open child pipe: %s\n",
1147                           strerror(errno)));
1148                 return False;
1149         }
1150
1151         ZERO_STRUCT(state);
1152         state.pid = sys_getpid();
1153         state.request = &state._request;
1154
1155         child->pid = sys_fork();
1156
1157         if (child->pid == -1) {
1158                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
1159                 return False;
1160         }
1161
1162         if (child->pid != 0) {
1163                 /* Parent */
1164                 close(fdpair[0]);
1165                 child->next = child->prev = NULL;
1166                 DLIST_ADD(children, child);
1167                 child->sock = fdpair[1];
1168                 return True;
1169         }
1170
1171         /* Child */
1172
1173         DEBUG(10, ("Child process %d\n", (int)sys_getpid()));
1174
1175         /* Stop zombies in children */
1176         CatchChild();
1177
1178         state.sock = fdpair[0];
1179         close(fdpair[1]);
1180
1181         if (!winbindd_reinit_after_fork(child->logfilename)) {
1182                 _exit(0);
1183         }
1184
1185         /* Handle online/offline messages. */
1186         messaging_register(winbind_messaging_context(), NULL,
1187                            MSG_WINBIND_OFFLINE, child_msg_offline);
1188         messaging_register(winbind_messaging_context(), NULL,
1189                            MSG_WINBIND_ONLINE, child_msg_online);
1190         messaging_register(winbind_messaging_context(), NULL,
1191                            MSG_DUMP_EVENT_LIST, child_msg_dump_event_list);
1192         messaging_register(winbind_messaging_context(), NULL,
1193                            MSG_DEBUG, debug_message);
1194
1195         primary_domain = find_our_domain();
1196
1197         if (primary_domain == NULL) {
1198                 smb_panic("no primary domain found");
1199         }
1200
1201         /* It doesn't matter if we allow cache login,
1202          * try to bring domain online after fork. */
1203         if ( child->domain ) {
1204                 child->domain->startup = True;
1205                 child->domain->startup_time = time(NULL);
1206                 /* we can be in primary domain or in trusted domain
1207                  * If we are in trusted domain, set the primary domain
1208                  * in start-up mode */
1209                 if (!(child->domain->internal)) {
1210                         set_domain_online_request(child->domain);
1211                         if (!(child->domain->primary)) {
1212                                 primary_domain->startup = True;
1213                                 primary_domain->startup_time = time(NULL);
1214                                 set_domain_online_request(primary_domain);
1215                         }
1216                 }
1217         }
1218
1219         /*
1220          * We are in idmap child, make sure that we set the
1221          * check_online_event to bring primary domain online.
1222          */
1223         if (child == idmap_child()) {
1224                 set_domain_online_request(primary_domain);
1225         }
1226
1227         /* We might be in the idmap child...*/
1228         if (child->domain && !(child->domain->internal) &&
1229             lp_winbind_offline_logon()) {
1230
1231                 set_domain_online_request(child->domain);
1232
1233                 if (primary_domain && (primary_domain != child->domain)) {
1234                         /* We need to talk to the primary
1235                          * domain as well as the trusted
1236                          * domain inside a trusted domain
1237                          * child.
1238                          * See the code in :
1239                          * set_dc_type_and_flags_trustinfo()
1240                          * for details.
1241                          */
1242                         set_domain_online_request(primary_domain);
1243                 }
1244
1245                 child->lockout_policy_event = event_add_timed(
1246                         winbind_event_context(), NULL, timeval_zero(),
1247                         account_lockout_policy_handler,
1248                         child);
1249         }
1250
1251         if (child->domain && child->domain->primary &&
1252             !USE_KERBEROS_KEYTAB &&
1253             lp_server_role() == ROLE_DOMAIN_MEMBER) {
1254
1255                 struct timeval next_change;
1256
1257                 if (calculate_next_machine_pwd_change(child->domain->name,
1258                                                        &next_change)) {
1259                         child->machine_password_change_event = event_add_timed(
1260                                 winbind_event_context(), NULL, next_change,
1261                                 machine_password_change_handler,
1262                                 child);
1263                 }
1264         }
1265
1266         while (1) {
1267
1268                 int ret;
1269                 fd_set r_fds;
1270                 fd_set w_fds;
1271                 int maxfd;
1272                 struct timeval t;
1273                 struct timeval *tp;
1274                 struct timeval now;
1275                 TALLOC_CTX *frame = talloc_stackframe();
1276                 struct iovec iov[2];
1277                 int iov_count;
1278
1279                 if (run_events(winbind_event_context(), 0, NULL, NULL)) {
1280                         TALLOC_FREE(frame);
1281                         continue;
1282                 }
1283
1284                 GetTimeOfDay(&now);
1285
1286                 if (child->domain && child->domain->startup &&
1287                                 (now.tv_sec > child->domain->startup_time + 30)) {
1288                         /* No longer in "startup" mode. */
1289                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1290                                 child->domain->name ));
1291                         child->domain->startup = False;
1292                 }
1293
1294                 FD_ZERO(&r_fds);
1295                 FD_ZERO(&w_fds);
1296                 FD_SET(state.sock, &r_fds);
1297                 maxfd = state.sock;
1298
1299                 event_add_to_select_args(winbind_event_context(), &now,
1300                                          &r_fds, &w_fds, &t, &maxfd);
1301                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1302                 if (tp) {
1303                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1304                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1305                 }
1306
1307                 ret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, tp);
1308
1309                 if (run_events(winbind_event_context(), ret, &r_fds, &w_fds)) {
1310                         /* We got a signal - continue. */
1311                         TALLOC_FREE(frame);
1312                         continue;
1313                 }
1314
1315                 if (ret == 0) {
1316                         DEBUG(11,("nothing is ready yet, continue\n"));
1317                         TALLOC_FREE(frame);
1318                         continue;
1319                 }
1320
1321                 if (ret == -1 && errno == EINTR) {
1322                         /* We got a signal - continue. */
1323                         TALLOC_FREE(frame);
1324                         continue;
1325                 }
1326
1327                 if (ret == -1 && errno != EINTR) {
1328                         DEBUG(0,("select error occured\n"));
1329                         TALLOC_FREE(frame);
1330                         perror("select");
1331                         _exit(1);
1332                 }
1333
1334                 /* fetch a request from the main daemon */
1335                 child_read_request(&state);
1336
1337                 if (state.finished) {
1338                         /* we lost contact with our parent */
1339                         _exit(0);
1340                 }
1341
1342                 DEBUG(4,("child daemon request %d\n", (int)state.request->cmd));
1343
1344                 ZERO_STRUCT(state.response);
1345                 state.request->null_term = '\0';
1346                 child_process_request(child, &state);
1347
1348                 DEBUG(4, ("Finished processing child request %d\n",
1349                           (int)state.request->cmd));
1350
1351                 SAFE_FREE(state.request->extra_data.data);
1352
1353                 iov[0].iov_base = (void *)&state.response;
1354                 iov[0].iov_len = sizeof(struct winbindd_response);
1355                 iov_count = 1;
1356
1357                 if (state.response.length > sizeof(struct winbindd_response)) {
1358                         iov[1].iov_base =
1359                                 (void *)state.response.extra_data.data;
1360                         iov[1].iov_len = state.response.length-iov[0].iov_len;
1361                         iov_count = 2;
1362                 }
1363
1364                 DEBUG(10, ("Writing %d bytes to parent\n",
1365                            (int)state.response.length));
1366
1367                 if (write_data_iov(state.sock, iov, iov_count) !=
1368                     state.response.length) {
1369                         DEBUG(0, ("Could not write result\n"));
1370                         exit(1);
1371                 }
1372                 TALLOC_FREE(frame);
1373         }
1374 }