Fix bogus uninitialized variable warnings
[Samba/gbeck.git] / source3 / winbindd / winbindd.c
blob615f4a918e6c06bbafbc132b39cf0beb4bd9728c
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind daemon for ntdom nss module
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
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.
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.
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/>.
25 #include "includes.h"
26 #include "winbindd.h"
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
31 bool opt_nocache = False;
32 static bool interactive = False;
34 extern bool override_logfile;
36 struct event_context *winbind_event_context(void)
38 static struct event_context *ctx;
40 if (!ctx && !(ctx = event_context_init(NULL))) {
41 smb_panic("Could not init winbind event context");
43 return ctx;
46 struct messaging_context *winbind_messaging_context(void)
48 static struct messaging_context *ctx;
50 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
51 winbind_event_context()))) {
52 smb_panic("Could not init winbind messaging context");
54 return ctx;
57 /* Reload configuration */
59 static bool reload_services_file(void)
61 bool ret;
63 if (lp_loaded()) {
64 const char *fname = lp_configfile();
66 if (file_exist(fname,NULL) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
67 set_dyn_CONFIGFILE(fname);
71 reopen_logs();
72 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
74 reopen_logs();
75 load_interfaces();
77 return(ret);
81 /**************************************************************************** **
82 Handle a fault..
83 **************************************************************************** */
85 static void fault_quit(void)
87 dump_core();
90 static void winbindd_status(void)
92 struct winbindd_cli_state *tmp;
94 DEBUG(0, ("winbindd status:\n"));
96 /* Print client state information */
98 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
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));
109 /* Print winbindd status to log file */
111 static void print_winbindd_status(void)
113 winbindd_status();
116 /* Flush client cache */
118 static void flush_caches(void)
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. */
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();
129 * Ensure all cache and idmap caches are consistent
130 * before we initialize the cache again.
132 if (winbindd_validate_cache() < 0) {
133 DEBUG(0, ("winbindd cache tdb corrupt and no backup "
134 "could be restore.\n"));
137 /* Initialize cache again. */
138 if (!initialize_winbindd_cache()) {
139 exit(1);
144 /* Handle the signal by unlinking socket and exiting */
146 static void terminate(void)
148 char *path = NULL;
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);
157 idmap_close();
159 trustdom_cache_shutdown();
161 #if 0
162 if (interactive) {
163 TALLOC_CTX *mem_ctx = talloc_init("end_description");
164 char *description = talloc_describe_all(mem_ctx);
166 DEBUG(3, ("tallocs left:\n%s\n", description));
167 talloc_destroy(mem_ctx);
169 #endif
171 exit(0);
174 static bool do_sigterm;
176 static void termination_handler(int signum)
178 do_sigterm = True;
179 sys_select_signal(signum);
182 static bool do_sigusr2;
184 static void sigusr2_handler(int signum)
186 do_sigusr2 = True;
187 sys_select_signal(SIGUSR2);
190 static bool do_sighup;
192 static void sighup_handler(int signum)
194 do_sighup = True;
195 sys_select_signal(SIGHUP);
198 static bool do_sigchld;
200 static void sigchld_handler(int signum)
202 do_sigchld = True;
203 sys_select_signal(SIGCHLD);
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)
213 /* Flush various caches */
214 flush_caches();
215 reload_services_file();
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)
225 do_sigterm = True;
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)
235 uint8 ret;
236 pid_t child_pid;
237 struct sigaction act;
238 struct sigaction oldact;
240 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
241 "message.\n"));
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...
248 CatchChild();
249 child_pid = sys_fork();
251 if (child_pid == -1) {
252 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
253 strerror(errno)));
254 return;
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;
264 /* child */
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);
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);
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[] = {
290 /* User functions */
292 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
293 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
295 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
296 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
297 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
299 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
300 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
301 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
302 "GETUSERDOMGROUPS" },
304 /* Group functions */
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" },
313 /* PAM auth functions */
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" },
321 /* Enumeration functions */
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" },
329 /* SID related functions */
331 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
332 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
333 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
335 /* Lookup related functions */
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" },
349 /* Miscellaneous */
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" },
364 /* Credential cache access */
365 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
367 /* WINS functions */
369 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
370 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
372 /* End of list */
374 { WINBINDD_NUM_CMDS, NULL, "NONE" }
377 static void process_request(struct winbindd_cli_state *state)
379 struct winbindd_dispatch_table *table = dispatch_table;
381 /* Free response data - we may be interrupted and receive another
382 command before being able to send this data off. */
384 SAFE_FREE(state->response.extra_data.data);
386 ZERO_STRUCT(state->response);
388 state->response.result = WINBINDD_PENDING;
389 state->response.length = sizeof(struct winbindd_response);
391 state->mem_ctx = talloc_init("winbind request");
392 if (state->mem_ctx == NULL)
393 return;
395 /* Remember who asked us. */
396 state->pid = state->request.pid;
398 /* Process command */
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;
409 if (!table->fn) {
410 DEBUG(10,("process_request: unknown request fn number %d\n",
411 (int)state->request.cmd ));
412 request_error(state);
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.
421 static struct fd_event *fd_events = NULL;
423 void add_fd_event(struct fd_event *ev)
425 struct fd_event *match;
427 /* only add unique fd_event structs */
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
438 DLIST_ADD(fd_events, ev);
441 void remove_fd_event(struct fd_event *ev)
443 DLIST_REMOVE(fd_events, ev);
447 * Handler for fd_events to complete a read/write request, set up by
448 * setup_async_read/setup_async_write.
451 static void rw_callback(struct fd_event *event, int flags)
453 size_t todo;
454 ssize_t done = 0;
456 todo = event->length - event->done;
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);
464 if (done <= 0) {
465 event->flags = 0;
466 event->finished(event->private_data, False);
467 return;
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);
476 if (done <= 0) {
477 event->flags = 0;
478 event->finished(event->private_data, False);
479 return;
483 event->done += done;
485 if (event->done == event->length) {
486 event->flags = 0;
487 event->finished(event->private_data, True);
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.
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)
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;
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)
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;
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.
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.
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);
542 static void response_extra_sent(void *private_data, bool success)
544 struct winbindd_cli_state *state =
545 talloc_get_type_abort(private_data, struct winbindd_cli_state);
547 if (state->mem_ctx != NULL) {
548 talloc_destroy(state->mem_ctx);
549 state->mem_ctx = NULL;
552 if (!success) {
553 state->finished = True;
554 return;
557 SAFE_FREE(state->request.extra_data.data);
558 SAFE_FREE(state->response.extra_data.data);
560 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
561 request_len_recv, state);
564 static void response_main_sent(void *private_data, bool success)
566 struct winbindd_cli_state *state =
567 talloc_get_type_abort(private_data, struct winbindd_cli_state);
569 if (!success) {
570 state->finished = True;
571 return;
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;
580 setup_async_read(&state->fd_event, &state->request,
581 sizeof(uint32), request_len_recv, state);
582 return;
585 setup_async_write(&state->fd_event, state->response.extra_data.data,
586 state->response.length - sizeof(state->response),
587 response_extra_sent, state);
590 static void request_finished(struct winbindd_cli_state *state)
592 setup_async_write(&state->fd_event, &state->response,
593 sizeof(state->response), response_main_sent, state);
596 void request_error(struct winbindd_cli_state *state)
598 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
599 state->response.result = WINBINDD_ERROR;
600 request_finished(state);
603 void request_ok(struct winbindd_cli_state *state)
605 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
606 state->response.result = WINBINDD_OK;
607 request_finished(state);
610 void request_finished_cont(void *private_data, bool success)
612 struct winbindd_cli_state *state =
613 talloc_get_type_abort(private_data, struct winbindd_cli_state);
615 if (success)
616 request_ok(state);
617 else
618 request_error(state);
621 static void request_len_recv(void *private_data, bool success)
623 struct winbindd_cli_state *state =
624 talloc_get_type_abort(private_data, struct winbindd_cli_state);
626 if (!success) {
627 state->finished = True;
628 return;
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;
638 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
639 sizeof(state->request) - sizeof(uint32),
640 request_main_recv, state);
643 static void request_main_recv(void *private_data, bool success)
645 struct winbindd_cli_state *state =
646 talloc_get_type_abort(private_data, struct winbindd_cli_state);
648 if (!success) {
649 state->finished = True;
650 return;
653 if (state->request.extra_len == 0) {
654 state->request.extra_data.data = NULL;
655 request_recv(state, True);
656 return;
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;
668 state->request.extra_data.data =
669 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
671 if (state->request.extra_data.data == NULL) {
672 DEBUG(0, ("malloc failed\n"));
673 state->finished = True;
674 return;
677 /* Ensure null termination */
678 state->request.extra_data.data[state->request.extra_len] = '\0';
680 setup_async_read(&state->fd_event, state->request.extra_data.data,
681 state->request.extra_len, request_recv, state);
684 static void request_recv(void *private_data, bool success)
686 struct winbindd_cli_state *state =
687 talloc_get_type_abort(private_data, struct winbindd_cli_state);
689 if (!success) {
690 state->finished = True;
691 return;
694 process_request(state);
697 /* Process a new connection by adding it to the client connection list */
699 static void new_connection(int listen_sock, bool privileged)
701 struct sockaddr_un sunaddr;
702 struct winbindd_cli_state *state;
703 socklen_t len;
704 int sock;
706 /* Accept connection */
708 len = sizeof(sunaddr);
710 do {
711 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
712 } while (sock == -1 && errno == EINTR);
714 if (sock == -1)
715 return;
717 DEBUG(6,("accepted socket %d\n", sock));
719 /* Create new connection structure */
721 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
722 close(sock);
723 return;
726 state->sock = sock;
728 state->last_access = time(NULL);
730 state->privileged = privileged;
732 state->fd_event.fd = state->sock;
733 state->fd_event.flags = 0;
734 add_fd_event(&state->fd_event);
736 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
737 request_len_recv, state);
739 /* Add to connection list */
741 winbindd_add_client(state);
744 /* Remove a client connection from client connection list */
746 static void remove_client(struct winbindd_cli_state *state)
748 /* It's a dead client - hold a funeral */
750 if (state == NULL) {
751 return;
754 /* Close socket */
756 close(state->sock);
758 /* Free any getent state */
760 free_getent_state(state->getpwent_state);
761 free_getent_state(state->getgrent_state);
763 /* We may have some extra data that was not freed if the client was
764 killed unexpectedly */
766 SAFE_FREE(state->response.extra_data.data);
768 if (state->mem_ctx != NULL) {
769 talloc_destroy(state->mem_ctx);
770 state->mem_ctx = NULL;
773 remove_fd_event(&state->fd_event);
775 /* Remove from list and free */
777 winbindd_remove_client(state);
778 TALLOC_FREE(state);
781 /* Shutdown client connection which has been idle for the longest time */
783 static bool remove_idle_client(void)
785 struct winbindd_cli_state *state, *remove_state = NULL;
786 time_t last_access = 0;
787 int nidle = 0;
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;
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;
807 return False;
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. */
815 static void process_loop(void)
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;
823 /* Open Sockets here to get stuff going ASAP */
824 listen_sock = open_winbindd_socket();
825 listen_priv_sock = open_winbindd_priv_socket();
827 if (listen_sock == -1 || listen_priv_sock == -1) {
828 perror("open_winbind_socket");
829 exit(1);
832 /* We'll be doing this a lot */
834 /* Handle messages */
836 message_dispatch(winbind_messaging_context());
838 run_events(winbind_event_context(), 0, NULL, NULL);
840 /* refresh the trusted domain cache */
842 rescan_trusted_domains();
844 /* Initialise fd lists for select() */
846 maxfd = MAX(listen_sock, listen_priv_sock);
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);
853 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
854 timeout.tv_usec = 0;
856 /* Check for any event timeouts. */
857 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
858 timeout = timeval_min(&timeout, &ev_timeout);
861 /* Set up client readers and writers */
863 state = winbindd_client_list();
865 while (state) {
867 struct winbindd_cli_state *next = state->next;
869 /* Dispose of client connection if it is marked as
870 finished */
872 if (state->finished)
873 remove_client(state);
875 state = next;
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);
883 if (ev->flags & EVENT_FD_WRITE) {
884 FD_SET(ev->fd, &w_fds);
885 maxfd = MAX(ev->fd, maxfd);
889 /* Call select */
891 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
893 if (selret == 0) {
894 goto no_fds_ready;
897 if (selret == -1) {
898 if (errno == EINTR) {
899 goto no_fds_ready;
902 /* Select error, something is badly wrong */
904 perror("select");
905 exit(1);
908 /* selret > 0 */
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;
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;
938 /* new, non-privileged connection */
939 new_connection(listen_sock, False);
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;
957 /* new, privileged connection */
958 new_connection(listen_priv_sock, True);
961 no_fds_ready:
963 #if 0
964 winbindd_check_cache_size(time(NULL));
965 #endif
967 /* Check signal handling things */
969 if (do_sigterm)
970 terminate();
972 if (do_sighup) {
974 DEBUG(3, ("got SIGHUP\n"));
976 flush_caches();
977 reload_services_file();
979 do_sighup = False;
982 if (do_sigusr2) {
983 print_winbindd_status();
984 do_sigusr2 = False;
987 if (do_sigchld) {
988 pid_t pid;
990 do_sigchld = False;
992 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
993 winbind_child_died(pid);
998 /* Main function */
1000 int main(int argc, char **argv, char **envp)
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
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
1023 poptContext pc;
1024 int opt;
1025 TALLOC_CTX *frame = talloc_stackframe();
1027 /* glibc (?) likes to print "User defined signal 1" and exit if a
1028 SIGUSR[12] is received before a handler is installed */
1030 CatchSignal(SIGUSR1, SIG_IGN);
1031 CatchSignal(SIGUSR2, SIG_IGN);
1033 fault_setup((void (*)(void *))fault_quit );
1034 dump_core_setup("winbindd");
1036 load_case_tables();
1038 /* Initialise for running in non-root mode */
1040 sec_init();
1042 set_remote_machine_name("winbindd", False);
1044 /* Set environment variable so we don't recursively call ourselves.
1045 This may also be useful interactively. */
1047 if ( !winbind_off() ) {
1048 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1049 exit(1);
1052 /* Initialise samba/rpc client stuff */
1054 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
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);
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);
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);
1101 poptFreeContext(pc);
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);
1111 setup_logging("winbindd", log_stdout);
1112 reopen_logs();
1114 DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1115 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1117 if (!reload_services_file()) {
1118 DEBUG(0, ("error opening config file\n"));
1119 exit(1);
1122 if (!directory_exist(lp_lockdir(), NULL)) {
1123 mkdir(lp_lockdir(), 0755);
1126 /* Setup names. */
1128 if (!init_names())
1129 exit(1);
1131 load_interfaces();
1133 if (!secrets_init()) {
1135 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1136 return False;
1139 /* Enable netbios namecache */
1141 namecache_enable();
1143 /* Winbind daemon initialisation */
1145 if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1146 DEBUG(1, ("Could not init idmap cache!\n"));
1149 /* Unblock all signals we are interested in as they may have been
1150 blocked by the parent process. */
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);
1160 /* Setup signal handlers */
1162 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1163 CatchSignal(SIGQUIT, termination_handler);
1164 CatchSignal(SIGTERM, termination_handler);
1165 CatchSignal(SIGCHLD, sigchld_handler);
1167 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1169 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1170 CatchSignal(SIGHUP, sighup_handler);
1172 if (!interactive)
1173 become_daemon(Fork, no_process_group);
1175 pidfile_create("winbindd");
1177 #if HAVE_SETPGID
1179 * If we're interactive we want to set our own process group for
1180 * signal management.
1182 if (interactive && !no_process_group)
1183 setpgid( (pid_t)0, (pid_t)0);
1184 #endif
1186 TimeInit();
1188 /* Initialise messaging system */
1190 if (winbind_messaging_context() == NULL) {
1191 DEBUG(0, ("unable to initialize messaging system\n"));
1192 exit(1);
1196 * Ensure all cache and idmap caches are consistent
1197 * before we startup.
1199 if (winbindd_validate_cache() < 0) {
1200 DEBUG(0, ("corrupted tdb found, trying to restore backup\n"));
1203 /* Initialize cache (ensure version is correct). */
1204 if (!initialize_winbindd_cache()) {
1205 exit(1);
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);
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);
1223 messaging_register(winbind_messaging_context(), NULL,
1224 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1226 messaging_register(winbind_messaging_context(), NULL,
1227 MSG_WINBIND_VALIDATE_CACHE,
1228 winbind_msg_validate_cache);
1230 messaging_register(winbind_messaging_context(), NULL,
1231 MSG_WINBIND_DUMP_DOMAIN_LIST,
1232 winbind_msg_dump_domain_list);
1234 netsamlogon_cache_init(); /* Non-critical */
1236 /* clear the cached list of trusted domains */
1238 wcache_tdc_clear();
1240 if (!init_domain_list()) {
1241 DEBUG(0,("unable to initalize domain list\n"));
1242 exit(1);
1245 init_idmap_child();
1246 init_locator_child();
1248 smb_nscd_flush_user_cache();
1249 smb_nscd_flush_group_cache();
1251 /* Loop waiting for requests */
1253 TALLOC_FREE(frame);
1254 while (1) {
1255 frame = talloc_stackframe();
1256 process_loop();
1257 TALLOC_FREE(frame);
1260 return 0;