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