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