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