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