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