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