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