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