]> git.samba.org - metze/samba/wip.git/blob - source3/winbindd/winbindd.c
Prevent winbindd from segfaulting due to corrupted cache tdb.
[metze/samba/wip.git] / source3 / winbindd / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000-2002
7    Copyright (C) Andrew Tridgell 2002
8    Copyright (C) Jelmer Vernooij 2003
9    Copyright (C) Volker Lendecke 2004
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 bool opt_nocache = False;
32 static bool interactive = False;
33
34 extern bool override_logfile;
35
36 struct event_context *winbind_event_context(void)
37 {
38         static struct event_context *ctx;
39
40         if (!ctx && !(ctx = event_context_init(NULL))) {
41                 smb_panic("Could not init winbind event context");
42         }
43         return ctx;
44 }
45
46 struct messaging_context *winbind_messaging_context(void)
47 {
48         static struct messaging_context *ctx;
49
50         if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
51                                            winbind_event_context()))) {
52                 smb_panic("Could not init winbind messaging context");
53         }
54         return ctx;
55 }
56
57 /* Reload configuration */
58
59 static bool reload_services_file(void)
60 {
61         bool ret;
62
63         if (lp_loaded()) {
64                 const char *fname = lp_configfile();
65
66                 if (file_exist(fname,NULL) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
67                         set_dyn_CONFIGFILE(fname);
68                 }
69         }
70
71         reopen_logs();
72         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
73
74         reopen_logs();
75         load_interfaces();
76
77         return(ret);
78 }
79
80
81 /**************************************************************************** **
82  Handle a fault..
83  **************************************************************************** */
84
85 static void fault_quit(void)
86 {
87         dump_core();
88 }
89
90 static void winbindd_status(void)
91 {
92         struct winbindd_cli_state *tmp;
93
94         DEBUG(0, ("winbindd status:\n"));
95
96         /* Print client state information */
97         
98         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
99         
100         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
101                 DEBUG(2, ("\tclient list:\n"));
102                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
103                         DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
104                                   (unsigned long)tmp->pid, tmp->sock));
105                 }
106         }
107 }
108
109 /* Print winbindd status to log file */
110
111 static void print_winbindd_status(void)
112 {
113         winbindd_status();
114 }
115
116 /* Flush client cache */
117
118 static void flush_caches(void)
119 {
120         /* We need to invalidate cached user list entries on a SIGHUP 
121            otherwise cached access denied errors due to restrict anonymous
122            hang around until the sequence number changes. */
123
124         if (wcache_invalidate_cache() < 0) {
125                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
126                 /* Close the cache to be able to valdite the cache */
127                 close_winbindd_cache();
128                 /*
129                  * Ensure all cache and idmap caches are consistent
130                  * before we initialize the cache again.
131                  */
132                 if (winbindd_validate_cache() < 0) {
133                         DEBUG(0, ("corrupted tdb found, trying to restore backup\n"));
134                 }
135
136                 /* Initialize cache again. */
137                 if (!initialize_winbindd_cache()) {
138                         exit(1);
139                 }
140         }
141 }
142
143 /* Handle the signal by unlinking socket and exiting */
144
145 static void terminate(void)
146 {
147         char *path = NULL;
148
149         /* Remove socket file */
150         if (asprintf(&path, "%s/%s",
151                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
152                 unlink(path);
153                 SAFE_FREE(path);
154         }
155
156         idmap_close();
157         
158         trustdom_cache_shutdown();
159
160 #if 0
161         if (interactive) {
162                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
163                 char *description = talloc_describe_all(mem_ctx);
164
165                 DEBUG(3, ("tallocs left:\n%s\n", description));
166                 talloc_destroy(mem_ctx);
167         }
168 #endif
169
170         exit(0);
171 }
172
173 static bool do_sigterm;
174
175 static void termination_handler(int signum)
176 {
177         do_sigterm = True;
178         sys_select_signal(signum);
179 }
180
181 static bool do_sigusr2;
182
183 static void sigusr2_handler(int signum)
184 {
185         do_sigusr2 = True;
186         sys_select_signal(SIGUSR2);
187 }
188
189 static bool do_sighup;
190
191 static void sighup_handler(int signum)
192 {
193         do_sighup = True;
194         sys_select_signal(SIGHUP);
195 }
196
197 static bool do_sigchld;
198
199 static void sigchld_handler(int signum)
200 {
201         do_sigchld = True;
202         sys_select_signal(SIGCHLD);
203 }
204
205 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
206 static void msg_reload_services(struct messaging_context *msg,
207                                 void *private_data,
208                                 uint32_t msg_type,
209                                 struct server_id server_id,
210                                 DATA_BLOB *data)
211 {
212         /* Flush various caches */
213         flush_caches();
214         reload_services_file();
215 }
216
217 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
218 static void msg_shutdown(struct messaging_context *msg,
219                          void *private_data,
220                          uint32_t msg_type,
221                          struct server_id server_id,
222                          DATA_BLOB *data)
223 {
224         do_sigterm = True;
225 }
226
227
228 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
229                                        void *private_data,
230                                        uint32_t msg_type,
231                                        struct server_id server_id,
232                                        DATA_BLOB *data)
233 {
234         uint8 ret;
235         pid_t child_pid;
236         struct sigaction act;
237         struct sigaction oldact;
238
239         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
240                    "message.\n"));
241
242         /*
243          * call the validation code from a child:
244          * so we don't block the main winbindd and the validation
245          * code can safely use fork/waitpid...
246          */
247         CatchChild();
248         child_pid = sys_fork();
249
250         if (child_pid == -1) {
251                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
252                           strerror(errno)));
253                 return;
254         }
255
256         if (child_pid != 0) {
257                 /* parent */
258                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
259                           "pid %d.\n", child_pid));
260                 return;
261         }
262
263         /* child */
264
265         /* install default SIGCHLD handler: validation code uses fork/waitpid */
266         ZERO_STRUCT(act);
267         act.sa_handler = SIG_DFL;
268 #ifdef SA_RESTART
269         /* We *want* SIGALRM to interrupt a system call. */
270         act.sa_flags = SA_RESTART;
271 #endif
272         sigemptyset(&act.sa_mask);
273         sigaddset(&act.sa_mask,SIGCHLD);
274         sigaction(SIGCHLD,&act,&oldact);
275
276         ret = (uint8)winbindd_validate_cache_nobackup();
277         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
278         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
279                            (size_t)1);
280         _exit(0);
281 }
282
283 static struct winbindd_dispatch_table {
284         enum winbindd_cmd cmd;
285         void (*fn)(struct winbindd_cli_state *state);
286         const char *winbindd_cmd_name;
287 } dispatch_table[] = {
288         
289         /* User functions */
290
291         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
292         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
293
294         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
295         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
296         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
297
298         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
299         { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
300         { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
301           "GETUSERDOMGROUPS" },
302
303         /* Group functions */
304
305         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
306         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
307         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
308         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
309         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
310         { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
311
312         /* PAM auth functions */
313
314         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
315         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
316         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
317         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
318         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
319
320         /* Enumeration functions */
321
322         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
323         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
324         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
325           "LIST_TRUSTDOM" },
326         { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
327
328         /* SID related functions */
329
330         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
331         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
332         { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
333
334         /* Lookup related functions */
335
336         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
337         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
338         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
339         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
340 #if 0   /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
341         { WINBINDD_SIDS_TO_XIDS, winbindd_sids_to_unixids, "SIDS_TO_XIDS" },
342 #endif  /* end DISABLED */
343         { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
344         { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
345         { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
346         { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
347
348         /* Miscellaneous */
349
350         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
351         { WINBINDD_PING, winbindd_ping, "PING" },
352         { WINBINDD_INFO, winbindd_info, "INFO" },
353         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
354           "INTERFACE_VERSION" },
355         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
356         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
357         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
358         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
359           "WINBINDD_PRIV_PIPE_DIR" },
360         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
361         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
362
363         /* Credential cache access */
364         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
365
366         /* WINS functions */
367
368         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
369         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
370         
371         /* End of list */
372
373         { WINBINDD_NUM_CMDS, NULL, "NONE" }
374 };
375
376 static void process_request(struct winbindd_cli_state *state)
377 {
378         struct winbindd_dispatch_table *table = dispatch_table;
379
380         /* Free response data - we may be interrupted and receive another
381            command before being able to send this data off. */
382
383         SAFE_FREE(state->response.extra_data.data);  
384
385         ZERO_STRUCT(state->response);
386
387         state->response.result = WINBINDD_PENDING;
388         state->response.length = sizeof(struct winbindd_response);
389
390         state->mem_ctx = talloc_init("winbind request");
391         if (state->mem_ctx == NULL)
392                 return;
393
394         /* Remember who asked us. */
395         state->pid = state->request.pid;
396
397         /* Process command */
398
399         for (table = dispatch_table; table->fn; table++) {
400                 if (state->request.cmd == table->cmd) {
401                         DEBUG(10,("process_request: request fn %s\n",
402                                   table->winbindd_cmd_name ));
403                         table->fn(state);
404                         break;
405                 }
406         }
407
408         if (!table->fn) {
409                 DEBUG(10,("process_request: unknown request fn number %d\n",
410                           (int)state->request.cmd ));
411                 request_error(state);
412         }
413 }
414
415 /*
416  * A list of file descriptors being monitored by select in the main processing
417  * loop. fd_event->handler is called whenever the socket is readable/writable.
418  */
419
420 static struct fd_event *fd_events = NULL;
421
422 void add_fd_event(struct fd_event *ev)
423 {
424         struct fd_event *match;
425
426         /* only add unique fd_event structs */
427
428         for (match=fd_events; match; match=match->next ) {
429 #ifdef DEVELOPER
430                 SMB_ASSERT( match != ev );
431 #else
432                 if ( match == ev )
433                         return;
434 #endif
435         }
436
437         DLIST_ADD(fd_events, ev);
438 }
439
440 void remove_fd_event(struct fd_event *ev)
441 {
442         DLIST_REMOVE(fd_events, ev);
443 }
444
445 /*
446  * Handler for fd_events to complete a read/write request, set up by
447  * setup_async_read/setup_async_write.
448  */
449
450 static void rw_callback(struct fd_event *event, int flags)
451 {
452         size_t todo;
453         ssize_t done = 0;
454
455         todo = event->length - event->done;
456
457         if (event->flags & EVENT_FD_WRITE) {
458                 SMB_ASSERT(flags == EVENT_FD_WRITE);
459                 done = sys_write(event->fd,
460                                  &((char *)event->data)[event->done],
461                                  todo);
462
463                 if (done <= 0) {
464                         event->flags = 0;
465                         event->finished(event->private_data, False);
466                         return;
467                 }
468         }
469
470         if (event->flags & EVENT_FD_READ) {
471                 SMB_ASSERT(flags == EVENT_FD_READ);
472                 done = sys_read(event->fd, &((char *)event->data)[event->done],
473                                 todo);
474
475                 if (done <= 0) {
476                         event->flags = 0;
477                         event->finished(event->private_data, False);
478                         return;
479                 }
480         }
481
482         event->done += done;
483
484         if (event->done == event->length) {
485                 event->flags = 0;
486                 event->finished(event->private_data, True);
487         }
488 }
489
490 /*
491  * Request an async read/write on a fd_event structure. (*finished) is called
492  * when the request is completed or an error had occurred.
493  */
494
495 void setup_async_read(struct fd_event *event, void *data, size_t length,
496                       void (*finished)(void *private_data, bool success),
497                       void *private_data)
498 {
499         SMB_ASSERT(event->flags == 0);
500         event->data = data;
501         event->length = length;
502         event->done = 0;
503         event->handler = rw_callback;
504         event->finished = finished;
505         event->private_data = private_data;
506         event->flags = EVENT_FD_READ;
507 }
508
509 void setup_async_write(struct fd_event *event, void *data, size_t length,
510                        void (*finished)(void *private_data, bool success),
511                        void *private_data)
512 {
513         SMB_ASSERT(event->flags == 0);
514         event->data = data;
515         event->length = length;
516         event->done = 0;
517         event->handler = rw_callback;
518         event->finished = finished;
519         event->private_data = private_data;
520         event->flags = EVENT_FD_WRITE;
521 }
522
523 /*
524  * This is the main event loop of winbind requests. It goes through a
525  * state-machine of 3 read/write requests, 4 if you have extra data to send.
526  *
527  * An idle winbind client has a read request of 4 bytes outstanding,
528  * finalizing function is request_len_recv, checking the length. request_recv
529  * then processes the packet. The processing function then at some point has
530  * to call request_finished which schedules sending the response.
531  */
532
533 static void request_len_recv(void *private_data, bool success);
534 static void request_recv(void *private_data, bool success);
535 static void request_main_recv(void *private_data, bool success);
536 static void request_finished(struct winbindd_cli_state *state);
537 void request_finished_cont(void *private_data, bool success);
538 static void response_main_sent(void *private_data, bool success);
539 static void response_extra_sent(void *private_data, bool success);
540
541 static void response_extra_sent(void *private_data, bool success)
542 {
543         struct winbindd_cli_state *state =
544                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
545
546         if (state->mem_ctx != NULL) {
547                 talloc_destroy(state->mem_ctx);
548                 state->mem_ctx = NULL;
549         }
550
551         if (!success) {
552                 state->finished = True;
553                 return;
554         }
555
556         SAFE_FREE(state->request.extra_data.data);
557         SAFE_FREE(state->response.extra_data.data);
558
559         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
560                          request_len_recv, state);
561 }
562
563 static void response_main_sent(void *private_data, bool success)
564 {
565         struct winbindd_cli_state *state =
566                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
567
568         if (!success) {
569                 state->finished = True;
570                 return;
571         }
572
573         if (state->response.length == sizeof(state->response)) {
574                 if (state->mem_ctx != NULL) {
575                         talloc_destroy(state->mem_ctx);
576                         state->mem_ctx = NULL;
577                 }
578
579                 setup_async_read(&state->fd_event, &state->request,
580                                  sizeof(uint32), request_len_recv, state);
581                 return;
582         }
583
584         setup_async_write(&state->fd_event, state->response.extra_data.data,
585                           state->response.length - sizeof(state->response),
586                           response_extra_sent, state);
587 }
588
589 static void request_finished(struct winbindd_cli_state *state)
590 {
591         setup_async_write(&state->fd_event, &state->response,
592                           sizeof(state->response), response_main_sent, state);
593 }
594
595 void request_error(struct winbindd_cli_state *state)
596 {
597         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
598         state->response.result = WINBINDD_ERROR;
599         request_finished(state);
600 }
601
602 void request_ok(struct winbindd_cli_state *state)
603 {
604         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
605         state->response.result = WINBINDD_OK;
606         request_finished(state);
607 }
608
609 void request_finished_cont(void *private_data, bool success)
610 {
611         struct winbindd_cli_state *state =
612                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
613
614         if (success)
615                 request_ok(state);
616         else
617                 request_error(state);
618 }
619
620 static void request_len_recv(void *private_data, bool success)
621 {
622         struct winbindd_cli_state *state =
623                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
624
625         if (!success) {
626                 state->finished = True;
627                 return;
628         }
629
630         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
631                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
632                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
633                 state->finished = True;
634                 return;
635         }
636
637         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
638                          sizeof(state->request) - sizeof(uint32),
639                          request_main_recv, state);
640 }
641
642 static void request_main_recv(void *private_data, bool success)
643 {
644         struct winbindd_cli_state *state =
645                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
646
647         if (!success) {
648                 state->finished = True;
649                 return;
650         }
651
652         if (state->request.extra_len == 0) {
653                 state->request.extra_data.data = NULL;
654                 request_recv(state, True);
655                 return;
656         }
657
658         if ((!state->privileged) &&
659             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
660                 DEBUG(3, ("Got request with %d bytes extra data on "
661                           "unprivileged socket\n", (int)state->request.extra_len));
662                 state->request.extra_data.data = NULL;
663                 state->finished = True;
664                 return;
665         }
666
667         state->request.extra_data.data =
668                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
669
670         if (state->request.extra_data.data == NULL) {
671                 DEBUG(0, ("malloc failed\n"));
672                 state->finished = True;
673                 return;
674         }
675
676         /* Ensure null termination */
677         state->request.extra_data.data[state->request.extra_len] = '\0';
678
679         setup_async_read(&state->fd_event, state->request.extra_data.data,
680                          state->request.extra_len, request_recv, state);
681 }
682
683 static void request_recv(void *private_data, bool success)
684 {
685         struct winbindd_cli_state *state =
686                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
687
688         if (!success) {
689                 state->finished = True;
690                 return;
691         }
692
693         process_request(state);
694 }
695
696 /* Process a new connection by adding it to the client connection list */
697
698 static void new_connection(int listen_sock, bool privileged)
699 {
700         struct sockaddr_un sunaddr;
701         struct winbindd_cli_state *state;
702         socklen_t len;
703         int sock;
704         
705         /* Accept connection */
706         
707         len = sizeof(sunaddr);
708
709         do {
710                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
711         } while (sock == -1 && errno == EINTR);
712
713         if (sock == -1)
714                 return;
715         
716         DEBUG(6,("accepted socket %d\n", sock));
717         
718         /* Create new connection structure */
719         
720         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
721                 close(sock);
722                 return;
723         }
724         
725         state->sock = sock;
726
727         state->last_access = time(NULL);        
728
729         state->privileged = privileged;
730
731         state->fd_event.fd = state->sock;
732         state->fd_event.flags = 0;
733         add_fd_event(&state->fd_event);
734
735         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
736                          request_len_recv, state);
737
738         /* Add to connection list */
739         
740         winbindd_add_client(state);
741 }
742
743 /* Remove a client connection from client connection list */
744
745 static void remove_client(struct winbindd_cli_state *state)
746 {
747         /* It's a dead client - hold a funeral */
748         
749         if (state == NULL) {
750                 return;
751         }
752                 
753         /* Close socket */
754                 
755         close(state->sock);
756                 
757         /* Free any getent state */
758                 
759         free_getent_state(state->getpwent_state);
760         free_getent_state(state->getgrent_state);
761                 
762         /* We may have some extra data that was not freed if the client was
763            killed unexpectedly */
764
765         SAFE_FREE(state->response.extra_data.data);
766
767         if (state->mem_ctx != NULL) {
768                 talloc_destroy(state->mem_ctx);
769                 state->mem_ctx = NULL;
770         }
771
772         remove_fd_event(&state->fd_event);
773                 
774         /* Remove from list and free */
775                 
776         winbindd_remove_client(state);
777         TALLOC_FREE(state);
778 }
779
780 /* Shutdown client connection which has been idle for the longest time */
781
782 static bool remove_idle_client(void)
783 {
784         struct winbindd_cli_state *state, *remove_state = NULL;
785         time_t last_access = 0;
786         int nidle = 0;
787
788         for (state = winbindd_client_list(); state; state = state->next) {
789                 if (state->response.result != WINBINDD_PENDING &&
790                     !state->getpwent_state && !state->getgrent_state) {
791                         nidle++;
792                         if (!last_access || state->last_access < last_access) {
793                                 last_access = state->last_access;
794                                 remove_state = state;
795                         }
796                 }
797         }
798
799         if (remove_state) {
800                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
801                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
802                 remove_client(remove_state);
803                 return True;
804         }
805
806         return False;
807 }
808
809 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
810    non-forking, non-threaded model which allows us to handle many
811    simultaneous connections while remaining impervious to many denial of
812    service attacks. */
813
814 static void process_loop(void)
815 {
816         struct winbindd_cli_state *state;
817         struct fd_event *ev;
818         fd_set r_fds, w_fds;
819         int maxfd, listen_sock, listen_priv_sock, selret;
820         struct timeval timeout, ev_timeout;
821
822         /* Open Sockets here to get stuff going ASAP */
823         listen_sock = open_winbindd_socket();
824         listen_priv_sock = open_winbindd_priv_socket();
825
826         if (listen_sock == -1 || listen_priv_sock == -1) {
827                 perror("open_winbind_socket");
828                 exit(1);
829         }
830
831         /* We'll be doing this a lot */
832
833         /* Handle messages */
834
835         message_dispatch(winbind_messaging_context());
836
837         run_events(winbind_event_context(), 0, NULL, NULL);
838
839         /* refresh the trusted domain cache */
840
841         rescan_trusted_domains();
842
843         /* Initialise fd lists for select() */
844
845         maxfd = MAX(listen_sock, listen_priv_sock);
846
847         FD_ZERO(&r_fds);
848         FD_ZERO(&w_fds);
849         FD_SET(listen_sock, &r_fds);
850         FD_SET(listen_priv_sock, &r_fds);
851
852         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
853         timeout.tv_usec = 0;
854
855         /* Check for any event timeouts. */
856         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
857                 timeout = timeval_min(&timeout, &ev_timeout);
858         }
859
860         /* Set up client readers and writers */
861
862         state = winbindd_client_list();
863
864         while (state) {
865
866                 struct winbindd_cli_state *next = state->next;
867
868                 /* Dispose of client connection if it is marked as 
869                    finished */ 
870
871                 if (state->finished)
872                         remove_client(state);
873
874                 state = next;
875         }
876
877         for (ev = fd_events; ev; ev = ev->next) {
878                 if (ev->flags & EVENT_FD_READ) {
879                         FD_SET(ev->fd, &r_fds);
880                         maxfd = MAX(ev->fd, maxfd);
881                 }
882                 if (ev->flags & EVENT_FD_WRITE) {
883                         FD_SET(ev->fd, &w_fds);
884                         maxfd = MAX(ev->fd, maxfd);
885                 }
886         }
887
888         /* Call select */
889         
890         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
891
892         if (selret == 0) {
893                 goto no_fds_ready;
894         }
895
896         if (selret == -1) {
897                 if (errno == EINTR) {
898                         goto no_fds_ready;
899                 }
900
901                 /* Select error, something is badly wrong */
902
903                 perror("select");
904                 exit(1);
905         }
906
907         /* selret > 0 */
908
909         ev = fd_events;
910         while (ev != NULL) {
911                 struct fd_event *next = ev->next;
912                 int flags = 0;
913                 if (FD_ISSET(ev->fd, &r_fds))
914                         flags |= EVENT_FD_READ;
915                 if (FD_ISSET(ev->fd, &w_fds))
916                         flags |= EVENT_FD_WRITE;
917                 if (flags)
918                         ev->handler(ev, flags);
919                 ev = next;
920         }
921
922         if (FD_ISSET(listen_sock, &r_fds)) {
923                 while (winbindd_num_clients() >
924                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
925                         DEBUG(5,("winbindd: Exceeding %d client "
926                                  "connections, removing idle "
927                                  "connection.\n",
928                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
929                         if (!remove_idle_client()) {
930                                 DEBUG(0,("winbindd: Exceeding %d "
931                                          "client connections, no idle "
932                                          "connection found\n",
933                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
934                                 break;
935                         }
936                 }
937                 /* new, non-privileged connection */
938                 new_connection(listen_sock, False);
939         }
940             
941         if (FD_ISSET(listen_priv_sock, &r_fds)) {
942                 while (winbindd_num_clients() >
943                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
944                         DEBUG(5,("winbindd: Exceeding %d client "
945                                  "connections, removing idle "
946                                  "connection.\n",
947                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
948                         if (!remove_idle_client()) {
949                                 DEBUG(0,("winbindd: Exceeding %d "
950                                          "client connections, no idle "
951                                          "connection found\n",
952                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
953                                 break;
954                         }
955                 }
956                 /* new, privileged connection */
957                 new_connection(listen_priv_sock, True);
958         }
959
960  no_fds_ready:
961
962 #if 0
963         winbindd_check_cache_size(time(NULL));
964 #endif
965
966         /* Check signal handling things */
967
968         if (do_sigterm)
969                 terminate();
970
971         if (do_sighup) {
972
973                 DEBUG(3, ("got SIGHUP\n"));
974
975                 flush_caches();
976                 reload_services_file();
977
978                 do_sighup = False;
979         }
980
981         if (do_sigusr2) {
982                 print_winbindd_status();
983                 do_sigusr2 = False;
984         }
985
986         if (do_sigchld) {
987                 pid_t pid;
988
989                 do_sigchld = False;
990
991                 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
992                         winbind_child_died(pid);
993                 }
994         }
995 }
996
997 /* Main function */
998
999 int main(int argc, char **argv, char **envp)
1000 {
1001         static bool is_daemon = False;
1002         static bool Fork = True;
1003         static bool log_stdout = False;
1004         static bool no_process_group = False;
1005         enum {
1006                 OPT_DAEMON = 1000,
1007                 OPT_FORK,
1008                 OPT_NO_PROCESS_GROUP,
1009                 OPT_LOG_STDOUT
1010         };
1011         struct poptOption long_options[] = {
1012                 POPT_AUTOHELP
1013                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1014                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1015                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1016                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1017                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1018                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1019                 POPT_COMMON_SAMBA
1020                 POPT_TABLEEND
1021         };
1022         poptContext pc;
1023         int opt;
1024         TALLOC_CTX *frame = talloc_stackframe();
1025
1026         /* glibc (?) likes to print "User defined signal 1" and exit if a
1027            SIGUSR[12] is received before a handler is installed */
1028
1029         CatchSignal(SIGUSR1, SIG_IGN);
1030         CatchSignal(SIGUSR2, SIG_IGN);
1031
1032         fault_setup((void (*)(void *))fault_quit );
1033         dump_core_setup("winbindd");
1034
1035         load_case_tables();
1036
1037         /* Initialise for running in non-root mode */
1038
1039         sec_init();
1040
1041         set_remote_machine_name("winbindd", False);
1042
1043         /* Set environment variable so we don't recursively call ourselves.
1044            This may also be useful interactively. */
1045
1046         if ( !winbind_off() ) {
1047                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1048                 exit(1);
1049         }
1050
1051         /* Initialise samba/rpc client stuff */
1052
1053         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1054
1055         while ((opt = poptGetNextOpt(pc)) != -1) {
1056                 switch (opt) {
1057                         /* Don't become a daemon */
1058                 case OPT_DAEMON:
1059                         is_daemon = True;
1060                         break;
1061                 case 'i':
1062                         interactive = True;
1063                         log_stdout = True;
1064                         Fork = False;
1065                         break;
1066                 case OPT_FORK:
1067                         Fork = false;
1068                         break;
1069                 case OPT_NO_PROCESS_GROUP:
1070                         no_process_group = true;
1071                         break;
1072                 case OPT_LOG_STDOUT:
1073                         log_stdout = true;
1074                         break;
1075                 case 'n':
1076                         opt_nocache = true;
1077                         break;
1078                 default:
1079                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1080                                   poptBadOption(pc, 0), poptStrerror(opt));
1081                         poptPrintUsage(pc, stderr, 0);
1082                         exit(1);
1083                 }
1084         }
1085
1086         if (is_daemon && interactive) {
1087                 d_fprintf(stderr,"\nERROR: "
1088                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1089                 poptPrintUsage(pc, stderr, 0);
1090                 exit(1);
1091         }
1092
1093         if (log_stdout && Fork) {
1094                 d_fprintf(stderr, "\nERROR: "
1095                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1096                 poptPrintUsage(pc, stderr, 0);
1097                 exit(1);
1098         }
1099
1100         poptFreeContext(pc);
1101
1102         if (!override_logfile) {
1103                 char *logfile = NULL;
1104                 if (asprintf(&logfile,"%s/log.winbindd",
1105                                 get_dyn_LOGFILEBASE()) > 0) {
1106                         lp_set_logfile(logfile);
1107                         SAFE_FREE(logfile);
1108                 }
1109         }
1110         setup_logging("winbindd", log_stdout);
1111         reopen_logs();
1112
1113         DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1114         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1115
1116         if (!reload_services_file()) {
1117                 DEBUG(0, ("error opening config file\n"));
1118                 exit(1);
1119         }
1120
1121         if (!directory_exist(lp_lockdir(), NULL)) {
1122                 mkdir(lp_lockdir(), 0755);
1123         }
1124
1125         /* Setup names. */
1126
1127         if (!init_names())
1128                 exit(1);
1129
1130         load_interfaces();
1131
1132         if (!secrets_init()) {
1133
1134                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1135                 return False;
1136         }
1137
1138         /* Enable netbios namecache */
1139
1140         namecache_enable();
1141
1142         /* Winbind daemon initialisation */
1143
1144         if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1145                 DEBUG(1, ("Could not init idmap cache!\n"));            
1146         }
1147
1148         /* Unblock all signals we are interested in as they may have been
1149            blocked by the parent process. */
1150
1151         BlockSignals(False, SIGINT);
1152         BlockSignals(False, SIGQUIT);
1153         BlockSignals(False, SIGTERM);
1154         BlockSignals(False, SIGUSR1);
1155         BlockSignals(False, SIGUSR2);
1156         BlockSignals(False, SIGHUP);
1157         BlockSignals(False, SIGCHLD);
1158
1159         /* Setup signal handlers */
1160         
1161         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
1162         CatchSignal(SIGQUIT, termination_handler);
1163         CatchSignal(SIGTERM, termination_handler);
1164         CatchSignal(SIGCHLD, sigchld_handler);
1165
1166         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1167
1168         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
1169         CatchSignal(SIGHUP, sighup_handler);
1170
1171         if (!interactive)
1172                 become_daemon(Fork, no_process_group);
1173
1174         pidfile_create("winbindd");
1175
1176 #if HAVE_SETPGID
1177         /*
1178          * If we're interactive we want to set our own process group for
1179          * signal management.
1180          */
1181         if (interactive && !no_process_group)
1182                 setpgid( (pid_t)0, (pid_t)0);
1183 #endif
1184
1185         TimeInit();
1186
1187         /* Initialise messaging system */
1188
1189         if (winbind_messaging_context() == NULL) {
1190                 DEBUG(0, ("unable to initialize messaging system\n"));
1191                 exit(1);
1192         }
1193
1194         /*
1195          * Ensure all cache and idmap caches are consistent
1196          * before we startup.
1197          */
1198         if (winbindd_validate_cache() < 0) {
1199                 DEBUG(0, ("corrupted tdb found, trying to restore backup\n"));
1200         }
1201
1202         /* Initialize cache (ensure version is correct). */
1203         if (!initialize_winbindd_cache()) {
1204                 exit(1);
1205         }
1206
1207         /* React on 'smbcontrol winbindd reload-config' in the same way
1208            as to SIGHUP signal */
1209         messaging_register(winbind_messaging_context(), NULL,
1210                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1211         messaging_register(winbind_messaging_context(), NULL,
1212                            MSG_SHUTDOWN, msg_shutdown);
1213
1214         /* Handle online/offline messages. */
1215         messaging_register(winbind_messaging_context(), NULL,
1216                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1217         messaging_register(winbind_messaging_context(), NULL,
1218                            MSG_WINBIND_ONLINE, winbind_msg_online);
1219         messaging_register(winbind_messaging_context(), NULL,
1220                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1221
1222         messaging_register(winbind_messaging_context(), NULL,
1223                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1224
1225         messaging_register(winbind_messaging_context(), NULL,
1226                            MSG_WINBIND_VALIDATE_CACHE,
1227                            winbind_msg_validate_cache);
1228
1229         netsamlogon_cache_init(); /* Non-critical */
1230         
1231         /* clear the cached list of trusted domains */
1232
1233         wcache_tdc_clear();     
1234         
1235         if (!init_domain_list()) {
1236                 DEBUG(0,("unable to initalize domain list\n"));
1237                 exit(1);
1238         }
1239
1240         init_idmap_child();
1241         init_locator_child();
1242
1243         smb_nscd_flush_user_cache();
1244         smb_nscd_flush_group_cache();
1245
1246         /* Loop waiting for requests */
1247
1248         TALLOC_FREE(frame);
1249         while (1) {
1250                 frame = talloc_stackframe();
1251                 process_loop();
1252                 TALLOC_FREE(frame);
1253         }
1254
1255         return 0;
1256 }