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