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