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