Second part of fix for bug #8663 - deleting a symlink fails if the symlink target...
[Samba.git] / source3 / winbindd / winbindd.c
blob110f0348cb953a2a64c847c4b83efd31aca5df54
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 "popt_common.h"
27 #include "winbindd.h"
28 #include "nsswitch/winbind_client.h"
29 #include "nsswitch/wb_reqtrans.h"
30 #include "ntdomain.h"
31 #include "../librpc/gen_ndr/srv_lsa.h"
32 #include "../librpc/gen_ndr/srv_samr.h"
33 #include "secrets.h"
34 #include "idmap.h"
35 #include "lib/addrchange.h"
36 #include "serverid.h"
37 #include "auth.h"
38 #include "messages.h"
40 #undef DBGC_CLASS
41 #define DBGC_CLASS DBGC_WINBIND
43 static bool client_is_idle(struct winbindd_cli_state *state);
44 static void remove_client(struct winbindd_cli_state *state);
46 static bool opt_nocache = False;
47 static bool interactive = False;
49 extern bool override_logfile;
51 struct messaging_context *winbind_messaging_context(void)
53 struct messaging_context *msg_ctx = server_messaging_context();
54 if (likely(msg_ctx != NULL)) {
55 return msg_ctx;
57 smb_panic("Could not init winbindd's messaging context.\n");
58 return NULL;
61 /* Reload configuration */
63 static bool reload_services_file(const char *lfile)
65 bool ret;
67 if (lp_loaded()) {
68 const char *fname = lp_configfile();
70 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
71 set_dyn_CONFIGFILE(fname);
75 /* if this is a child, restore the logfile to the special
76 name - <domain>, idmap, etc. */
77 if (lfile && *lfile) {
78 lp_set_logfile(lfile);
81 reopen_logs();
82 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
84 reopen_logs();
85 load_interfaces();
87 return(ret);
91 /**************************************************************************** **
92 Handle a fault..
93 **************************************************************************** */
95 static void fault_quit(void)
97 dump_core();
100 static void winbindd_status(void)
102 struct winbindd_cli_state *tmp;
104 DEBUG(0, ("winbindd status:\n"));
106 /* Print client state information */
108 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
110 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
111 DEBUG(2, ("\tclient list:\n"));
112 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
113 DEBUGADD(2, ("\t\tpid %lu, sock %d (%s)\n",
114 (unsigned long)tmp->pid, tmp->sock,
115 client_is_idle(tmp) ? "idle" : "active"));
120 /* Flush client cache */
122 static void flush_caches(void)
124 /* We need to invalidate cached user list entries on a SIGHUP
125 otherwise cached access denied errors due to restrict anonymous
126 hang around until the sequence number changes. */
128 if (!wcache_invalidate_cache()) {
129 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
130 if (!winbindd_cache_validate_and_initialize()) {
131 exit(1);
136 static void flush_caches_noinit(void)
139 * We need to invalidate cached user list entries on a SIGHUP
140 * otherwise cached access denied errors due to restrict anonymous
141 * hang around until the sequence number changes.
142 * NB
143 * Skip uninitialized domains when flush cache.
144 * If domain is not initialized, it means it is never
145 * used or never become online. look, wcache_invalidate_cache()
146 * -> get_cache() -> init_dc_connection(). It causes a lot of traffic
147 * for unused domains and large traffic for primay domain's DC if there
148 * are many domains..
151 if (!wcache_invalidate_cache_noinit()) {
152 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
153 if (!winbindd_cache_validate_and_initialize()) {
154 exit(1);
159 /* Handle the signal by unlinking socket and exiting */
161 static void terminate(bool is_parent)
163 if (is_parent) {
164 /* When parent goes away we should
165 * remove the socket file. Not so
166 * when children terminate.
168 char *path = NULL;
170 if (asprintf(&path, "%s/%s",
171 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
172 unlink(path);
173 SAFE_FREE(path);
177 idmap_close();
179 trustdom_cache_shutdown();
181 gencache_stabilize();
183 #if 0
184 if (interactive) {
185 TALLOC_CTX *mem_ctx = talloc_init("end_description");
186 char *description = talloc_describe_all(mem_ctx);
188 DEBUG(3, ("tallocs left:\n%s\n", description));
189 talloc_destroy(mem_ctx);
191 #endif
193 if (is_parent) {
194 serverid_deregister(procid_self());
195 pidfile_unlink();
198 exit(0);
201 static void winbindd_sig_term_handler(struct tevent_context *ev,
202 struct tevent_signal *se,
203 int signum,
204 int count,
205 void *siginfo,
206 void *private_data)
208 bool *is_parent = talloc_get_type_abort(private_data, bool);
210 DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
211 signum, (int)*is_parent));
212 terminate(*is_parent);
215 bool winbindd_setup_sig_term_handler(bool parent)
217 struct tevent_signal *se;
218 bool *is_parent;
220 is_parent = talloc(winbind_event_context(), bool);
221 if (!is_parent) {
222 return false;
225 *is_parent = parent;
227 se = tevent_add_signal(winbind_event_context(),
228 is_parent,
229 SIGTERM, 0,
230 winbindd_sig_term_handler,
231 is_parent);
232 if (!se) {
233 DEBUG(0,("failed to setup SIGTERM handler"));
234 talloc_free(is_parent);
235 return false;
238 se = tevent_add_signal(winbind_event_context(),
239 is_parent,
240 SIGINT, 0,
241 winbindd_sig_term_handler,
242 is_parent);
243 if (!se) {
244 DEBUG(0,("failed to setup SIGINT handler"));
245 talloc_free(is_parent);
246 return false;
249 se = tevent_add_signal(winbind_event_context(),
250 is_parent,
251 SIGQUIT, 0,
252 winbindd_sig_term_handler,
253 is_parent);
254 if (!se) {
255 DEBUG(0,("failed to setup SIGINT handler"));
256 talloc_free(is_parent);
257 return false;
260 return true;
263 static void winbindd_sig_hup_handler(struct tevent_context *ev,
264 struct tevent_signal *se,
265 int signum,
266 int count,
267 void *siginfo,
268 void *private_data)
270 const char *file = (const char *)private_data;
272 DEBUG(1,("Reloading services after SIGHUP\n"));
273 flush_caches_noinit();
274 reload_services_file(file);
277 bool winbindd_setup_sig_hup_handler(const char *lfile)
279 struct tevent_signal *se;
280 char *file = NULL;
282 if (lfile) {
283 file = talloc_strdup(winbind_event_context(),
284 lfile);
285 if (!file) {
286 return false;
290 se = tevent_add_signal(winbind_event_context(),
291 winbind_event_context(),
292 SIGHUP, 0,
293 winbindd_sig_hup_handler,
294 file);
295 if (!se) {
296 return false;
299 return true;
302 static void winbindd_sig_chld_handler(struct tevent_context *ev,
303 struct tevent_signal *se,
304 int signum,
305 int count,
306 void *siginfo,
307 void *private_data)
309 pid_t pid;
311 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
312 winbind_child_died(pid);
316 static bool winbindd_setup_sig_chld_handler(void)
318 struct tevent_signal *se;
320 se = tevent_add_signal(winbind_event_context(),
321 winbind_event_context(),
322 SIGCHLD, 0,
323 winbindd_sig_chld_handler,
324 NULL);
325 if (!se) {
326 return false;
329 return true;
332 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
333 struct tevent_signal *se,
334 int signum,
335 int count,
336 void *siginfo,
337 void *private_data)
339 winbindd_status();
342 static bool winbindd_setup_sig_usr2_handler(void)
344 struct tevent_signal *se;
346 se = tevent_add_signal(winbind_event_context(),
347 winbind_event_context(),
348 SIGUSR2, 0,
349 winbindd_sig_usr2_handler,
350 NULL);
351 if (!se) {
352 return false;
355 return true;
358 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
359 static void msg_reload_services(struct messaging_context *msg,
360 void *private_data,
361 uint32_t msg_type,
362 struct server_id server_id,
363 DATA_BLOB *data)
365 /* Flush various caches */
366 flush_caches();
367 reload_services_file((const char *) private_data);
370 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
371 static void msg_shutdown(struct messaging_context *msg,
372 void *private_data,
373 uint32_t msg_type,
374 struct server_id server_id,
375 DATA_BLOB *data)
377 /* only the parent waits for this message */
378 DEBUG(0,("Got shutdown message\n"));
379 terminate(true);
383 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
384 void *private_data,
385 uint32_t msg_type,
386 struct server_id server_id,
387 DATA_BLOB *data)
389 uint8 ret;
390 pid_t child_pid;
391 NTSTATUS status;
393 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
394 "message.\n"));
397 * call the validation code from a child:
398 * so we don't block the main winbindd and the validation
399 * code can safely use fork/waitpid...
401 child_pid = sys_fork();
403 if (child_pid == -1) {
404 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
405 strerror(errno)));
406 return;
409 if (child_pid != 0) {
410 /* parent */
411 DEBUG(5, ("winbind_msg_validate_cache: child created with "
412 "pid %d.\n", (int)child_pid));
413 return;
416 /* child */
418 status = winbindd_reinit_after_fork(NULL, NULL);
419 if (!NT_STATUS_IS_OK(status)) {
420 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
421 nt_errstr(status)));
422 _exit(0);
425 /* install default SIGCHLD handler: validation code uses fork/waitpid */
426 CatchSignal(SIGCHLD, SIG_DFL);
428 ret = (uint8)winbindd_validate_cache_nobackup();
429 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
430 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
431 (size_t)1);
432 _exit(0);
435 static struct winbindd_dispatch_table {
436 enum winbindd_cmd cmd;
437 void (*fn)(struct winbindd_cli_state *state);
438 const char *winbindd_cmd_name;
439 } dispatch_table[] = {
441 /* Enumeration functions */
443 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
444 "LIST_TRUSTDOM" },
446 /* Miscellaneous */
448 { WINBINDD_INFO, winbindd_info, "INFO" },
449 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
450 "INTERFACE_VERSION" },
451 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
452 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
453 { WINBINDD_DC_INFO, winbindd_dc_info, "DC_INFO" },
454 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
455 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
456 "WINBINDD_PRIV_PIPE_DIR" },
458 /* Credential cache access */
459 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
460 { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
462 /* WINS functions */
464 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
465 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
467 /* End of list */
469 { WINBINDD_NUM_CMDS, NULL, "NONE" }
472 struct winbindd_async_dispatch_table {
473 enum winbindd_cmd cmd;
474 const char *cmd_name;
475 struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
476 struct tevent_context *ev,
477 struct winbindd_cli_state *cli,
478 struct winbindd_request *request);
479 NTSTATUS (*recv_req)(struct tevent_req *req,
480 struct winbindd_response *presp);
483 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
484 { WINBINDD_PING, "PING",
485 wb_ping_send, wb_ping_recv },
486 { WINBINDD_LOOKUPSID, "LOOKUPSID",
487 winbindd_lookupsid_send, winbindd_lookupsid_recv },
488 { WINBINDD_LOOKUPSIDS, "LOOKUPSIDS",
489 winbindd_lookupsids_send, winbindd_lookupsids_recv },
490 { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
491 winbindd_lookupname_send, winbindd_lookupname_recv },
492 { WINBINDD_SID_TO_UID, "SID_TO_UID",
493 winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
494 { WINBINDD_SID_TO_GID, "SID_TO_GID",
495 winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
496 { WINBINDD_UID_TO_SID, "UID_TO_SID",
497 winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
498 { WINBINDD_GID_TO_SID, "GID_TO_SID",
499 winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
500 { WINBINDD_SIDS_TO_XIDS, "SIDS_TO_XIDS",
501 winbindd_sids_to_xids_send, winbindd_sids_to_xids_recv },
502 { WINBINDD_GETPWSID, "GETPWSID",
503 winbindd_getpwsid_send, winbindd_getpwsid_recv },
504 { WINBINDD_GETPWNAM, "GETPWNAM",
505 winbindd_getpwnam_send, winbindd_getpwnam_recv },
506 { WINBINDD_GETPWUID, "GETPWUID",
507 winbindd_getpwuid_send, winbindd_getpwuid_recv },
508 { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
509 winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
510 { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
511 winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
512 { WINBINDD_GETGROUPS, "GETGROUPS",
513 winbindd_getgroups_send, winbindd_getgroups_recv },
514 { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
515 winbindd_show_sequence_send, winbindd_show_sequence_recv },
516 { WINBINDD_GETGRGID, "GETGRGID",
517 winbindd_getgrgid_send, winbindd_getgrgid_recv },
518 { WINBINDD_GETGRNAM, "GETGRNAM",
519 winbindd_getgrnam_send, winbindd_getgrnam_recv },
520 { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
521 winbindd_getusersids_send, winbindd_getusersids_recv },
522 { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
523 winbindd_lookuprids_send, winbindd_lookuprids_recv },
524 { WINBINDD_SETPWENT, "SETPWENT",
525 winbindd_setpwent_send, winbindd_setpwent_recv },
526 { WINBINDD_GETPWENT, "GETPWENT",
527 winbindd_getpwent_send, winbindd_getpwent_recv },
528 { WINBINDD_ENDPWENT, "ENDPWENT",
529 winbindd_endpwent_send, winbindd_endpwent_recv },
530 { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
531 winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
532 { WINBINDD_GETDCNAME, "GETDCNAME",
533 winbindd_getdcname_send, winbindd_getdcname_recv },
534 { WINBINDD_SETGRENT, "SETGRENT",
535 winbindd_setgrent_send, winbindd_setgrent_recv },
536 { WINBINDD_GETGRENT, "GETGRENT",
537 winbindd_getgrent_send, winbindd_getgrent_recv },
538 { WINBINDD_ENDGRENT, "ENDGRENT",
539 winbindd_endgrent_send, winbindd_endgrent_recv },
540 { WINBINDD_LIST_USERS, "LIST_USERS",
541 winbindd_list_users_send, winbindd_list_users_recv },
542 { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
543 winbindd_list_groups_send, winbindd_list_groups_recv },
544 { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
545 winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
546 { WINBINDD_PING_DC, "PING_DC",
547 winbindd_ping_dc_send, winbindd_ping_dc_recv },
548 { WINBINDD_PAM_AUTH, "PAM_AUTH",
549 winbindd_pam_auth_send, winbindd_pam_auth_recv },
550 { WINBINDD_PAM_LOGOFF, "PAM_LOGOFF",
551 winbindd_pam_logoff_send, winbindd_pam_logoff_recv },
552 { WINBINDD_PAM_CHAUTHTOK, "PAM_CHAUTHTOK",
553 winbindd_pam_chauthtok_send, winbindd_pam_chauthtok_recv },
554 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, "PAM_CHNG_PSWD_AUTH_CRAP",
555 winbindd_pam_chng_pswd_auth_crap_send,
556 winbindd_pam_chng_pswd_auth_crap_recv },
558 { 0, NULL, NULL, NULL }
561 static struct winbindd_async_dispatch_table async_priv_table[] = {
562 { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
563 winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
564 { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
565 winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
566 { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
567 winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
568 { WINBINDD_PAM_AUTH_CRAP, "PAM_AUTH_CRAP",
569 winbindd_pam_auth_crap_send, winbindd_pam_auth_crap_recv },
571 { 0, NULL, NULL, NULL }
574 static void wb_request_done(struct tevent_req *req);
576 static void process_request(struct winbindd_cli_state *state)
578 struct winbindd_dispatch_table *table = dispatch_table;
579 struct winbindd_async_dispatch_table *atable;
581 state->mem_ctx = talloc_named(state, 0, "winbind request");
582 if (state->mem_ctx == NULL)
583 return;
585 /* Remember who asked us. */
586 state->pid = state->request->pid;
588 state->cmd_name = "unknown request";
589 state->recv_fn = NULL;
591 /* Process command */
593 for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
594 if (state->request->cmd == atable->cmd) {
595 break;
599 if ((atable->send_req == NULL) && state->privileged) {
600 for (atable = async_priv_table; atable->send_req;
601 atable += 1) {
602 if (state->request->cmd == atable->cmd) {
603 break;
608 if (atable->send_req != NULL) {
609 struct tevent_req *req;
611 state->cmd_name = atable->cmd_name;
612 state->recv_fn = atable->recv_req;
614 DEBUG(10, ("process_request: Handling async request %d:%s\n",
615 (int)state->pid, state->cmd_name));
617 req = atable->send_req(state->mem_ctx, winbind_event_context(),
618 state, state->request);
619 if (req == NULL) {
620 DEBUG(0, ("process_request: atable->send failed for "
621 "%s\n", atable->cmd_name));
622 request_error(state);
623 return;
625 tevent_req_set_callback(req, wb_request_done, state);
626 return;
629 state->response = talloc_zero(state->mem_ctx,
630 struct winbindd_response);
631 if (state->response == NULL) {
632 DEBUG(10, ("talloc failed\n"));
633 remove_client(state);
634 return;
636 state->response->result = WINBINDD_PENDING;
637 state->response->length = sizeof(struct winbindd_response);
639 for (table = dispatch_table; table->fn; table++) {
640 if (state->request->cmd == table->cmd) {
641 DEBUG(10,("process_request: request fn %s\n",
642 table->winbindd_cmd_name ));
643 state->cmd_name = table->winbindd_cmd_name;
644 table->fn(state);
645 break;
649 if (!table->fn) {
650 DEBUG(10,("process_request: unknown request fn number %d\n",
651 (int)state->request->cmd ));
652 request_error(state);
656 static void wb_request_done(struct tevent_req *req)
658 struct winbindd_cli_state *state = tevent_req_callback_data(
659 req, struct winbindd_cli_state);
660 NTSTATUS status;
662 state->response = talloc_zero(state->mem_ctx,
663 struct winbindd_response);
664 if (state->response == NULL) {
665 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
666 (int)state->pid, state->cmd_name));
667 remove_client(state);
668 return;
670 state->response->result = WINBINDD_PENDING;
671 state->response->length = sizeof(struct winbindd_response);
673 status = state->recv_fn(req, state->response);
674 TALLOC_FREE(req);
676 DEBUG(10,("wb_request_done[%d:%s]: %s\n",
677 (int)state->pid, state->cmd_name, nt_errstr(status)));
679 if (!NT_STATUS_IS_OK(status)) {
680 request_error(state);
681 return;
683 request_ok(state);
687 * This is the main event loop of winbind requests. It goes through a
688 * state-machine of 3 read/write requests, 4 if you have extra data to send.
690 * An idle winbind client has a read request of 4 bytes outstanding,
691 * finalizing function is request_len_recv, checking the length. request_recv
692 * then processes the packet. The processing function then at some point has
693 * to call request_finished which schedules sending the response.
696 static void request_finished(struct winbindd_cli_state *state);
698 static void winbind_client_request_read(struct tevent_req *req);
699 static void winbind_client_response_written(struct tevent_req *req);
701 static void request_finished(struct winbindd_cli_state *state)
703 struct tevent_req *req;
705 TALLOC_FREE(state->request);
707 req = wb_resp_write_send(state, winbind_event_context(),
708 state->out_queue, state->sock,
709 state->response);
710 if (req == NULL) {
711 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
712 (int)state->pid, state->cmd_name));
713 remove_client(state);
714 return;
716 tevent_req_set_callback(req, winbind_client_response_written, state);
719 static void winbind_client_response_written(struct tevent_req *req)
721 struct winbindd_cli_state *state = tevent_req_callback_data(
722 req, struct winbindd_cli_state);
723 ssize_t ret;
724 int err;
726 ret = wb_resp_write_recv(req, &err);
727 TALLOC_FREE(req);
728 if (ret == -1) {
729 close(state->sock);
730 state->sock = -1;
731 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
732 (int)state->pid, state->cmd_name, strerror(err)));
733 remove_client(state);
734 return;
737 DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
738 "to client\n", (int)state->pid, state->cmd_name));
740 TALLOC_FREE(state->mem_ctx);
741 state->response = NULL;
742 state->cmd_name = "no request";
743 state->recv_fn = NULL;
745 req = wb_req_read_send(state, winbind_event_context(), state->sock,
746 WINBINDD_MAX_EXTRA_DATA);
747 if (req == NULL) {
748 remove_client(state);
749 return;
751 tevent_req_set_callback(req, winbind_client_request_read, state);
754 void request_error(struct winbindd_cli_state *state)
756 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
757 state->response->result = WINBINDD_ERROR;
758 request_finished(state);
761 void request_ok(struct winbindd_cli_state *state)
763 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
764 state->response->result = WINBINDD_OK;
765 request_finished(state);
768 /* Process a new connection by adding it to the client connection list */
770 static void new_connection(int listen_sock, bool privileged)
772 struct sockaddr_un sunaddr;
773 struct winbindd_cli_state *state;
774 struct tevent_req *req;
775 socklen_t len;
776 int sock;
778 /* Accept connection */
780 len = sizeof(sunaddr);
782 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr, &len);
784 if (sock == -1) {
785 if (errno != EINTR) {
786 DEBUG(0, ("Faild to accept socket - %s\n",
787 strerror(errno)));
789 return;
792 DEBUG(6,("accepted socket %d\n", sock));
794 /* Create new connection structure */
796 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
797 close(sock);
798 return;
801 state->sock = sock;
803 state->out_queue = tevent_queue_create(state, "winbind client reply");
804 if (state->out_queue == NULL) {
805 close(sock);
806 TALLOC_FREE(state);
807 return;
810 state->last_access = time(NULL);
812 state->privileged = privileged;
814 req = wb_req_read_send(state, winbind_event_context(), state->sock,
815 WINBINDD_MAX_EXTRA_DATA);
816 if (req == NULL) {
817 TALLOC_FREE(state);
818 close(sock);
819 return;
821 tevent_req_set_callback(req, winbind_client_request_read, state);
823 /* Add to connection list */
825 winbindd_add_client(state);
828 static void winbind_client_request_read(struct tevent_req *req)
830 struct winbindd_cli_state *state = tevent_req_callback_data(
831 req, struct winbindd_cli_state);
832 ssize_t ret;
833 int err;
835 ret = wb_req_read_recv(req, state, &state->request, &err);
836 TALLOC_FREE(req);
837 if (ret == -1) {
838 if (err == EPIPE) {
839 DEBUG(6, ("closing socket %d, client exited\n",
840 state->sock));
841 } else {
842 DEBUG(2, ("Could not read client request from fd %d: "
843 "%s\n", state->sock, strerror(err)));
845 close(state->sock);
846 state->sock = -1;
847 remove_client(state);
848 return;
850 process_request(state);
853 /* Remove a client connection from client connection list */
855 static void remove_client(struct winbindd_cli_state *state)
857 char c = 0;
858 int nwritten;
860 /* It's a dead client - hold a funeral */
862 if (state == NULL) {
863 return;
866 if (state->sock != -1) {
867 /* tell client, we are closing ... */
868 nwritten = write(state->sock, &c, sizeof(c));
869 if (nwritten == -1) {
870 DEBUG(2, ("final write to client failed: %s\n",
871 strerror(errno)));
874 /* Close socket */
876 close(state->sock);
877 state->sock = -1;
880 TALLOC_FREE(state->mem_ctx);
882 /* Remove from list and free */
884 winbindd_remove_client(state);
885 TALLOC_FREE(state);
888 /* Is a client idle? */
890 static bool client_is_idle(struct winbindd_cli_state *state) {
891 return (state->response == NULL &&
892 !state->pwent_state && !state->grent_state);
895 /* Shutdown client connection which has been idle for the longest time */
897 static bool remove_idle_client(void)
899 struct winbindd_cli_state *state, *remove_state = NULL;
900 time_t last_access = 0;
901 int nidle = 0;
903 for (state = winbindd_client_list(); state; state = state->next) {
904 if (client_is_idle(state)) {
905 nidle++;
906 if (!last_access || state->last_access < last_access) {
907 last_access = state->last_access;
908 remove_state = state;
913 if (remove_state) {
914 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
915 nidle, remove_state->sock, (unsigned int)remove_state->pid));
916 remove_client(remove_state);
917 return True;
920 return False;
923 struct winbindd_listen_state {
924 bool privileged;
925 int fd;
928 static void winbindd_listen_fde_handler(struct tevent_context *ev,
929 struct tevent_fd *fde,
930 uint16_t flags,
931 void *private_data)
933 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
934 struct winbindd_listen_state);
936 while (winbindd_num_clients() > lp_winbind_max_clients() - 1) {
937 DEBUG(5,("winbindd: Exceeding %d client "
938 "connections, removing idle "
939 "connection.\n", lp_winbind_max_clients()));
940 if (!remove_idle_client()) {
941 DEBUG(0,("winbindd: Exceeding %d "
942 "client connections, no idle "
943 "connection found\n",
944 lp_winbind_max_clients()));
945 break;
948 new_connection(s->fd, s->privileged);
952 * Winbindd socket accessor functions
955 const char *get_winbind_pipe_dir(void)
957 return lp_parm_const_string(-1, "winbindd", "socket dir", WINBINDD_SOCKET_DIR);
960 char *get_winbind_priv_pipe_dir(void)
962 return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
965 static bool winbindd_setup_listeners(void)
967 struct winbindd_listen_state *pub_state = NULL;
968 struct winbindd_listen_state *priv_state = NULL;
969 struct tevent_fd *fde;
971 pub_state = talloc(winbind_event_context(),
972 struct winbindd_listen_state);
973 if (!pub_state) {
974 goto failed;
977 pub_state->privileged = false;
978 pub_state->fd = create_pipe_sock(
979 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME, 0755);
980 if (pub_state->fd == -1) {
981 goto failed;
984 fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
985 TEVENT_FD_READ, winbindd_listen_fde_handler,
986 pub_state);
987 if (fde == NULL) {
988 close(pub_state->fd);
989 goto failed;
991 tevent_fd_set_auto_close(fde);
993 priv_state = talloc(winbind_event_context(),
994 struct winbindd_listen_state);
995 if (!priv_state) {
996 goto failed;
999 priv_state->privileged = true;
1000 priv_state->fd = create_pipe_sock(
1001 get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
1002 if (priv_state->fd == -1) {
1003 goto failed;
1006 fde = tevent_add_fd(winbind_event_context(), priv_state,
1007 priv_state->fd, TEVENT_FD_READ,
1008 winbindd_listen_fde_handler, priv_state);
1009 if (fde == NULL) {
1010 close(priv_state->fd);
1011 goto failed;
1013 tevent_fd_set_auto_close(fde);
1015 return true;
1016 failed:
1017 TALLOC_FREE(pub_state);
1018 TALLOC_FREE(priv_state);
1019 return false;
1022 bool winbindd_use_idmap_cache(void)
1024 return !opt_nocache;
1027 bool winbindd_use_cache(void)
1029 return !opt_nocache;
1032 void winbindd_register_handlers(void)
1034 /* Setup signal handlers */
1036 if (!winbindd_setup_sig_term_handler(true))
1037 exit(1);
1038 if (!winbindd_setup_sig_hup_handler(NULL))
1039 exit(1);
1040 if (!winbindd_setup_sig_chld_handler())
1041 exit(1);
1042 if (!winbindd_setup_sig_usr2_handler())
1043 exit(1);
1045 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1048 * Ensure all cache and idmap caches are consistent
1049 * and initialized before we startup.
1051 if (!winbindd_cache_validate_and_initialize()) {
1052 exit(1);
1055 /* get broadcast messages */
1057 if (!serverid_register(procid_self(),
1058 FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1059 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1060 exit(1);
1063 /* React on 'smbcontrol winbindd reload-config' in the same way
1064 as to SIGHUP signal */
1065 messaging_register(winbind_messaging_context(), NULL,
1066 MSG_SMB_CONF_UPDATED, msg_reload_services);
1067 messaging_register(winbind_messaging_context(), NULL,
1068 MSG_SHUTDOWN, msg_shutdown);
1070 /* Handle online/offline messages. */
1071 messaging_register(winbind_messaging_context(), NULL,
1072 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1073 messaging_register(winbind_messaging_context(), NULL,
1074 MSG_WINBIND_ONLINE, winbind_msg_online);
1075 messaging_register(winbind_messaging_context(), NULL,
1076 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1078 messaging_register(winbind_messaging_context(), NULL,
1079 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1081 messaging_register(winbind_messaging_context(), NULL,
1082 MSG_WINBIND_VALIDATE_CACHE,
1083 winbind_msg_validate_cache);
1085 messaging_register(winbind_messaging_context(), NULL,
1086 MSG_WINBIND_DUMP_DOMAIN_LIST,
1087 winbind_msg_dump_domain_list);
1089 messaging_register(winbind_messaging_context(), NULL,
1090 MSG_WINBIND_IP_DROPPED,
1091 winbind_msg_ip_dropped_parent);
1093 /* Register handler for MSG_DEBUG. */
1094 messaging_register(winbind_messaging_context(), NULL,
1095 MSG_DEBUG,
1096 winbind_msg_debug);
1098 netsamlogon_cache_init(); /* Non-critical */
1100 /* clear the cached list of trusted domains */
1102 wcache_tdc_clear();
1104 if (!init_domain_list()) {
1105 DEBUG(0,("unable to initialize domain list\n"));
1106 exit(1);
1109 init_idmap_child();
1110 init_locator_child();
1112 smb_nscd_flush_user_cache();
1113 smb_nscd_flush_group_cache();
1115 if (lp_allow_trusted_domains()) {
1116 if (tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1117 rescan_trusted_domains, NULL) == NULL) {
1118 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1119 exit(1);
1125 struct winbindd_addrchanged_state {
1126 struct addrchange_context *ctx;
1127 struct tevent_context *ev;
1128 struct messaging_context *msg_ctx;
1131 static void winbindd_addr_changed(struct tevent_req *req);
1133 static void winbindd_init_addrchange(TALLOC_CTX *mem_ctx,
1134 struct tevent_context *ev,
1135 struct messaging_context *msg_ctx)
1137 struct winbindd_addrchanged_state *state;
1138 struct tevent_req *req;
1139 NTSTATUS status;
1141 state = talloc(mem_ctx, struct winbindd_addrchanged_state);
1142 if (state == NULL) {
1143 DEBUG(10, ("talloc failed\n"));
1144 return;
1146 state->ev = ev;
1147 state->msg_ctx = msg_ctx;
1149 status = addrchange_context_create(state, &state->ctx);
1150 if (!NT_STATUS_IS_OK(status)) {
1151 DEBUG(10, ("addrchange_context_create failed: %s\n",
1152 nt_errstr(status)));
1153 TALLOC_FREE(state);
1154 return;
1156 req = addrchange_send(state, ev, state->ctx);
1157 if (req == NULL) {
1158 DEBUG(0, ("addrchange_send failed\n"));
1159 TALLOC_FREE(state);
1160 return;
1162 tevent_req_set_callback(req, winbindd_addr_changed, state);
1165 static void winbindd_addr_changed(struct tevent_req *req)
1167 struct winbindd_addrchanged_state *state = tevent_req_callback_data(
1168 req, struct winbindd_addrchanged_state);
1169 enum addrchange_type type;
1170 struct sockaddr_storage addr;
1171 NTSTATUS status;
1173 status = addrchange_recv(req, &type, &addr);
1174 TALLOC_FREE(req);
1175 if (!NT_STATUS_IS_OK(status)) {
1176 DEBUG(10, ("addrchange_recv failed: %s, stop listening\n",
1177 nt_errstr(status)));
1178 TALLOC_FREE(state);
1179 return;
1181 if (type == ADDRCHANGE_DEL) {
1182 char addrstr[INET6_ADDRSTRLEN];
1183 DATA_BLOB blob;
1185 print_sockaddr(addrstr, sizeof(addrstr), &addr);
1187 DEBUG(3, ("winbindd: kernel (AF_NETLINK) dropped ip %s\n",
1188 addrstr));
1190 blob = data_blob_const(addrstr, strlen(addrstr)+1);
1192 status = messaging_send(state->msg_ctx,
1193 messaging_server_id(state->msg_ctx),
1194 MSG_WINBIND_IP_DROPPED, &blob);
1195 if (!NT_STATUS_IS_OK(status)) {
1196 DEBUG(10, ("messaging_send failed: %s - ignoring\n",
1197 nt_errstr(status)));
1200 req = addrchange_send(state, state->ev, state->ctx);
1201 if (req == NULL) {
1202 DEBUG(0, ("addrchange_send failed\n"));
1203 TALLOC_FREE(state);
1204 return;
1206 tevent_req_set_callback(req, winbindd_addr_changed, state);
1209 /* Main function */
1211 int main(int argc, char **argv, char **envp)
1213 static bool is_daemon = False;
1214 static bool Fork = True;
1215 static bool log_stdout = False;
1216 static bool no_process_group = False;
1217 enum {
1218 OPT_DAEMON = 1000,
1219 OPT_FORK,
1220 OPT_NO_PROCESS_GROUP,
1221 OPT_LOG_STDOUT
1223 struct poptOption long_options[] = {
1224 POPT_AUTOHELP
1225 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1226 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1227 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1228 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1229 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1230 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1231 POPT_COMMON_SAMBA
1232 POPT_TABLEEND
1234 poptContext pc;
1235 int opt;
1236 TALLOC_CTX *frame;
1237 NTSTATUS status;
1240 * Do this before any other talloc operation
1242 talloc_enable_null_tracking();
1243 frame = talloc_stackframe();
1245 /* glibc (?) likes to print "User defined signal 1" and exit if a
1246 SIGUSR[12] is received before a handler is installed */
1248 CatchSignal(SIGUSR1, SIG_IGN);
1249 CatchSignal(SIGUSR2, SIG_IGN);
1251 fault_setup((void (*)(void *))fault_quit );
1252 dump_core_setup("winbindd");
1254 load_case_tables();
1256 /* Initialise for running in non-root mode */
1258 sec_init();
1260 set_remote_machine_name("winbindd", False);
1262 /* Set environment variable so we don't recursively call ourselves.
1263 This may also be useful interactively. */
1265 if ( !winbind_off() ) {
1266 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1267 exit(1);
1270 /* Initialise samba/rpc client stuff */
1272 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1274 while ((opt = poptGetNextOpt(pc)) != -1) {
1275 switch (opt) {
1276 /* Don't become a daemon */
1277 case OPT_DAEMON:
1278 is_daemon = True;
1279 break;
1280 case 'i':
1281 interactive = True;
1282 log_stdout = True;
1283 Fork = False;
1284 break;
1285 case OPT_FORK:
1286 Fork = false;
1287 break;
1288 case OPT_NO_PROCESS_GROUP:
1289 no_process_group = true;
1290 break;
1291 case OPT_LOG_STDOUT:
1292 log_stdout = true;
1293 break;
1294 case 'n':
1295 opt_nocache = true;
1296 break;
1297 default:
1298 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1299 poptBadOption(pc, 0), poptStrerror(opt));
1300 poptPrintUsage(pc, stderr, 0);
1301 exit(1);
1305 if (is_daemon && interactive) {
1306 d_fprintf(stderr,"\nERROR: "
1307 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1308 poptPrintUsage(pc, stderr, 0);
1309 exit(1);
1312 if (log_stdout && Fork) {
1313 d_fprintf(stderr, "\nERROR: "
1314 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1315 poptPrintUsage(pc, stderr, 0);
1316 exit(1);
1319 poptFreeContext(pc);
1321 if (!override_logfile) {
1322 char *lfile = NULL;
1323 if (asprintf(&lfile,"%s/log.winbindd",
1324 get_dyn_LOGFILEBASE()) > 0) {
1325 lp_set_logfile(lfile);
1326 SAFE_FREE(lfile);
1329 if (log_stdout) {
1330 setup_logging("winbindd", DEBUG_STDOUT);
1331 } else {
1332 setup_logging("winbindd", DEBUG_FILE);
1334 reopen_logs();
1336 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1337 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1339 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1340 DEBUG(0, ("error opening config file\n"));
1341 exit(1);
1344 /* Initialise messaging system */
1346 if (winbind_messaging_context() == NULL) {
1347 exit(1);
1350 if (!reload_services_file(NULL)) {
1351 DEBUG(0, ("error opening config file\n"));
1352 exit(1);
1355 if (!directory_exist(lp_lockdir())) {
1356 mkdir(lp_lockdir(), 0755);
1359 /* Setup names. */
1361 if (!init_names())
1362 exit(1);
1364 load_interfaces();
1366 if (!secrets_init()) {
1368 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1369 return False;
1372 /* Unblock all signals we are interested in as they may have been
1373 blocked by the parent process. */
1375 BlockSignals(False, SIGINT);
1376 BlockSignals(False, SIGQUIT);
1377 BlockSignals(False, SIGTERM);
1378 BlockSignals(False, SIGUSR1);
1379 BlockSignals(False, SIGUSR2);
1380 BlockSignals(False, SIGHUP);
1381 BlockSignals(False, SIGCHLD);
1383 if (!interactive)
1384 become_daemon(Fork, no_process_group, log_stdout);
1386 pidfile_create("winbindd");
1388 #if HAVE_SETPGID
1390 * If we're interactive we want to set our own process group for
1391 * signal management.
1393 if (interactive && !no_process_group)
1394 setpgid( (pid_t)0, (pid_t)0);
1395 #endif
1397 TimeInit();
1399 /* Don't use winbindd_reinit_after_fork here as
1400 * we're just starting up and haven't created any
1401 * winbindd-specific resources we must free yet. JRA.
1404 status = reinit_after_fork(winbind_messaging_context(),
1405 winbind_event_context(),
1406 procid_self(), false);
1407 if (!NT_STATUS_IS_OK(status)) {
1408 DEBUG(0,("reinit_after_fork() failed\n"));
1409 exit(1);
1412 winbindd_register_handlers();
1414 status = init_system_info();
1415 if (!NT_STATUS_IS_OK(status)) {
1416 DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
1417 nt_errstr(status)));
1418 exit(1);
1421 rpc_lsarpc_init(NULL);
1422 rpc_samr_init(NULL);
1424 winbindd_init_addrchange(NULL, winbind_event_context(),
1425 winbind_messaging_context());
1427 /* setup listen sockets */
1429 if (!winbindd_setup_listeners()) {
1430 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1431 exit(1);
1434 TALLOC_FREE(frame);
1435 /* Loop waiting for requests */
1436 while (1) {
1437 frame = talloc_stackframe();
1439 if (tevent_loop_once(winbind_event_context()) == -1) {
1440 DEBUG(1, ("tevent_loop_once() failed: %s\n",
1441 strerror(errno)));
1442 return 1;
1445 TALLOC_FREE(frame);
1448 return 0;