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