r23448: Doh ! Don't call winbind_child_died() *before* the
[samba.git] / source / nsswitch / 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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 /*
25  * We fork a child per domain to be able to act non-blocking in the main
26  * winbind daemon. A domain controller thousands of miles away being being
27  * slow replying with a 10.000 user list should not hold up netlogon calls
28  * that can be handled locally.
29  */
30
31 #include "includes.h"
32 #include "winbindd.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_WINBIND
36
37 extern BOOL override_logfile;
38
39 /* Read some data from a client connection */
40
41 static void child_read_request(struct winbindd_cli_state *state)
42 {
43         ssize_t len;
44
45         /* Read data */
46
47         len = read_data(state->sock, (char *)&state->request,
48                         sizeof(state->request));
49
50         if (len != sizeof(state->request)) {
51                 DEBUG(len > 0 ? 0 : 3, ("Got invalid request length: %d\n", (int)len));
52                 state->finished = True;
53                 return;
54         }
55
56         if (state->request.extra_len == 0) {
57                 state->request.extra_data.data = NULL;
58                 return;
59         }
60
61         DEBUG(10, ("Need to read %d extra bytes\n", (int)state->request.extra_len));
62
63         state->request.extra_data.data =
64                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
65
66         if (state->request.extra_data.data == NULL) {
67                 DEBUG(0, ("malloc failed\n"));
68                 state->finished = True;
69                 return;
70         }
71
72         /* Ensure null termination */
73         state->request.extra_data.data[state->request.extra_len] = '\0';
74
75         len = read_data(state->sock, state->request.extra_data.data,
76                         state->request.extra_len);
77
78         if (len != state->request.extra_len) {
79                 DEBUG(0, ("Could not read extra data\n"));
80                 state->finished = True;
81                 return;
82         }
83 }
84
85 /*
86  * Machinery for async requests sent to children. You set up a
87  * winbindd_request, select a child to query, and issue a async_request
88  * call. When the request is completed, the callback function you specified is
89  * called back with the private pointer you gave to async_request.
90  */
91
92 struct winbindd_async_request {
93         struct winbindd_async_request *next, *prev;
94         TALLOC_CTX *mem_ctx;
95         struct winbindd_child *child;
96         struct winbindd_request *request;
97         struct winbindd_response *response;
98         void (*continuation)(void *private_data, BOOL success);
99         struct timed_event *reply_timeout_event;
100         void *private_data;
101 };
102
103 static void async_main_request_sent(void *private_data, BOOL success);
104 static void async_request_sent(void *private_data, BOOL success);
105 static void async_reply_recv(void *private_data, BOOL success);
106 static void schedule_async_request(struct winbindd_child *child);
107
108 void async_request(TALLOC_CTX *mem_ctx, struct winbindd_child *child,
109                    struct winbindd_request *request,
110                    struct winbindd_response *response,
111                    void (*continuation)(void *private_data, BOOL success),
112                    void *private_data)
113 {
114         struct winbindd_async_request *state;
115
116         SMB_ASSERT(continuation != NULL);
117
118         state = TALLOC_P(mem_ctx, struct winbindd_async_request);
119
120         if (state == NULL) {
121                 DEBUG(0, ("talloc failed\n"));
122                 continuation(private_data, False);
123                 return;
124         }
125
126         state->mem_ctx = mem_ctx;
127         state->child = child;
128         state->request = request;
129         state->response = response;
130         state->continuation = continuation;
131         state->private_data = private_data;
132
133         DLIST_ADD_END(child->requests, state, struct winbindd_async_request *);
134
135         schedule_async_request(child);
136
137         return;
138 }
139
140 static void async_main_request_sent(void *private_data, BOOL success)
141 {
142         struct winbindd_async_request *state =
143                 talloc_get_type_abort(private_data, struct winbindd_async_request);
144
145         if (!success) {
146                 DEBUG(5, ("Could not send async request\n"));
147
148                 state->response->length = sizeof(struct winbindd_response);
149                 state->response->result = WINBINDD_ERROR;
150                 state->continuation(state->private_data, False);
151                 return;
152         }
153
154         if (state->request->extra_len == 0) {
155                 async_request_sent(private_data, True);
156                 return;
157         }
158
159         setup_async_write(&state->child->event, state->request->extra_data.data,
160                           state->request->extra_len,
161                           async_request_sent, state);
162 }
163
164 /****************************************************************
165  Handler triggered if the child winbindd doesn't respond within
166  a given timeout.
167 ****************************************************************/
168
169 static void async_request_timeout_handler(struct event_context *ctx,
170                                         struct timed_event *te,
171                                         const struct timeval *now,
172                                         void *private_data)
173 {
174         struct winbindd_async_request *state =
175                 talloc_get_type_abort(private_data, struct winbindd_async_request);
176
177         /* Deal with the reply - set to error. */
178
179         async_reply_recv(private_data, False);
180
181         DEBUG(0,("async_request_timeout_handler: child pid %u is not responding. "
182                 "Closing connection to it.\n",
183                 state->child->pid ));
184
185         /* Send kill signal to child. */
186         kill(state->child->pid, SIGTERM);
187
188         /* 
189          * Close the socket to the child.
190          */
191
192         winbind_child_died(state->child->pid);
193 }
194
195 static void async_request_sent(void *private_data_data, BOOL success)
196 {
197         uint32_t timeout = 30;
198         struct winbindd_async_request *state =
199                 talloc_get_type_abort(private_data_data, struct winbindd_async_request);
200
201         if (!success) {
202                 DEBUG(5, ("Could not send async request\n"));
203
204                 state->response->length = sizeof(struct winbindd_response);
205                 state->response->result = WINBINDD_ERROR;
206                 state->continuation(state->private_data, False);
207                 return;
208         }
209
210         /* Request successfully sent to the child, setup the wait for reply */
211
212         setup_async_read(&state->child->event,
213                          &state->response->result,
214                          sizeof(state->response->result),
215                          async_reply_recv, state);
216
217         /* 
218          * Normal timeouts are 30s, but auth requests may take a long
219          * time to timeout.
220          */
221
222         if (state->request->cmd == WINBINDD_PAM_AUTH ||
223                         state->request->cmd == WINBINDD_PAM_AUTH_CRAP ) {
224
225                 timeout = 300;
226         }
227
228         /* 
229          * Set up a timeout of 30 seconds for the response.
230          * If we don't get it close the child socket and
231          * report failure.
232          */
233
234         state->reply_timeout_event = event_add_timed(winbind_event_context(),
235                                                         NULL,
236                                                         timeval_current_ofs(timeout,0),
237                                                         "async_request_timeout",
238                                                         async_request_timeout_handler,
239                                                         state);
240         if (!state->reply_timeout_event) {
241                 smb_panic("async_request_sent: failed to add timeout handler.\n");
242         }
243 }
244
245 static void async_reply_recv(void *private_data, BOOL success)
246 {
247         struct winbindd_async_request *state =
248                 talloc_get_type_abort(private_data, struct winbindd_async_request);
249         struct winbindd_child *child = state->child;
250
251         if (state->reply_timeout_event) {
252                 TALLOC_FREE(state->reply_timeout_event);
253         }
254
255         state->response->length = sizeof(struct winbindd_response);
256
257         if (!success) {
258                 DEBUG(5, ("Could not receive async reply\n"));
259
260                 cache_cleanup_response(child->pid);
261                 DLIST_REMOVE(child->requests, state);
262
263                 state->response->result = WINBINDD_ERROR;
264                 state->continuation(state->private_data, False);
265                 return;
266         }
267
268         SMB_ASSERT(cache_retrieve_response(child->pid,
269                                            state->response));
270
271         cache_cleanup_response(child->pid);
272         
273         DLIST_REMOVE(child->requests, state);
274
275         schedule_async_request(child);
276
277         state->continuation(state->private_data, True);
278 }
279
280 static BOOL fork_domain_child(struct winbindd_child *child);
281
282 static void schedule_async_request(struct winbindd_child *child)
283 {
284         struct winbindd_async_request *request = child->requests;
285
286         if (request == NULL) {
287                 return;
288         }
289
290         if (child->event.flags != 0) {
291                 return;         /* Busy */
292         }
293
294         if ((child->pid == 0) && (!fork_domain_child(child))) {
295                 /* Cancel all outstanding requests */
296
297                 while (request != NULL) {
298                         /* request might be free'd in the continuation */
299                         struct winbindd_async_request *next = request->next;
300                         request->continuation(request->private_data, False);
301                         request = next;
302                 }
303                 return;
304         }
305
306         setup_async_write(&child->event, request->request,
307                           sizeof(*request->request),
308                           async_main_request_sent, request);
309
310         return;
311 }
312
313 struct domain_request_state {
314         TALLOC_CTX *mem_ctx;
315         struct winbindd_domain *domain;
316         struct winbindd_request *request;
317         struct winbindd_response *response;
318         void (*continuation)(void *private_data_data, BOOL success);
319         void *private_data_data;
320 };
321
322 static void domain_init_recv(void *private_data_data, BOOL success);
323
324 void async_domain_request(TALLOC_CTX *mem_ctx,
325                           struct winbindd_domain *domain,
326                           struct winbindd_request *request,
327                           struct winbindd_response *response,
328                           void (*continuation)(void *private_data_data, BOOL success),
329                           void *private_data_data)
330 {
331         struct domain_request_state *state;
332
333         if (domain->initialized) {
334                 async_request(mem_ctx, &domain->child, request, response,
335                               continuation, private_data_data);
336                 return;
337         }
338
339         state = TALLOC_P(mem_ctx, struct domain_request_state);
340         if (state == NULL) {
341                 DEBUG(0, ("talloc failed\n"));
342                 continuation(private_data_data, False);
343                 return;
344         }
345
346         state->mem_ctx = mem_ctx;
347         state->domain = domain;
348         state->request = request;
349         state->response = response;
350         state->continuation = continuation;
351         state->private_data_data = private_data_data;
352
353         init_child_connection(domain, domain_init_recv, state);
354 }
355
356 static void recvfrom_child(void *private_data_data, BOOL success)
357 {
358         struct winbindd_cli_state *state =
359                 talloc_get_type_abort(private_data_data, struct winbindd_cli_state);
360         enum winbindd_result result = state->response.result;
361
362         /* This is an optimization: The child has written directly to the
363          * response buffer. The request itself is still in pending state,
364          * state that in the result code. */
365
366         state->response.result = WINBINDD_PENDING;
367
368         if ((!success) || (result != WINBINDD_OK)) {
369                 request_error(state);
370                 return;
371         }
372
373         request_ok(state);
374 }
375
376 void sendto_child(struct winbindd_cli_state *state,
377                   struct winbindd_child *child)
378 {
379         async_request(state->mem_ctx, child, &state->request,
380                       &state->response, recvfrom_child, state);
381 }
382
383 void sendto_domain(struct winbindd_cli_state *state,
384                    struct winbindd_domain *domain)
385 {
386         async_domain_request(state->mem_ctx, domain,
387                              &state->request, &state->response,
388                              recvfrom_child, state);
389 }
390
391 static void domain_init_recv(void *private_data_data, BOOL success)
392 {
393         struct domain_request_state *state =
394                 talloc_get_type_abort(private_data_data, struct domain_request_state);
395
396         if (!success) {
397                 DEBUG(5, ("Domain init returned an error\n"));
398                 state->continuation(state->private_data_data, False);
399                 return;
400         }
401
402         async_request(state->mem_ctx, &state->domain->child,
403                       state->request, state->response,
404                       state->continuation, state->private_data_data);
405 }
406
407 struct winbindd_child_dispatch_table {
408         enum winbindd_cmd cmd;
409         enum winbindd_result (*fn)(struct winbindd_domain *domain,
410                                    struct winbindd_cli_state *state);
411         const char *winbindd_cmd_name;
412 };
413
414 static struct winbindd_child_dispatch_table child_dispatch_table[] = {
415         
416         { WINBINDD_LOOKUPSID,            winbindd_dual_lookupsid,             "LOOKUPSID" },
417         { WINBINDD_LOOKUPNAME,           winbindd_dual_lookupname,            "LOOKUPNAME" },
418         { WINBINDD_LOOKUPRIDS,           winbindd_dual_lookuprids,            "LOOKUPRIDS" },
419         { WINBINDD_LIST_TRUSTDOM,        winbindd_dual_list_trusted_domains,  "LIST_TRUSTDOM" },
420         { WINBINDD_INIT_CONNECTION,      winbindd_dual_init_connection,       "INIT_CONNECTION" },
421         { WINBINDD_GETDCNAME,            winbindd_dual_getdcname,             "GETDCNAME" },
422         { WINBINDD_SHOW_SEQUENCE,        winbindd_dual_show_sequence,         "SHOW_SEQUENCE" },
423         { WINBINDD_PAM_AUTH,             winbindd_dual_pam_auth,              "PAM_AUTH" },
424         { WINBINDD_PAM_AUTH_CRAP,        winbindd_dual_pam_auth_crap,         "AUTH_CRAP" },
425         { WINBINDD_PAM_LOGOFF,           winbindd_dual_pam_logoff,            "PAM_LOGOFF" },
426         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP,winbindd_dual_pam_chng_pswd_auth_crap,"CHNG_PSWD_AUTH_CRAP" },
427         { WINBINDD_PAM_CHAUTHTOK,        winbindd_dual_pam_chauthtok,         "PAM_CHAUTHTOK" },
428         { WINBINDD_CHECK_MACHACC,        winbindd_dual_check_machine_acct,    "CHECK_MACHACC" },
429         { WINBINDD_DUAL_SID2UID,         winbindd_dual_sid2uid,               "DUAL_SID2UID" },
430         { WINBINDD_DUAL_SID2GID,         winbindd_dual_sid2gid,               "DUAL_SID2GID" },
431 #if 0   /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
432         { WINBINDD_DUAL_SIDS2XIDS,       winbindd_dual_sids2xids,             "DUAL_SIDS2XIDS" },
433 #endif  /* end DISABLED */
434         { WINBINDD_DUAL_UID2SID,         winbindd_dual_uid2sid,               "DUAL_UID2SID" },
435         { WINBINDD_DUAL_GID2SID,         winbindd_dual_gid2sid,               "DUAL_GID2SID" },
436         { WINBINDD_DUAL_UID2NAME,        winbindd_dual_uid2name,              "DUAL_UID2NAME" },
437         { WINBINDD_DUAL_NAME2UID,        winbindd_dual_name2uid,              "DUAL_NAME2UID" },
438         { WINBINDD_DUAL_GID2NAME,        winbindd_dual_gid2name,              "DUAL_GID2NAME" },
439         { WINBINDD_DUAL_NAME2GID,        winbindd_dual_name2gid,              "DUAL_NAME2GID" },
440         { WINBINDD_DUAL_SET_MAPPING,     winbindd_dual_set_mapping,           "DUAL_SET_MAPPING" },
441         { WINBINDD_DUAL_SET_HWM,         winbindd_dual_set_hwm,               "DUAL_SET_HWMS" },
442         { WINBINDD_DUAL_DUMP_MAPS,       winbindd_dual_dump_maps,             "DUAL_DUMP_MAPS" },
443         { WINBINDD_DUAL_USERINFO,        winbindd_dual_userinfo,              "DUAL_USERINFO" },
444         { WINBINDD_ALLOCATE_UID,         winbindd_dual_allocate_uid,          "ALLOCATE_UID" },
445         { WINBINDD_ALLOCATE_GID,         winbindd_dual_allocate_gid,          "ALLOCATE_GID" },
446         { WINBINDD_GETUSERDOMGROUPS,     winbindd_dual_getuserdomgroups,      "GETUSERDOMGROUPS" },
447         { WINBINDD_DUAL_GETSIDALIASES,   winbindd_dual_getsidaliases,         "GETSIDALIASES" },
448         { WINBINDD_CCACHE_NTLMAUTH,      winbindd_dual_ccache_ntlm_auth,      "CCACHE_NTLM_AUTH" },
449         /* End of list */
450
451         { WINBINDD_NUM_CMDS, NULL, "NONE" }
452 };
453
454 static void child_process_request(struct winbindd_domain *domain,
455                                   struct winbindd_cli_state *state)
456 {
457         struct winbindd_child_dispatch_table *table;
458
459         /* Free response data - we may be interrupted and receive another
460            command before being able to send this data off. */
461
462         state->response.result = WINBINDD_ERROR;
463         state->response.length = sizeof(struct winbindd_response);
464
465         state->mem_ctx = talloc_init("winbind request");
466         if (state->mem_ctx == NULL)
467                 return;
468
469         /* Process command */
470
471         for (table = child_dispatch_table; table->fn; table++) {
472                 if (state->request.cmd == table->cmd) {
473                         DEBUG(10,("process_request: request fn %s\n",
474                                   table->winbindd_cmd_name ));
475                         state->response.result = table->fn(domain, state);
476                         break;
477                 }
478         }
479
480         if (!table->fn) {
481                 DEBUG(10,("process_request: unknown request fn number %d\n",
482                           (int)state->request.cmd ));
483                 state->response.result = WINBINDD_ERROR;
484         }
485
486         talloc_destroy(state->mem_ctx);
487 }
488
489 void setup_domain_child(struct winbindd_domain *domain,
490                         struct winbindd_child *child,
491                         const char *explicit_logfile)
492 {
493         if (explicit_logfile != NULL) {
494                 pstr_sprintf(child->logfilename, "%s/log.winbindd-%s",
495                              dyn_LOGFILEBASE, explicit_logfile);
496         } else if (domain != NULL) {
497                 pstr_sprintf(child->logfilename, "%s/log.wb-%s",
498                              dyn_LOGFILEBASE, domain->name);
499         } else {
500                 smb_panic("Internal error: domain == NULL && "
501                           "explicit_logfile == NULL");
502         }
503
504         child->domain = domain;
505 }
506
507 struct winbindd_child *children = NULL;
508
509 void winbind_child_died(pid_t pid)
510 {
511         struct winbindd_child *child;
512
513         for (child = children; child != NULL; child = child->next) {
514                 if (child->pid == pid) {
515                         break;
516                 }
517         }
518
519         if (child == NULL) {
520                 DEBUG(0, ("Unknown child %d died!\n", pid));
521                 return;
522         }
523
524         remove_fd_event(&child->event);
525         close(child->event.fd);
526         child->event.fd = 0;
527         child->event.flags = 0;
528         child->pid = 0;
529
530         schedule_async_request(child);
531 }
532
533 /* Ensure any negative cache entries with the netbios or realm names are removed. */
534
535 void winbindd_flush_negative_conn_cache(struct winbindd_domain *domain)
536 {
537         flush_negative_conn_cache_for_domain(domain->name);
538         if (*domain->alt_name) {
539                 flush_negative_conn_cache_for_domain(domain->alt_name);
540         }
541 }
542
543 /* Set our domains as offline and forward the offline message to our children. */
544
545 void winbind_msg_offline(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_offline: got offline message.\n"));
555
556         if (!lp_winbind_offline_logon()) {
557                 DEBUG(10,("winbind_msg_offline: rejecting offline message.\n"));
558                 return;
559         }
560
561         /* Set our global state as offline. */
562         if (!set_global_winbindd_state_offline()) {
563                 DEBUG(10,("winbind_msg_offline: offline request failed.\n"));
564                 return;
565         }
566
567         /* Set all our domains as offline. */
568         for (domain = domain_list(); domain; domain = domain->next) {
569                 if (domain->internal) {
570                         continue;
571                 }
572                 DEBUG(5,("winbind_msg_offline: marking %s offline.\n", domain->name));
573                 set_domain_offline(domain);
574         }
575
576         for (child = children; child != NULL; child = child->next) {
577                 /* Don't send message to idmap child.  We've already
578                    done so above. */
579                 if (!child->domain || (child == idmap_child())) {
580                         continue;
581                 }
582
583                 /* Or internal domains (this should not be possible....) */
584                 if (child->domain->internal) {
585                         continue;
586                 }
587
588                 /* Each winbindd child should only process requests for one domain - make sure
589                    we only set it online / offline for that domain. */
590
591                 DEBUG(10,("winbind_msg_offline: sending message to pid %u for domain %s.\n",
592                         (unsigned int)child->pid, domain->name ));
593
594                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
595                                    MSG_WINBIND_OFFLINE,
596                                    (uint8 *)child->domain->name,
597                                    strlen(child->domain->name)+1);
598         }
599 }
600
601 /* Set our domains as online and forward the online message to our children. */
602
603 void winbind_msg_online(struct messaging_context *msg_ctx,
604                         void *private_data,
605                         uint32_t msg_type,
606                         struct server_id server_id,
607                         DATA_BLOB *data)
608 {
609         struct winbindd_child *child;
610         struct winbindd_domain *domain;
611
612         DEBUG(10,("winbind_msg_online: got online message.\n"));
613
614         if (!lp_winbind_offline_logon()) {
615                 DEBUG(10,("winbind_msg_online: rejecting online message.\n"));
616                 return;
617         }
618
619         /* Set our global state as online. */
620         set_global_winbindd_state_online();
621
622         smb_nscd_flush_user_cache();
623         smb_nscd_flush_group_cache();
624
625         /* Set all our domains as online. */
626         for (domain = domain_list(); domain; domain = domain->next) {
627                 if (domain->internal) {
628                         continue;
629                 }
630                 DEBUG(5,("winbind_msg_online: requesting %s to go online.\n", domain->name));
631
632                 winbindd_flush_negative_conn_cache(domain);
633                 set_domain_online_request(domain);
634
635                 /* Send an online message to the idmap child when our
636                    primary domain comes back online */
637
638                 if ( domain->primary ) {
639                         struct winbindd_child *idmap = idmap_child();
640                         
641                         if ( idmap->pid != 0 ) {
642                                 messaging_send_buf(msg_ctx,
643                                                    pid_to_procid(idmap->pid), 
644                                                    MSG_WINBIND_ONLINE,
645                                                    (uint8 *)domain->name,
646                                                    strlen(domain->name)+1);
647                         }
648                         
649                 }
650         }
651
652         for (child = children; child != NULL; child = child->next) {
653                 /* Don't send message to idmap child. */
654                 if (!child->domain || (child == idmap_child())) {
655                         continue;
656                 }
657
658                 /* Or internal domains (this should not be possible....) */
659                 if (child->domain->internal) {
660                         continue;
661                 }
662
663                 /* Each winbindd child should only process requests for one domain - make sure
664                    we only set it online / offline for that domain. */
665
666                 DEBUG(10,("winbind_msg_online: sending message to pid %u for domain %s.\n",
667                         (unsigned int)child->pid, child->domain->name ));
668
669                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
670                                    MSG_WINBIND_ONLINE,
671                                    (uint8 *)child->domain->name,
672                                    strlen(child->domain->name)+1);
673         }
674 }
675
676 /* Forward the online/offline messages to our children. */
677 void winbind_msg_onlinestatus(struct messaging_context *msg_ctx,
678                               void *private_data,
679                               uint32_t msg_type,
680                               struct server_id server_id,
681                               DATA_BLOB *data)
682 {
683         struct winbindd_child *child;
684
685         DEBUG(10,("winbind_msg_onlinestatus: got onlinestatus message.\n"));
686
687         for (child = children; child != NULL; child = child->next) {
688                 if (child->domain && child->domain->primary) {
689                         DEBUG(10,("winbind_msg_onlinestatus: "
690                                   "sending message to pid %u of primary domain.\n",
691                                   (unsigned int)child->pid));
692                         messaging_send_buf(msg_ctx, pid_to_procid(child->pid), 
693                                            MSG_WINBIND_ONLINESTATUS,
694                                            (uint8 *)data->data,
695                                            data->length);
696                         break;
697                 }
698         }
699 }
700
701
702 static void account_lockout_policy_handler(struct event_context *ctx,
703                                            struct timed_event *te,
704                                            const struct timeval *now,
705                                            void *private_data)
706 {
707         struct winbindd_child *child =
708                 (struct winbindd_child *)private_data;
709         TALLOC_CTX *mem_ctx = NULL;
710         struct winbindd_methods *methods;
711         SAM_UNK_INFO_12 lockout_policy;
712         NTSTATUS result;
713
714         DEBUG(10,("account_lockout_policy_handler called\n"));
715
716         if (child->lockout_policy_event) {
717                 TALLOC_FREE(child->lockout_policy_event);
718         }
719
720         if ( !winbindd_can_contact_domain( child->domain ) ) {
721                 DEBUG(10,("account_lockout_policy_handler: Removing myself since I "
722                           "do not have an incoming trust to domain %s\n", 
723                           child->domain->name));
724
725                 return;         
726         }
727
728         methods = child->domain->methods;
729
730         mem_ctx = talloc_init("account_lockout_policy_handler ctx");
731         if (!mem_ctx) {
732                 result = NT_STATUS_NO_MEMORY;
733         } else {
734                 result = methods->lockout_policy(child->domain, mem_ctx, &lockout_policy);
735         }
736
737         talloc_destroy(mem_ctx);
738
739         if (!NT_STATUS_IS_OK(result)) {
740                 DEBUG(10,("account_lockout_policy_handler: lockout_policy failed error %s\n",
741                          nt_errstr(result)));
742         }
743
744         child->lockout_policy_event = event_add_timed(winbind_event_context(), NULL,
745                                                       timeval_current_ofs(3600, 0),
746                                                       "account_lockout_policy_handler",
747                                                       account_lockout_policy_handler,
748                                                       child);
749 }
750
751 /* Deal with a request to go offline. */
752
753 static void child_msg_offline(struct messaging_context *msg,
754                               void *private_data,
755                               uint32_t msg_type,
756                               struct server_id server_id,
757                               DATA_BLOB *data)
758 {
759         struct winbindd_domain *domain;
760         const char *domainname = (const char *)data->data;
761
762         if (data->data == NULL || data->length == 0) {
763                 return;
764         }
765
766         DEBUG(5,("child_msg_offline received for domain %s.\n", domainname));
767
768         if (!lp_winbind_offline_logon()) {
769                 DEBUG(10,("child_msg_offline: rejecting offline message.\n"));
770                 return;
771         }
772
773         /* Mark the requested domain offline. */
774
775         for (domain = domain_list(); domain; domain = domain->next) {
776                 if (domain->internal) {
777                         continue;
778                 }
779                 if (strequal(domain->name, domainname)) {
780                         DEBUG(5,("child_msg_offline: marking %s offline.\n", domain->name));
781                         set_domain_offline(domain);
782                 }
783         }
784 }
785
786 /* Deal with a request to go online. */
787
788 static void child_msg_online(struct messaging_context *msg,
789                              void *private_data,
790                              uint32_t msg_type,
791                              struct server_id server_id,
792                              DATA_BLOB *data)
793 {
794         struct winbindd_domain *domain;
795         const char *domainname = (const char *)data->data;
796
797         if (data->data == NULL || data->length == 0) {
798                 return;
799         }
800
801         DEBUG(5,("child_msg_online received for domain %s.\n", domainname));
802
803         if (!lp_winbind_offline_logon()) {
804                 DEBUG(10,("child_msg_online: rejecting online message.\n"));
805                 return;
806         }
807
808         /* Set our global state as online. */
809         set_global_winbindd_state_online();
810
811         /* Try and mark everything online - delete any negative cache entries
812            to force a reconnect now. */
813
814         for (domain = domain_list(); domain; domain = domain->next) {
815                 if (domain->internal) {
816                         continue;
817                 }
818                 if (strequal(domain->name, domainname)) {
819                         DEBUG(5,("child_msg_online: requesting %s to go online.\n", domain->name));
820                         winbindd_flush_negative_conn_cache(domain);
821                         set_domain_online_request(domain);
822                 }
823         }
824 }
825
826 static const char *collect_onlinestatus(TALLOC_CTX *mem_ctx)
827 {
828         struct winbindd_domain *domain;
829         char *buf = NULL;
830
831         if ((buf = talloc_asprintf(mem_ctx, "global:%s ", 
832                                    get_global_winbindd_state_offline() ? 
833                                    "Offline":"Online")) == NULL) {
834                 return NULL;
835         }
836
837         for (domain = domain_list(); domain; domain = domain->next) {
838                 if ((buf = talloc_asprintf_append(buf, "%s:%s ", 
839                                                   domain->name, 
840                                                   domain->online ?
841                                                   "Online":"Offline")) == NULL) {
842                         return NULL;
843                 }
844         }
845
846         buf = talloc_asprintf_append(buf, "\n");
847
848         DEBUG(5,("collect_onlinestatus: %s", buf));
849
850         return buf;
851 }
852
853 static void child_msg_onlinestatus(struct messaging_context *msg_ctx,
854                                    void *private_data,
855                                    uint32_t msg_type,
856                                    struct server_id server_id,
857                                    DATA_BLOB *data)
858 {
859         TALLOC_CTX *mem_ctx;
860         const char *message;
861         struct server_id *sender;
862         
863         DEBUG(5,("winbind_msg_onlinestatus received.\n"));
864
865         if (!data->data) {
866                 return;
867         }
868
869         sender = (struct server_id *)data->data;
870
871         mem_ctx = talloc_init("winbind_msg_onlinestatus");
872         if (mem_ctx == NULL) {
873                 return;
874         }
875         
876         message = collect_onlinestatus(mem_ctx);
877         if (message == NULL) {
878                 talloc_destroy(mem_ctx);
879                 return;
880         }
881
882         messaging_send_buf(msg_ctx, *sender, MSG_WINBIND_ONLINESTATUS, 
883                            (uint8 *)message, strlen(message) + 1);
884
885         talloc_destroy(mem_ctx);
886 }
887
888 static BOOL fork_domain_child(struct winbindd_child *child)
889 {
890         int fdpair[2];
891         struct winbindd_cli_state state;
892         struct winbindd_domain *domain;
893
894         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair) != 0) {
895                 DEBUG(0, ("Could not open child pipe: %s\n",
896                           strerror(errno)));
897                 return False;
898         }
899
900         ZERO_STRUCT(state);
901         state.pid = sys_getpid();
902
903         /* Stop zombies */
904         CatchChild();
905
906         child->pid = sys_fork();
907
908         if (child->pid == -1) {
909                 DEBUG(0, ("Could not fork: %s\n", strerror(errno)));
910                 return False;
911         }
912
913         if (child->pid != 0) {
914                 /* Parent */
915                 close(fdpair[0]);
916                 child->next = child->prev = NULL;
917                 DLIST_ADD(children, child);
918                 child->event.fd = fdpair[1];
919                 child->event.flags = 0;
920                 child->requests = NULL;
921                 add_fd_event(&child->event);
922                 return True;
923         }
924
925         /* Child */
926
927         state.sock = fdpair[0];
928         close(fdpair[1]);
929
930         /* tdb needs special fork handling */
931         if (tdb_reopen_all(1) == -1) {
932                 DEBUG(0,("tdb_reopen_all failed.\n"));
933                 _exit(0);
934         }
935
936         close_conns_after_fork();
937
938         if (!override_logfile) {
939                 lp_set_logfile(child->logfilename);
940                 reopen_logs();
941         }
942
943         /*
944          * For clustering, we need to re-init our ctdbd connection after the
945          * fork
946          */
947         if (!NT_STATUS_IS_OK(messaging_reinit(winbind_messaging_context())))
948                 exit(1);
949
950         /* Don't handle the same messages as our parent. */
951         messaging_deregister(winbind_messaging_context(),
952                              MSG_SMB_CONF_UPDATED, NULL);
953         messaging_deregister(winbind_messaging_context(),
954                              MSG_SHUTDOWN, NULL);
955         messaging_deregister(winbind_messaging_context(),
956                              MSG_WINBIND_OFFLINE, NULL);
957         messaging_deregister(winbind_messaging_context(),
958                              MSG_WINBIND_ONLINE, NULL);
959         messaging_deregister(winbind_messaging_context(),
960                              MSG_WINBIND_ONLINESTATUS, NULL);
961
962         /* Handle online/offline messages. */
963         messaging_register(winbind_messaging_context(), NULL,
964                            MSG_WINBIND_OFFLINE, child_msg_offline);
965         messaging_register(winbind_messaging_context(), NULL,
966                            MSG_WINBIND_ONLINE, child_msg_online);
967         messaging_register(winbind_messaging_context(), NULL,
968                            MSG_WINBIND_ONLINESTATUS, child_msg_onlinestatus);
969
970         if ( child->domain ) {
971                 child->domain->startup = True;
972                 child->domain->startup_time = time(NULL);
973         }
974
975         /* Ensure we have no pending check_online events other
976            than one for this domain. */
977
978         for (domain = domain_list(); domain; domain = domain->next) {
979                 if (domain != child->domain) {
980                         if (domain->check_online_event) {
981                                 TALLOC_FREE(domain->check_online_event);
982                         }
983                 }
984         }
985
986         /* Ensure we're not handling an event inherited from
987            our parent. */
988
989         cancel_named_event(winbind_event_context(),
990                            "krb5_ticket_refresh_handler");
991
992         /* We might be in the idmap child...*/
993         if (child->domain && !(child->domain->internal) &&
994             lp_winbind_offline_logon()) {
995
996                 set_domain_online_request(child->domain);
997
998                 child->lockout_policy_event = event_add_timed(
999                         winbind_event_context(), NULL, timeval_zero(),
1000                         "account_lockout_policy_handler",
1001                         account_lockout_policy_handler,
1002                         child);
1003         }
1004
1005         while (1) {
1006
1007                 int ret;
1008                 fd_set read_fds;
1009                 struct timeval t;
1010                 struct timeval *tp;
1011                 struct timeval now;
1012
1013                 /* free up any talloc memory */
1014                 lp_TALLOC_FREE();
1015                 main_loop_TALLOC_FREE();
1016
1017                 run_events(winbind_event_context(), 0, NULL, NULL);
1018
1019                 GetTimeOfDay(&now);
1020
1021                 if (child->domain && child->domain->startup &&
1022                                 (now.tv_sec > child->domain->startup_time + 30)) {
1023                         /* No longer in "startup" mode. */
1024                         DEBUG(10,("fork_domain_child: domain %s no longer in 'startup' mode.\n",
1025                                 child->domain->name ));
1026                         child->domain->startup = False;
1027                 }
1028
1029                 tp = get_timed_events_timeout(winbind_event_context(), &t);
1030                 if (tp) {
1031                         DEBUG(11,("select will use timeout of %u.%u seconds\n",
1032                                 (unsigned int)tp->tv_sec, (unsigned int)tp->tv_usec ));
1033                 }
1034
1035                 /* Handle messages */
1036
1037                 message_dispatch(winbind_messaging_context());
1038
1039                 FD_ZERO(&read_fds);
1040                 FD_SET(state.sock, &read_fds);
1041
1042                 ret = sys_select(state.sock + 1, &read_fds, NULL, NULL, tp);
1043
1044                 if (ret == 0) {
1045                         DEBUG(11,("nothing is ready yet, continue\n"));
1046                         continue;
1047                 }
1048
1049                 if (ret == -1 && errno == EINTR) {
1050                         /* We got a signal - continue. */
1051                         continue;
1052                 }
1053
1054                 if (ret == -1 && errno != EINTR) {
1055                         DEBUG(0,("select error occured\n"));
1056                         perror("select");
1057                         return False;
1058                 }
1059
1060                 /* fetch a request from the main daemon */
1061                 child_read_request(&state);
1062
1063                 if (state.finished) {
1064                         /* we lost contact with our parent */
1065                         exit(0);
1066                 }
1067
1068                 DEBUG(4,("child daemon request %d\n", (int)state.request.cmd));
1069
1070                 ZERO_STRUCT(state.response);
1071                 state.request.null_term = '\0';
1072                 child_process_request(child->domain, &state);
1073
1074                 SAFE_FREE(state.request.extra_data.data);
1075
1076                 cache_store_response(sys_getpid(), &state.response);
1077
1078                 SAFE_FREE(state.response.extra_data.data);
1079
1080                 /* We just send the result code back, the result
1081                  * structure needs to be fetched via the
1082                  * winbindd_cache. Hmm. That needs fixing... */
1083
1084                 if (write_data(state.sock,
1085                                (const char *)&state.response.result,
1086                                sizeof(state.response.result)) !=
1087                     sizeof(state.response.result)) {
1088                         DEBUG(0, ("Could not write result\n"));
1089                         exit(1);
1090                 }
1091         }
1092 }