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