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