s3:winbindd: remove unused variables
[Samba.git] / source3 / winbindd / winbindd.c
blob7d4c996769a05c97a913d4946fa74c455f75f870
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 static 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 == NULL) {
51 ctx = messaging_init(NULL, server_id_self(),
52 winbind_event_context());
54 if (ctx == NULL) {
55 DEBUG(0, ("Could not init winbind messaging context.\n"));
57 return ctx;
60 /* Reload configuration */
62 static bool reload_services_file(const char *lfile)
64 bool ret;
66 if (lp_loaded()) {
67 const char *fname = lp_configfile();
69 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
70 set_dyn_CONFIGFILE(fname);
74 /* if this is a child, restore the logfile to the special
75 name - <domain>, idmap, etc. */
76 if (lfile && *lfile) {
77 lp_set_logfile(lfile);
80 reopen_logs();
81 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
83 reopen_logs();
84 load_interfaces();
86 return(ret);
90 /**************************************************************************** **
91 Handle a fault..
92 **************************************************************************** */
94 static void fault_quit(void)
96 dump_core();
99 static void winbindd_status(void)
101 struct winbindd_cli_state *tmp;
103 DEBUG(0, ("winbindd status:\n"));
105 /* Print client state information */
107 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
109 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
110 DEBUG(2, ("\tclient list:\n"));
111 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
112 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
113 (unsigned long)tmp->pid, tmp->sock));
118 /* Print winbindd status to log file */
120 static void print_winbindd_status(void)
122 winbindd_status();
125 /* Flush client cache */
127 static void flush_caches(void)
129 /* We need to invalidate cached user list entries on a SIGHUP
130 otherwise cached access denied errors due to restrict anonymous
131 hang around until the sequence number changes. */
133 if (!wcache_invalidate_cache()) {
134 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
135 if (!winbindd_cache_validate_and_initialize()) {
136 exit(1);
141 /* Handle the signal by unlinking socket and exiting */
143 static void terminate(bool is_parent)
145 if (is_parent) {
146 /* When parent goes away we should
147 * remove the socket file. Not so
148 * when children terminate.
150 char *path = NULL;
152 if (asprintf(&path, "%s/%s",
153 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
154 unlink(path);
155 SAFE_FREE(path);
159 idmap_close();
161 trustdom_cache_shutdown();
163 #if 0
164 if (interactive) {
165 TALLOC_CTX *mem_ctx = talloc_init("end_description");
166 char *description = talloc_describe_all(mem_ctx);
168 DEBUG(3, ("tallocs left:\n%s\n", description));
169 talloc_destroy(mem_ctx);
171 #endif
173 if (is_parent) {
174 pidfile_unlink();
177 exit(0);
180 static void winbindd_sig_term_handler(struct tevent_context *ev,
181 struct tevent_signal *se,
182 int signum,
183 int count,
184 void *siginfo,
185 void *private_data)
187 bool *is_parent = talloc_get_type_abort(private_data, bool);
189 DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
190 signum, (int)*is_parent));
191 terminate(*is_parent);
194 bool winbindd_setup_sig_term_handler(bool parent)
196 struct tevent_signal *se;
197 bool *is_parent;
199 is_parent = talloc(winbind_event_context(), bool);
200 if (!is_parent) {
201 return false;
204 *is_parent = parent;
206 se = tevent_add_signal(winbind_event_context(),
207 is_parent,
208 SIGTERM, 0,
209 winbindd_sig_term_handler,
210 is_parent);
211 if (!se) {
212 DEBUG(0,("failed to setup SIGTERM handler"));
213 talloc_free(is_parent);
214 return false;
217 se = tevent_add_signal(winbind_event_context(),
218 is_parent,
219 SIGINT, 0,
220 winbindd_sig_term_handler,
221 is_parent);
222 if (!se) {
223 DEBUG(0,("failed to setup SIGINT handler"));
224 talloc_free(is_parent);
225 return false;
228 se = tevent_add_signal(winbind_event_context(),
229 is_parent,
230 SIGQUIT, 0,
231 winbindd_sig_term_handler,
232 is_parent);
233 if (!se) {
234 DEBUG(0,("failed to setup SIGINT handler"));
235 talloc_free(is_parent);
236 return false;
239 return true;
242 static void winbindd_sig_hup_handler(struct tevent_context *ev,
243 struct tevent_signal *se,
244 int signum,
245 int count,
246 void *siginfo,
247 void *private_data)
249 const char *file = (const char *)private_data;
251 DEBUG(1,("Reloading services after SIGHUP\n"));
252 flush_caches();
253 reload_services_file(file);
256 bool winbindd_setup_sig_hup_handler(const char *lfile)
258 struct tevent_signal *se;
259 char *file = NULL;
261 if (lfile) {
262 file = talloc_strdup(winbind_event_context(),
263 lfile);
264 if (!file) {
265 return false;
269 se = tevent_add_signal(winbind_event_context(),
270 winbind_event_context(),
271 SIGHUP, 0,
272 winbindd_sig_hup_handler,
273 file);
274 if (!se) {
275 return false;
278 return true;
281 static void winbindd_sig_chld_handler(struct tevent_context *ev,
282 struct tevent_signal *se,
283 int signum,
284 int count,
285 void *siginfo,
286 void *private_data)
288 pid_t pid;
290 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
291 winbind_child_died(pid);
295 static bool winbindd_setup_sig_chld_handler(void)
297 struct tevent_signal *se;
299 se = tevent_add_signal(winbind_event_context(),
300 winbind_event_context(),
301 SIGCHLD, 0,
302 winbindd_sig_chld_handler,
303 NULL);
304 if (!se) {
305 return false;
308 return true;
311 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
312 struct tevent_signal *se,
313 int signum,
314 int count,
315 void *siginfo,
316 void *private_data)
318 print_winbindd_status();
321 static bool winbindd_setup_sig_usr2_handler(void)
323 struct tevent_signal *se;
325 se = tevent_add_signal(winbind_event_context(),
326 winbind_event_context(),
327 SIGUSR2, 0,
328 winbindd_sig_usr2_handler,
329 NULL);
330 if (!se) {
331 return false;
334 return true;
337 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
338 static void msg_reload_services(struct messaging_context *msg,
339 void *private_data,
340 uint32_t msg_type,
341 struct server_id server_id,
342 DATA_BLOB *data)
344 /* Flush various caches */
345 flush_caches();
346 reload_services_file((const char *) private_data);
349 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
350 static void msg_shutdown(struct messaging_context *msg,
351 void *private_data,
352 uint32_t msg_type,
353 struct server_id server_id,
354 DATA_BLOB *data)
356 /* only the parent waits for this message */
357 DEBUG(0,("Got shutdown message\n"));
358 terminate(true);
362 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
363 void *private_data,
364 uint32_t msg_type,
365 struct server_id server_id,
366 DATA_BLOB *data)
368 uint8 ret;
369 pid_t child_pid;
371 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
372 "message.\n"));
375 * call the validation code from a child:
376 * so we don't block the main winbindd and the validation
377 * code can safely use fork/waitpid...
379 child_pid = sys_fork();
381 if (child_pid == -1) {
382 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
383 strerror(errno)));
384 return;
387 if (child_pid != 0) {
388 /* parent */
389 DEBUG(5, ("winbind_msg_validate_cache: child created with "
390 "pid %d.\n", (int)child_pid));
391 return;
394 /* child */
396 if (!winbindd_reinit_after_fork(NULL)) {
397 _exit(0);
400 ret = (uint8)winbindd_validate_cache_nobackup();
401 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
402 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
403 (size_t)1);
404 _exit(0);
407 static struct winbindd_dispatch_table {
408 enum winbindd_cmd cmd;
409 void (*fn)(struct winbindd_cli_state *state);
410 const char *winbindd_cmd_name;
411 } dispatch_table[] = {
413 /* User functions */
415 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
416 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
417 { WINBINDD_GETPWSID, winbindd_getpwsid, "GETPWSID" },
419 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
420 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
421 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
423 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
424 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
425 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
426 "GETUSERDOMGROUPS" },
427 { WINBINDD_GETSIDALIASES, winbindd_getsidaliases,
428 "LOOKUPUSERALIASES" },
430 /* Group functions */
432 { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
433 { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
434 { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
435 { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
436 { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
437 { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
439 /* PAM auth functions */
441 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
442 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
443 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
444 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
445 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
447 /* Enumeration functions */
449 { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
450 { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
451 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
452 "LIST_TRUSTDOM" },
453 { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
455 /* SID related functions */
457 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
458 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
459 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
461 /* Lookup related functions */
463 { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
464 { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
465 { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
466 { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
467 { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
468 { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
469 { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
470 { WINBINDD_REMOVE_MAPPING, winbindd_remove_mapping, "REMOVE_MAPPING" },
471 { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
473 /* Miscellaneous */
475 { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
476 { WINBINDD_PING, winbindd_ping, "PING" },
477 { WINBINDD_INFO, winbindd_info, "INFO" },
478 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
479 "INTERFACE_VERSION" },
480 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
481 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
482 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
483 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
484 "WINBINDD_PRIV_PIPE_DIR" },
485 { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
486 { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
488 /* Credential cache access */
489 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
491 /* WINS functions */
493 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
494 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
496 /* End of list */
498 { WINBINDD_NUM_CMDS, NULL, "NONE" }
501 static void process_request(struct winbindd_cli_state *state)
503 struct winbindd_dispatch_table *table = dispatch_table;
505 /* Free response data - we may be interrupted and receive another
506 command before being able to send this data off. */
508 SAFE_FREE(state->response.extra_data.data);
510 ZERO_STRUCT(state->response);
512 state->response.result = WINBINDD_PENDING;
513 state->response.length = sizeof(struct winbindd_response);
515 state->mem_ctx = talloc_init("winbind request");
516 if (state->mem_ctx == NULL)
517 return;
519 /* Remember who asked us. */
520 state->pid = state->request.pid;
522 /* Process command */
524 for (table = dispatch_table; table->fn; table++) {
525 if (state->request.cmd == table->cmd) {
526 DEBUG(10,("process_request: request fn %s\n",
527 table->winbindd_cmd_name ));
528 table->fn(state);
529 break;
533 if (!table->fn) {
534 DEBUG(10,("process_request: unknown request fn number %d\n",
535 (int)state->request.cmd ));
536 request_error(state);
541 * A list of file descriptors being monitored by select in the main processing
542 * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
545 static struct winbindd_fd_event *fd_events = NULL;
547 void add_fd_event(struct winbindd_fd_event *ev)
549 struct winbindd_fd_event *match;
551 /* only add unique winbindd_fd_event structs */
553 for (match=fd_events; match; match=match->next ) {
554 #ifdef DEVELOPER
555 SMB_ASSERT( match != ev );
556 #else
557 if ( match == ev )
558 return;
559 #endif
562 DLIST_ADD(fd_events, ev);
565 void remove_fd_event(struct winbindd_fd_event *ev)
567 DLIST_REMOVE(fd_events, ev);
571 * Handler for winbindd_fd_events to complete a read/write request, set up by
572 * setup_async_read/setup_async_write.
575 static void rw_callback(struct winbindd_fd_event *event, int flags)
577 size_t todo;
578 ssize_t done = 0;
580 todo = event->length - event->done;
582 if (event->flags & EVENT_FD_WRITE) {
583 SMB_ASSERT(flags == EVENT_FD_WRITE);
584 done = sys_write(event->fd,
585 &((char *)event->data)[event->done],
586 todo);
588 if (done <= 0) {
589 event->flags = 0;
590 event->finished(event->private_data, False);
591 return;
595 if (event->flags & EVENT_FD_READ) {
596 SMB_ASSERT(flags == EVENT_FD_READ);
597 done = sys_read(event->fd, &((char *)event->data)[event->done],
598 todo);
600 if (done <= 0) {
601 event->flags = 0;
602 event->finished(event->private_data, False);
603 return;
607 event->done += done;
609 if (event->done == event->length) {
610 event->flags = 0;
611 event->finished(event->private_data, True);
616 * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
617 * when the request is completed or an error had occurred.
620 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
621 void (*finished)(void *private_data, bool success),
622 void *private_data)
624 SMB_ASSERT(event->flags == 0);
625 event->data = data;
626 event->length = length;
627 event->done = 0;
628 event->handler = rw_callback;
629 event->finished = finished;
630 event->private_data = private_data;
631 event->flags = EVENT_FD_READ;
634 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
635 void (*finished)(void *private_data, bool success),
636 void *private_data)
638 SMB_ASSERT(event->flags == 0);
639 event->data = data;
640 event->length = length;
641 event->done = 0;
642 event->handler = rw_callback;
643 event->finished = finished;
644 event->private_data = private_data;
645 event->flags = EVENT_FD_WRITE;
649 * This is the main event loop of winbind requests. It goes through a
650 * state-machine of 3 read/write requests, 4 if you have extra data to send.
652 * An idle winbind client has a read request of 4 bytes outstanding,
653 * finalizing function is request_len_recv, checking the length. request_recv
654 * then processes the packet. The processing function then at some point has
655 * to call request_finished which schedules sending the response.
658 static void request_len_recv(void *private_data, bool success);
659 static void request_recv(void *private_data, bool success);
660 static void request_main_recv(void *private_data, bool success);
661 static void request_finished(struct winbindd_cli_state *state);
662 static void response_main_sent(void *private_data, bool success);
663 static void response_extra_sent(void *private_data, bool success);
665 static void response_extra_sent(void *private_data, bool success)
667 struct winbindd_cli_state *state =
668 talloc_get_type_abort(private_data, struct winbindd_cli_state);
670 TALLOC_FREE(state->mem_ctx);
672 if (!success) {
673 state->finished = True;
674 return;
677 SAFE_FREE(state->response.extra_data.data);
679 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
680 request_len_recv, state);
683 static void response_main_sent(void *private_data, bool success)
685 struct winbindd_cli_state *state =
686 talloc_get_type_abort(private_data, struct winbindd_cli_state);
688 if (!success) {
689 state->finished = True;
690 return;
693 if (state->response.length == sizeof(state->response)) {
694 TALLOC_FREE(state->mem_ctx);
696 setup_async_read(&state->fd_event, &state->request,
697 sizeof(uint32), request_len_recv, state);
698 return;
701 setup_async_write(&state->fd_event, state->response.extra_data.data,
702 state->response.length - sizeof(state->response),
703 response_extra_sent, state);
706 static void request_finished(struct winbindd_cli_state *state)
708 /* Make sure request.extra_data is freed when finish processing a request */
709 SAFE_FREE(state->request.extra_data.data);
710 setup_async_write(&state->fd_event, &state->response,
711 sizeof(state->response), response_main_sent, state);
714 void request_error(struct winbindd_cli_state *state)
716 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
717 state->response.result = WINBINDD_ERROR;
718 request_finished(state);
721 void request_ok(struct winbindd_cli_state *state)
723 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
724 state->response.result = WINBINDD_OK;
725 request_finished(state);
728 static void request_len_recv(void *private_data, bool success)
730 struct winbindd_cli_state *state =
731 talloc_get_type_abort(private_data, struct winbindd_cli_state);
733 if (!success) {
734 state->finished = True;
735 return;
738 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
739 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
740 *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
741 state->finished = True;
742 return;
745 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
746 sizeof(state->request) - sizeof(uint32),
747 request_main_recv, state);
750 static void request_main_recv(void *private_data, bool success)
752 struct winbindd_cli_state *state =
753 talloc_get_type_abort(private_data, struct winbindd_cli_state);
755 if (!success) {
756 state->finished = True;
757 return;
760 if (state->request.extra_len == 0) {
761 state->request.extra_data.data = NULL;
762 request_recv(state, True);
763 return;
766 if ((!state->privileged) &&
767 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
768 DEBUG(3, ("Got request with %d bytes extra data on "
769 "unprivileged socket\n", (int)state->request.extra_len));
770 state->request.extra_data.data = NULL;
771 state->finished = True;
772 return;
775 state->request.extra_data.data =
776 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
778 if (state->request.extra_data.data == NULL) {
779 DEBUG(0, ("malloc failed\n"));
780 state->finished = True;
781 return;
784 /* Ensure null termination */
785 state->request.extra_data.data[state->request.extra_len] = '\0';
787 setup_async_read(&state->fd_event, state->request.extra_data.data,
788 state->request.extra_len, request_recv, state);
791 static void request_recv(void *private_data, bool success)
793 struct winbindd_cli_state *state =
794 talloc_get_type_abort(private_data, struct winbindd_cli_state);
796 if (!success) {
797 state->finished = True;
798 return;
801 process_request(state);
804 /* Process a new connection by adding it to the client connection list */
806 static void new_connection(int listen_sock, bool privileged)
808 struct sockaddr_un sunaddr;
809 struct winbindd_cli_state *state;
810 socklen_t len;
811 int sock;
813 /* Accept connection */
815 len = sizeof(sunaddr);
817 do {
818 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
819 } while (sock == -1 && errno == EINTR);
821 if (sock == -1)
822 return;
824 DEBUG(6,("accepted socket %d\n", sock));
826 /* Create new connection structure */
828 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
829 close(sock);
830 return;
833 state->sock = sock;
835 state->last_access = time(NULL);
837 state->privileged = privileged;
839 state->fd_event.fd = state->sock;
840 state->fd_event.flags = 0;
841 add_fd_event(&state->fd_event);
843 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
844 request_len_recv, state);
846 /* Add to connection list */
848 winbindd_add_client(state);
851 /* Remove a client connection from client connection list */
853 static void remove_client(struct winbindd_cli_state *state)
855 char c = 0;
856 int nwritten;
858 /* It's a dead client - hold a funeral */
860 if (state == NULL) {
861 return;
864 if (!state->finished) {
865 /* tell client, we are closing ... */
866 nwritten = write(state->sock, &c, sizeof(c));
867 if (nwritten == -1) {
868 DEBUG(2, ("final write to client failed: %s\n",
869 strerror(errno)));
873 /* Close socket */
875 close(state->sock);
877 /* Free any getent state */
879 free_getent_state(state->getpwent_state);
880 free_getent_state(state->getgrent_state);
882 /* We may have some extra data that was not freed if the client was
883 killed unexpectedly */
885 SAFE_FREE(state->response.extra_data.data);
887 TALLOC_FREE(state->mem_ctx);
889 remove_fd_event(&state->fd_event);
891 /* Remove from list and free */
893 winbindd_remove_client(state);
894 TALLOC_FREE(state);
897 /* Shutdown client connection which has been idle for the longest time */
899 static bool remove_idle_client(void)
901 struct winbindd_cli_state *state, *remove_state = NULL;
902 time_t last_access = 0;
903 int nidle = 0;
905 for (state = winbindd_client_list(); state; state = state->next) {
906 if (state->response.result != WINBINDD_PENDING &&
907 state->fd_event.flags == EVENT_FD_READ &&
908 !state->getpwent_state && !state->getgrent_state) {
909 nidle++;
910 if (!last_access || state->last_access < last_access) {
911 last_access = state->last_access;
912 remove_state = state;
917 if (remove_state) {
918 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
919 nidle, remove_state->sock, (unsigned int)remove_state->pid));
920 remove_client(remove_state);
921 return True;
924 return False;
927 struct winbindd_listen_state {
928 bool privileged;
929 int fd;
930 struct tevent_fd *fde;
933 static void winbindd_listen_fde_handler(struct tevent_context *ev,
934 struct tevent_fd *fde,
935 uint16_t flags,
936 void *private_data)
938 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
939 struct winbindd_listen_state);
941 while (winbindd_num_clients() >
942 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
943 DEBUG(5,("winbindd: Exceeding %d client "
944 "connections, removing idle "
945 "connection.\n",
946 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
947 if (!remove_idle_client()) {
948 DEBUG(0,("winbindd: Exceeding %d "
949 "client connections, no idle "
950 "connection found\n",
951 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
952 break;
956 /* new, non-privileged connection */
957 new_connection(s->fd, s->privileged);
960 static bool winbindd_setup_listeners(void)
962 struct winbindd_listen_state *pub_state = NULL;
963 struct winbindd_listen_state *priv_state = NULL;
965 pub_state = talloc(winbind_event_context(),
966 struct winbindd_listen_state);
967 if (!pub_state) {
968 goto failed;
971 pub_state->privileged = false;
972 pub_state->fd = open_winbindd_socket();
973 if (pub_state->fd == -1) {
974 goto failed;
977 pub_state->fde = tevent_add_fd(winbind_event_context(),
978 pub_state, pub_state->fd,
979 TEVENT_FD_READ,
980 winbindd_listen_fde_handler,
981 pub_state);
982 if (!pub_state->fde) {
983 close(pub_state->fd);
984 goto failed;
986 tevent_fd_set_auto_close(pub_state->fde);
988 priv_state = talloc(winbind_event_context(),
989 struct winbindd_listen_state);
990 if (!priv_state) {
991 goto failed;
994 priv_state->privileged = true;
995 priv_state->fd = open_winbindd_priv_socket();
996 if (priv_state->fd == -1) {
997 goto failed;
1000 priv_state->fde = tevent_add_fd(winbind_event_context(),
1001 priv_state, priv_state->fd,
1002 TEVENT_FD_READ,
1003 winbindd_listen_fde_handler,
1004 priv_state);
1005 if (!priv_state->fde) {
1006 close(priv_state->fd);
1007 goto failed;
1009 tevent_fd_set_auto_close(priv_state->fde);
1011 return true;
1012 failed:
1013 TALLOC_FREE(pub_state);
1014 TALLOC_FREE(priv_state);
1015 return false;
1018 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
1019 non-forking, non-threaded model which allows us to handle many
1020 simultaneous connections while remaining impervious to many denial of
1021 service attacks. */
1023 static void process_loop(void)
1025 struct winbindd_fd_event *ev;
1026 fd_set r_fds, w_fds;
1027 int maxfd = 0, selret;
1028 struct timeval timeout, ev_timeout;
1030 if (run_events(winbind_event_context(), 0, NULL, NULL)) {
1031 return;
1034 /* Initialise fd lists for select() */
1036 FD_ZERO(&r_fds);
1037 FD_ZERO(&w_fds);
1039 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
1040 timeout.tv_usec = 0;
1042 /* Check for any event timeouts. */
1044 struct timeval now;
1045 GetTimeOfDay(&now);
1048 * Initialize this high as event_add_to_select_args()
1049 * uses a timeval_min() on this and next_event. Fix
1050 * from Roel van Meer <rolek@alt001.com>.
1053 ev_timeout.tv_sec = 999999;
1054 ev_timeout.tv_usec = 0;
1056 event_add_to_select_args(winbind_event_context(), &now,
1057 &r_fds, &w_fds, &ev_timeout, &maxfd);
1059 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
1060 timeout = timeval_min(&timeout, &ev_timeout);
1063 for (ev = fd_events; ev; ev = ev->next) {
1064 if (ev->flags & EVENT_FD_READ) {
1065 FD_SET(ev->fd, &r_fds);
1066 maxfd = MAX(ev->fd, maxfd);
1068 if (ev->flags & EVENT_FD_WRITE) {
1069 FD_SET(ev->fd, &w_fds);
1070 maxfd = MAX(ev->fd, maxfd);
1074 /* Call select */
1076 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
1078 if (selret == 0) {
1079 goto no_fds_ready;
1082 if (selret == -1) {
1083 if (errno == EINTR) {
1084 goto no_fds_ready;
1087 /* Select error, something is badly wrong */
1089 perror("select");
1090 exit(1);
1093 /* selret > 0 */
1095 if (run_events(winbind_event_context(), selret, &r_fds, &w_fds)) {
1096 return;
1099 ev = fd_events;
1100 while (ev != NULL) {
1101 struct winbindd_fd_event *next = ev->next;
1102 int flags = 0;
1103 if (FD_ISSET(ev->fd, &r_fds))
1104 flags |= EVENT_FD_READ;
1105 if (FD_ISSET(ev->fd, &w_fds))
1106 flags |= EVENT_FD_WRITE;
1107 if (flags) {
1108 ev->handler(ev, flags);
1109 return;
1111 ev = next;
1114 return;
1116 no_fds_ready:
1118 run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1120 #if 0
1121 winbindd_check_cache_size(time(NULL));
1122 #endif
1125 bool winbindd_use_idmap_cache(void)
1127 return !opt_nocache;
1130 bool winbindd_use_cache(void)
1132 return !opt_nocache;
1135 /* Main function */
1137 int main(int argc, char **argv, char **envp)
1139 static bool is_daemon = False;
1140 static bool Fork = True;
1141 static bool log_stdout = False;
1142 static bool no_process_group = False;
1143 enum {
1144 OPT_DAEMON = 1000,
1145 OPT_FORK,
1146 OPT_NO_PROCESS_GROUP,
1147 OPT_LOG_STDOUT
1149 struct poptOption long_options[] = {
1150 POPT_AUTOHELP
1151 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1152 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1153 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1154 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1155 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1156 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1157 POPT_COMMON_SAMBA
1158 POPT_TABLEEND
1160 poptContext pc;
1161 int opt;
1162 TALLOC_CTX *frame = talloc_stackframe();
1164 /* glibc (?) likes to print "User defined signal 1" and exit if a
1165 SIGUSR[12] is received before a handler is installed */
1167 CatchSignal(SIGUSR1, SIG_IGN);
1168 CatchSignal(SIGUSR2, SIG_IGN);
1170 fault_setup((void (*)(void *))fault_quit );
1171 dump_core_setup("winbindd");
1173 load_case_tables();
1175 /* Initialise for running in non-root mode */
1177 sec_init();
1179 set_remote_machine_name("winbindd", False);
1181 /* Set environment variable so we don't recursively call ourselves.
1182 This may also be useful interactively. */
1184 if ( !winbind_off() ) {
1185 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1186 exit(1);
1189 /* Initialise samba/rpc client stuff */
1191 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1193 while ((opt = poptGetNextOpt(pc)) != -1) {
1194 switch (opt) {
1195 /* Don't become a daemon */
1196 case OPT_DAEMON:
1197 is_daemon = True;
1198 break;
1199 case 'i':
1200 interactive = True;
1201 log_stdout = True;
1202 Fork = False;
1203 break;
1204 case OPT_FORK:
1205 Fork = false;
1206 break;
1207 case OPT_NO_PROCESS_GROUP:
1208 no_process_group = true;
1209 break;
1210 case OPT_LOG_STDOUT:
1211 log_stdout = true;
1212 break;
1213 case 'n':
1214 opt_nocache = true;
1215 break;
1216 default:
1217 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1218 poptBadOption(pc, 0), poptStrerror(opt));
1219 poptPrintUsage(pc, stderr, 0);
1220 exit(1);
1224 if (is_daemon && interactive) {
1225 d_fprintf(stderr,"\nERROR: "
1226 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1227 poptPrintUsage(pc, stderr, 0);
1228 exit(1);
1231 if (log_stdout && Fork) {
1232 d_fprintf(stderr, "\nERROR: "
1233 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1234 poptPrintUsage(pc, stderr, 0);
1235 exit(1);
1238 poptFreeContext(pc);
1240 if (!override_logfile) {
1241 char *lfile = NULL;
1242 if (asprintf(&lfile,"%s/log.winbindd",
1243 get_dyn_LOGFILEBASE()) > 0) {
1244 lp_set_logfile(lfile);
1245 SAFE_FREE(lfile);
1248 setup_logging("winbindd", log_stdout);
1249 reopen_logs();
1251 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1252 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1254 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1255 DEBUG(0, ("error opening config file\n"));
1256 exit(1);
1259 /* Initialise messaging system */
1261 if (winbind_messaging_context() == NULL) {
1262 exit(1);
1265 if (!reload_services_file(NULL)) {
1266 DEBUG(0, ("error opening config file\n"));
1267 exit(1);
1270 if (!directory_exist(lp_lockdir())) {
1271 mkdir(lp_lockdir(), 0755);
1274 /* Setup names. */
1276 if (!init_names())
1277 exit(1);
1279 load_interfaces();
1281 if (!secrets_init()) {
1283 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1284 return False;
1287 /* Enable netbios namecache */
1289 namecache_enable();
1291 /* Unblock all signals we are interested in as they may have been
1292 blocked by the parent process. */
1294 BlockSignals(False, SIGINT);
1295 BlockSignals(False, SIGQUIT);
1296 BlockSignals(False, SIGTERM);
1297 BlockSignals(False, SIGUSR1);
1298 BlockSignals(False, SIGUSR2);
1299 BlockSignals(False, SIGHUP);
1300 BlockSignals(False, SIGCHLD);
1302 if (!interactive)
1303 become_daemon(Fork, no_process_group);
1305 pidfile_create("winbindd");
1307 #if HAVE_SETPGID
1309 * If we're interactive we want to set our own process group for
1310 * signal management.
1312 if (interactive && !no_process_group)
1313 setpgid( (pid_t)0, (pid_t)0);
1314 #endif
1316 TimeInit();
1318 /* Don't use winbindd_reinit_after_fork here as
1319 * we're just starting up and haven't created any
1320 * winbindd-specific resources we must free yet. JRA.
1323 if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1324 winbind_event_context(),
1325 false))) {
1326 DEBUG(0,("reinit_after_fork() failed\n"));
1327 exit(1);
1330 /* Setup signal handlers */
1332 if (!winbindd_setup_sig_term_handler(true))
1333 exit(1);
1334 if (!winbindd_setup_sig_hup_handler(NULL))
1335 exit(1);
1336 if (!winbindd_setup_sig_chld_handler())
1337 exit(1);
1338 if (!winbindd_setup_sig_usr2_handler())
1339 exit(1);
1341 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1344 * Ensure all cache and idmap caches are consistent
1345 * and initialized before we startup.
1347 if (!winbindd_cache_validate_and_initialize()) {
1348 exit(1);
1351 /* get broadcast messages */
1352 claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1354 /* React on 'smbcontrol winbindd reload-config' in the same way
1355 as to SIGHUP signal */
1356 messaging_register(winbind_messaging_context(), NULL,
1357 MSG_SMB_CONF_UPDATED, msg_reload_services);
1358 messaging_register(winbind_messaging_context(), NULL,
1359 MSG_SHUTDOWN, msg_shutdown);
1361 /* Handle online/offline messages. */
1362 messaging_register(winbind_messaging_context(), NULL,
1363 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1364 messaging_register(winbind_messaging_context(), NULL,
1365 MSG_WINBIND_ONLINE, winbind_msg_online);
1366 messaging_register(winbind_messaging_context(), NULL,
1367 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1369 messaging_register(winbind_messaging_context(), NULL,
1370 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1372 messaging_register(winbind_messaging_context(), NULL,
1373 MSG_WINBIND_VALIDATE_CACHE,
1374 winbind_msg_validate_cache);
1376 messaging_register(winbind_messaging_context(), NULL,
1377 MSG_WINBIND_DUMP_DOMAIN_LIST,
1378 winbind_msg_dump_domain_list);
1380 /* Register handler for MSG_DEBUG. */
1381 messaging_register(winbind_messaging_context(), NULL,
1382 MSG_DEBUG,
1383 winbind_msg_debug);
1385 netsamlogon_cache_init(); /* Non-critical */
1387 /* clear the cached list of trusted domains */
1389 wcache_tdc_clear();
1391 if (!init_domain_list()) {
1392 DEBUG(0,("unable to initialize domain list\n"));
1393 exit(1);
1396 init_idmap_child();
1397 init_locator_child();
1399 smb_nscd_flush_user_cache();
1400 smb_nscd_flush_group_cache();
1402 /* setup listen sockets */
1404 if (!winbindd_setup_listeners()) {
1405 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1406 exit(1);
1409 TALLOC_FREE(frame);
1410 /* Loop waiting for requests */
1411 while (1) {
1412 struct winbindd_cli_state *state;
1414 frame = talloc_stackframe();
1416 /* refresh the trusted domain cache */
1418 rescan_trusted_domains();
1420 /* Dispose of client connection if it is marked as
1421 finished */
1422 state = winbindd_client_list();
1423 while (state) {
1424 struct winbindd_cli_state *next = state->next;
1426 if (state->finished) {
1427 remove_client(state);
1430 state = next;
1433 process_loop();
1435 TALLOC_FREE(frame);
1438 return 0;