s3-winbindd: call dump_core_setup after command line option has been parsed
[Samba/gebeck_regimport.git] / source3 / winbindd / winbindd.c
blob20ee2fc06041be5ffe12198330857bd4b232e59d
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 char *fname = lp_configfile();
70 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
71 set_dyn_CONFIGFILE(fname);
73 TALLOC_FREE(fname);
76 /* if this is a child, restore the logfile to the special
77 name - <domain>, idmap, etc. */
78 if (lfile && *lfile) {
79 lp_set_logfile(lfile);
82 reopen_logs();
83 ret = lp_load_global(get_dyn_CONFIGFILE());
85 reopen_logs();
86 load_interfaces();
88 return(ret);
92 static void winbindd_status(void)
94 struct winbindd_cli_state *tmp;
96 DEBUG(0, ("winbindd status:\n"));
98 /* Print client state information */
100 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
102 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
103 DEBUG(2, ("\tclient list:\n"));
104 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
105 DEBUGADD(2, ("\t\tpid %lu, sock %d (%s)\n",
106 (unsigned long)tmp->pid, tmp->sock,
107 client_is_idle(tmp) ? "idle" : "active"));
112 /* Flush client cache */
114 static void flush_caches(void)
116 /* We need to invalidate cached user list entries on a SIGHUP
117 otherwise cached access denied errors due to restrict anonymous
118 hang around until the sequence number changes. */
120 if (!wcache_invalidate_cache()) {
121 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
122 if (!winbindd_cache_validate_and_initialize()) {
123 exit(1);
128 static void flush_caches_noinit(void)
131 * We need to invalidate cached user list entries on a SIGHUP
132 * otherwise cached access denied errors due to restrict anonymous
133 * hang around until the sequence number changes.
134 * NB
135 * Skip uninitialized domains when flush cache.
136 * If domain is not initialized, it means it is never
137 * used or never become online. look, wcache_invalidate_cache()
138 * -> get_cache() -> init_dc_connection(). It causes a lot of traffic
139 * for unused domains and large traffic for primay domain's DC if there
140 * are many domains..
143 if (!wcache_invalidate_cache_noinit()) {
144 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
145 if (!winbindd_cache_validate_and_initialize()) {
146 exit(1);
151 /* Handle the signal by unlinking socket and exiting */
153 static void terminate(bool is_parent)
155 if (is_parent) {
156 /* When parent goes away we should
157 * remove the socket file. Not so
158 * when children terminate.
160 char *path = NULL;
162 if (asprintf(&path, "%s/%s",
163 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
164 unlink(path);
165 SAFE_FREE(path);
169 idmap_close();
171 trustdom_cache_shutdown();
173 gencache_stabilize();
175 #if 0
176 if (interactive) {
177 TALLOC_CTX *mem_ctx = talloc_init("end_description");
178 char *description = talloc_describe_all(mem_ctx);
180 DEBUG(3, ("tallocs left:\n%s\n", description));
181 talloc_destroy(mem_ctx);
183 #endif
185 if (is_parent) {
186 serverid_deregister(procid_self());
187 pidfile_unlink();
190 exit(0);
193 static void winbindd_sig_term_handler(struct tevent_context *ev,
194 struct tevent_signal *se,
195 int signum,
196 int count,
197 void *siginfo,
198 void *private_data)
200 bool *is_parent = talloc_get_type_abort(private_data, bool);
202 DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
203 signum, (int)*is_parent));
204 terminate(*is_parent);
208 handle stdin becoming readable when we are in --foreground mode
210 static void winbindd_stdin_handler(struct tevent_context *ev,
211 struct tevent_fd *fde,
212 uint16_t flags,
213 void *private_data)
215 char c;
216 if (read(0, &c, 1) != 1) {
217 bool *is_parent = talloc_get_type_abort(private_data, bool);
219 /* we have reached EOF on stdin, which means the
220 parent has exited. Shutdown the server */
221 DEBUG(0,("EOF on stdin (is_parent=%d)\n",
222 (int)*is_parent));
223 terminate(*is_parent);
227 bool winbindd_setup_sig_term_handler(bool parent)
229 struct tevent_signal *se;
230 bool *is_parent;
232 is_parent = talloc(winbind_event_context(), bool);
233 if (!is_parent) {
234 return false;
237 *is_parent = parent;
239 se = tevent_add_signal(winbind_event_context(),
240 is_parent,
241 SIGTERM, 0,
242 winbindd_sig_term_handler,
243 is_parent);
244 if (!se) {
245 DEBUG(0,("failed to setup SIGTERM handler"));
246 talloc_free(is_parent);
247 return false;
250 se = tevent_add_signal(winbind_event_context(),
251 is_parent,
252 SIGINT, 0,
253 winbindd_sig_term_handler,
254 is_parent);
255 if (!se) {
256 DEBUG(0,("failed to setup SIGINT handler"));
257 talloc_free(is_parent);
258 return false;
261 se = tevent_add_signal(winbind_event_context(),
262 is_parent,
263 SIGQUIT, 0,
264 winbindd_sig_term_handler,
265 is_parent);
266 if (!se) {
267 DEBUG(0,("failed to setup SIGINT handler"));
268 talloc_free(is_parent);
269 return false;
272 return true;
275 bool winbindd_setup_stdin_handler(bool parent, bool foreground)
277 bool *is_parent;
279 if (foreground) {
280 is_parent = talloc(winbind_event_context(), bool);
281 if (!is_parent) {
282 return false;
285 *is_parent = parent;
287 /* if we are running in the foreground then look for
288 EOF on stdin, and exit if it happens. This allows
289 us to die if the parent process dies
291 tevent_add_fd(winbind_event_context(), is_parent, 0, TEVENT_FD_READ, winbindd_stdin_handler, is_parent);
294 return true;
297 static void winbindd_sig_hup_handler(struct tevent_context *ev,
298 struct tevent_signal *se,
299 int signum,
300 int count,
301 void *siginfo,
302 void *private_data)
304 const char *file = (const char *)private_data;
306 DEBUG(1,("Reloading services after SIGHUP\n"));
307 flush_caches_noinit();
308 reload_services_file(file);
311 bool winbindd_setup_sig_hup_handler(const char *lfile)
313 struct tevent_signal *se;
314 char *file = NULL;
316 if (lfile) {
317 file = talloc_strdup(winbind_event_context(),
318 lfile);
319 if (!file) {
320 return false;
324 se = tevent_add_signal(winbind_event_context(),
325 winbind_event_context(),
326 SIGHUP, 0,
327 winbindd_sig_hup_handler,
328 file);
329 if (!se) {
330 return false;
333 return true;
336 static void winbindd_sig_chld_handler(struct tevent_context *ev,
337 struct tevent_signal *se,
338 int signum,
339 int count,
340 void *siginfo,
341 void *private_data)
343 pid_t pid;
345 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
346 winbind_child_died(pid);
350 static bool winbindd_setup_sig_chld_handler(void)
352 struct tevent_signal *se;
354 se = tevent_add_signal(winbind_event_context(),
355 winbind_event_context(),
356 SIGCHLD, 0,
357 winbindd_sig_chld_handler,
358 NULL);
359 if (!se) {
360 return false;
363 return true;
366 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
367 struct tevent_signal *se,
368 int signum,
369 int count,
370 void *siginfo,
371 void *private_data)
373 winbindd_status();
376 static bool winbindd_setup_sig_usr2_handler(void)
378 struct tevent_signal *se;
380 se = tevent_add_signal(winbind_event_context(),
381 winbind_event_context(),
382 SIGUSR2, 0,
383 winbindd_sig_usr2_handler,
384 NULL);
385 if (!se) {
386 return false;
389 return true;
392 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
393 static void msg_reload_services(struct messaging_context *msg,
394 void *private_data,
395 uint32_t msg_type,
396 struct server_id server_id,
397 DATA_BLOB *data)
399 /* Flush various caches */
400 flush_caches();
401 reload_services_file((const char *) private_data);
404 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
405 static void msg_shutdown(struct messaging_context *msg,
406 void *private_data,
407 uint32_t msg_type,
408 struct server_id server_id,
409 DATA_BLOB *data)
411 /* only the parent waits for this message */
412 DEBUG(0,("Got shutdown message\n"));
413 terminate(true);
417 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
418 void *private_data,
419 uint32_t msg_type,
420 struct server_id server_id,
421 DATA_BLOB *data)
423 uint8 ret;
424 pid_t child_pid;
425 NTSTATUS status;
427 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
428 "message.\n"));
431 * call the validation code from a child:
432 * so we don't block the main winbindd and the validation
433 * code can safely use fork/waitpid...
435 child_pid = fork();
437 if (child_pid == -1) {
438 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
439 strerror(errno)));
440 return;
443 if (child_pid != 0) {
444 /* parent */
445 DEBUG(5, ("winbind_msg_validate_cache: child created with "
446 "pid %d.\n", (int)child_pid));
447 return;
450 /* child */
452 status = winbindd_reinit_after_fork(NULL, NULL);
453 if (!NT_STATUS_IS_OK(status)) {
454 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
455 nt_errstr(status)));
456 _exit(0);
459 /* install default SIGCHLD handler: validation code uses fork/waitpid */
460 CatchSignal(SIGCHLD, SIG_DFL);
462 ret = (uint8)winbindd_validate_cache_nobackup();
463 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
464 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
465 (size_t)1);
466 _exit(0);
469 static struct winbindd_dispatch_table {
470 enum winbindd_cmd cmd;
471 void (*fn)(struct winbindd_cli_state *state);
472 const char *winbindd_cmd_name;
473 } dispatch_table[] = {
475 /* Enumeration functions */
477 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
478 "LIST_TRUSTDOM" },
480 /* Miscellaneous */
482 { WINBINDD_INFO, winbindd_info, "INFO" },
483 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
484 "INTERFACE_VERSION" },
485 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
486 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
487 { WINBINDD_DC_INFO, winbindd_dc_info, "DC_INFO" },
488 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
489 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
490 "WINBINDD_PRIV_PIPE_DIR" },
492 /* Credential cache access */
493 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
494 { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
496 /* End of list */
498 { WINBINDD_NUM_CMDS, NULL, "NONE" }
501 struct winbindd_async_dispatch_table {
502 enum winbindd_cmd cmd;
503 const char *cmd_name;
504 struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
505 struct tevent_context *ev,
506 struct winbindd_cli_state *cli,
507 struct winbindd_request *request);
508 NTSTATUS (*recv_req)(struct tevent_req *req,
509 struct winbindd_response *presp);
512 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
513 { WINBINDD_PING, "PING",
514 wb_ping_send, wb_ping_recv },
515 { WINBINDD_LOOKUPSID, "LOOKUPSID",
516 winbindd_lookupsid_send, winbindd_lookupsid_recv },
517 { WINBINDD_LOOKUPSIDS, "LOOKUPSIDS",
518 winbindd_lookupsids_send, winbindd_lookupsids_recv },
519 { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
520 winbindd_lookupname_send, winbindd_lookupname_recv },
521 { WINBINDD_SID_TO_UID, "SID_TO_UID",
522 winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
523 { WINBINDD_SID_TO_GID, "SID_TO_GID",
524 winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
525 { WINBINDD_UID_TO_SID, "UID_TO_SID",
526 winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
527 { WINBINDD_GID_TO_SID, "GID_TO_SID",
528 winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
529 { WINBINDD_SIDS_TO_XIDS, "SIDS_TO_XIDS",
530 winbindd_sids_to_xids_send, winbindd_sids_to_xids_recv },
531 { WINBINDD_GETPWSID, "GETPWSID",
532 winbindd_getpwsid_send, winbindd_getpwsid_recv },
533 { WINBINDD_GETPWNAM, "GETPWNAM",
534 winbindd_getpwnam_send, winbindd_getpwnam_recv },
535 { WINBINDD_GETPWUID, "GETPWUID",
536 winbindd_getpwuid_send, winbindd_getpwuid_recv },
537 { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
538 winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
539 { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
540 winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
541 { WINBINDD_GETGROUPS, "GETGROUPS",
542 winbindd_getgroups_send, winbindd_getgroups_recv },
543 { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
544 winbindd_show_sequence_send, winbindd_show_sequence_recv },
545 { WINBINDD_GETGRGID, "GETGRGID",
546 winbindd_getgrgid_send, winbindd_getgrgid_recv },
547 { WINBINDD_GETGRNAM, "GETGRNAM",
548 winbindd_getgrnam_send, winbindd_getgrnam_recv },
549 { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
550 winbindd_getusersids_send, winbindd_getusersids_recv },
551 { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
552 winbindd_lookuprids_send, winbindd_lookuprids_recv },
553 { WINBINDD_SETPWENT, "SETPWENT",
554 winbindd_setpwent_send, winbindd_setpwent_recv },
555 { WINBINDD_GETPWENT, "GETPWENT",
556 winbindd_getpwent_send, winbindd_getpwent_recv },
557 { WINBINDD_ENDPWENT, "ENDPWENT",
558 winbindd_endpwent_send, winbindd_endpwent_recv },
559 { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
560 winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
561 { WINBINDD_GETDCNAME, "GETDCNAME",
562 winbindd_getdcname_send, winbindd_getdcname_recv },
563 { WINBINDD_SETGRENT, "SETGRENT",
564 winbindd_setgrent_send, winbindd_setgrent_recv },
565 { WINBINDD_GETGRENT, "GETGRENT",
566 winbindd_getgrent_send, winbindd_getgrent_recv },
567 { WINBINDD_ENDGRENT, "ENDGRENT",
568 winbindd_endgrent_send, winbindd_endgrent_recv },
569 { WINBINDD_LIST_USERS, "LIST_USERS",
570 winbindd_list_users_send, winbindd_list_users_recv },
571 { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
572 winbindd_list_groups_send, winbindd_list_groups_recv },
573 { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
574 winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
575 { WINBINDD_PING_DC, "PING_DC",
576 winbindd_ping_dc_send, winbindd_ping_dc_recv },
577 { WINBINDD_PAM_AUTH, "PAM_AUTH",
578 winbindd_pam_auth_send, winbindd_pam_auth_recv },
579 { WINBINDD_PAM_LOGOFF, "PAM_LOGOFF",
580 winbindd_pam_logoff_send, winbindd_pam_logoff_recv },
581 { WINBINDD_PAM_CHAUTHTOK, "PAM_CHAUTHTOK",
582 winbindd_pam_chauthtok_send, winbindd_pam_chauthtok_recv },
583 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, "PAM_CHNG_PSWD_AUTH_CRAP",
584 winbindd_pam_chng_pswd_auth_crap_send,
585 winbindd_pam_chng_pswd_auth_crap_recv },
586 { WINBINDD_WINS_BYIP, "WINS_BYIP",
587 winbindd_wins_byip_send, winbindd_wins_byip_recv },
588 { WINBINDD_WINS_BYNAME, "WINS_BYNAME",
589 winbindd_wins_byname_send, winbindd_wins_byname_recv },
591 { 0, NULL, NULL, NULL }
594 static struct winbindd_async_dispatch_table async_priv_table[] = {
595 { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
596 winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
597 { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
598 winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
599 { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
600 winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
601 { WINBINDD_PAM_AUTH_CRAP, "PAM_AUTH_CRAP",
602 winbindd_pam_auth_crap_send, winbindd_pam_auth_crap_recv },
604 { 0, NULL, NULL, NULL }
607 static void wb_request_done(struct tevent_req *req);
609 static void process_request(struct winbindd_cli_state *state)
611 struct winbindd_dispatch_table *table = dispatch_table;
612 struct winbindd_async_dispatch_table *atable;
614 state->mem_ctx = talloc_named(state, 0, "winbind request");
615 if (state->mem_ctx == NULL)
616 return;
618 /* Remember who asked us. */
619 state->pid = state->request->pid;
621 state->cmd_name = "unknown request";
622 state->recv_fn = NULL;
624 /* Process command */
626 for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
627 if (state->request->cmd == atable->cmd) {
628 break;
632 if ((atable->send_req == NULL) && state->privileged) {
633 for (atable = async_priv_table; atable->send_req;
634 atable += 1) {
635 if (state->request->cmd == atable->cmd) {
636 break;
641 if (atable->send_req != NULL) {
642 struct tevent_req *req;
644 state->cmd_name = atable->cmd_name;
645 state->recv_fn = atable->recv_req;
647 DEBUG(10, ("process_request: Handling async request %d:%s\n",
648 (int)state->pid, state->cmd_name));
650 req = atable->send_req(state->mem_ctx, winbind_event_context(),
651 state, state->request);
652 if (req == NULL) {
653 DEBUG(0, ("process_request: atable->send failed for "
654 "%s\n", atable->cmd_name));
655 request_error(state);
656 return;
658 tevent_req_set_callback(req, wb_request_done, state);
659 return;
662 state->response = talloc_zero(state->mem_ctx,
663 struct winbindd_response);
664 if (state->response == NULL) {
665 DEBUG(10, ("talloc failed\n"));
666 remove_client(state);
667 return;
669 state->response->result = WINBINDD_PENDING;
670 state->response->length = sizeof(struct winbindd_response);
672 for (table = dispatch_table; table->fn; table++) {
673 if (state->request->cmd == table->cmd) {
674 DEBUG(10,("process_request: request fn %s\n",
675 table->winbindd_cmd_name ));
676 state->cmd_name = table->winbindd_cmd_name;
677 table->fn(state);
678 break;
682 if (!table->fn) {
683 DEBUG(10,("process_request: unknown request fn number %d\n",
684 (int)state->request->cmd ));
685 request_error(state);
689 static void wb_request_done(struct tevent_req *req)
691 struct winbindd_cli_state *state = tevent_req_callback_data(
692 req, struct winbindd_cli_state);
693 NTSTATUS status;
695 state->response = talloc_zero(state->mem_ctx,
696 struct winbindd_response);
697 if (state->response == NULL) {
698 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
699 (int)state->pid, state->cmd_name));
700 remove_client(state);
701 return;
703 state->response->result = WINBINDD_PENDING;
704 state->response->length = sizeof(struct winbindd_response);
706 status = state->recv_fn(req, state->response);
707 TALLOC_FREE(req);
709 DEBUG(10,("wb_request_done[%d:%s]: %s\n",
710 (int)state->pid, state->cmd_name, nt_errstr(status)));
712 if (!NT_STATUS_IS_OK(status)) {
713 request_error(state);
714 return;
716 request_ok(state);
720 * This is the main event loop of winbind requests. It goes through a
721 * state-machine of 3 read/write requests, 4 if you have extra data to send.
723 * An idle winbind client has a read request of 4 bytes outstanding,
724 * finalizing function is request_len_recv, checking the length. request_recv
725 * then processes the packet. The processing function then at some point has
726 * to call request_finished which schedules sending the response.
729 static void request_finished(struct winbindd_cli_state *state);
731 static void winbind_client_request_read(struct tevent_req *req);
732 static void winbind_client_response_written(struct tevent_req *req);
734 static void request_finished(struct winbindd_cli_state *state)
736 struct tevent_req *req;
738 TALLOC_FREE(state->request);
740 req = wb_resp_write_send(state, winbind_event_context(),
741 state->out_queue, state->sock,
742 state->response);
743 if (req == NULL) {
744 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
745 (int)state->pid, state->cmd_name));
746 remove_client(state);
747 return;
749 tevent_req_set_callback(req, winbind_client_response_written, state);
752 static void winbind_client_response_written(struct tevent_req *req)
754 struct winbindd_cli_state *state = tevent_req_callback_data(
755 req, struct winbindd_cli_state);
756 ssize_t ret;
757 int err;
759 ret = wb_resp_write_recv(req, &err);
760 TALLOC_FREE(req);
761 if (ret == -1) {
762 close(state->sock);
763 state->sock = -1;
764 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
765 (int)state->pid, state->cmd_name, strerror(err)));
766 remove_client(state);
767 return;
770 DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
771 "to client\n", (int)state->pid, state->cmd_name));
773 TALLOC_FREE(state->mem_ctx);
774 state->response = NULL;
775 state->cmd_name = "no request";
776 state->recv_fn = NULL;
778 req = wb_req_read_send(state, winbind_event_context(), state->sock,
779 WINBINDD_MAX_EXTRA_DATA);
780 if (req == NULL) {
781 remove_client(state);
782 return;
784 tevent_req_set_callback(req, winbind_client_request_read, state);
787 void request_error(struct winbindd_cli_state *state)
789 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
790 state->response->result = WINBINDD_ERROR;
791 request_finished(state);
794 void request_ok(struct winbindd_cli_state *state)
796 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
797 state->response->result = WINBINDD_OK;
798 request_finished(state);
801 /* Process a new connection by adding it to the client connection list */
803 static void new_connection(int listen_sock, bool privileged)
805 struct sockaddr_un sunaddr;
806 struct winbindd_cli_state *state;
807 struct tevent_req *req;
808 socklen_t len;
809 int sock;
811 /* Accept connection */
813 len = sizeof(sunaddr);
815 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr, &len);
817 if (sock == -1) {
818 if (errno != EINTR) {
819 DEBUG(0, ("Faild to accept socket - %s\n",
820 strerror(errno)));
822 return;
825 DEBUG(6,("accepted socket %d\n", sock));
827 /* Create new connection structure */
829 if ((state = talloc_zero(NULL, struct winbindd_cli_state)) == NULL) {
830 close(sock);
831 return;
834 state->sock = sock;
836 state->out_queue = tevent_queue_create(state, "winbind client reply");
837 if (state->out_queue == NULL) {
838 close(sock);
839 TALLOC_FREE(state);
840 return;
843 state->last_access = time(NULL);
845 state->privileged = privileged;
847 req = wb_req_read_send(state, winbind_event_context(), state->sock,
848 WINBINDD_MAX_EXTRA_DATA);
849 if (req == NULL) {
850 TALLOC_FREE(state);
851 close(sock);
852 return;
854 tevent_req_set_callback(req, winbind_client_request_read, state);
856 /* Add to connection list */
858 winbindd_add_client(state);
861 static void winbind_client_request_read(struct tevent_req *req)
863 struct winbindd_cli_state *state = tevent_req_callback_data(
864 req, struct winbindd_cli_state);
865 ssize_t ret;
866 int err;
868 ret = wb_req_read_recv(req, state, &state->request, &err);
869 TALLOC_FREE(req);
870 if (ret == -1) {
871 if (err == EPIPE) {
872 DEBUG(6, ("closing socket %d, client exited\n",
873 state->sock));
874 } else {
875 DEBUG(2, ("Could not read client request from fd %d: "
876 "%s\n", state->sock, strerror(err)));
878 close(state->sock);
879 state->sock = -1;
880 remove_client(state);
881 return;
883 process_request(state);
886 /* Remove a client connection from client connection list */
888 static void remove_client(struct winbindd_cli_state *state)
890 char c = 0;
891 int nwritten;
893 /* It's a dead client - hold a funeral */
895 if (state == NULL) {
896 return;
899 if (state->sock != -1) {
900 /* tell client, we are closing ... */
901 nwritten = write(state->sock, &c, sizeof(c));
902 if (nwritten == -1) {
903 DEBUG(2, ("final write to client failed: %s\n",
904 strerror(errno)));
907 /* Close socket */
909 close(state->sock);
910 state->sock = -1;
913 TALLOC_FREE(state->mem_ctx);
915 /* Remove from list and free */
917 winbindd_remove_client(state);
918 TALLOC_FREE(state);
921 /* Is a client idle? */
923 static bool client_is_idle(struct winbindd_cli_state *state) {
924 return (state->response == NULL &&
925 !state->pwent_state && !state->grent_state);
928 /* Shutdown client connection which has been idle for the longest time */
930 static bool remove_idle_client(void)
932 struct winbindd_cli_state *state, *remove_state = NULL;
933 time_t last_access = 0;
934 int nidle = 0;
936 for (state = winbindd_client_list(); state; state = state->next) {
937 if (client_is_idle(state)) {
938 nidle++;
939 if (!last_access || state->last_access < last_access) {
940 last_access = state->last_access;
941 remove_state = state;
946 if (remove_state) {
947 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
948 nidle, remove_state->sock, (unsigned int)remove_state->pid));
949 remove_client(remove_state);
950 return True;
953 return False;
956 struct winbindd_listen_state {
957 bool privileged;
958 int fd;
961 static void winbindd_listen_fde_handler(struct tevent_context *ev,
962 struct tevent_fd *fde,
963 uint16_t flags,
964 void *private_data)
966 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
967 struct winbindd_listen_state);
969 while (winbindd_num_clients() > lp_winbind_max_clients() - 1) {
970 DEBUG(5,("winbindd: Exceeding %d client "
971 "connections, removing idle "
972 "connection.\n", lp_winbind_max_clients()));
973 if (!remove_idle_client()) {
974 DEBUG(0,("winbindd: Exceeding %d "
975 "client connections, no idle "
976 "connection found\n",
977 lp_winbind_max_clients()));
978 break;
981 new_connection(s->fd, s->privileged);
985 * Winbindd socket accessor functions
988 const char *get_winbind_pipe_dir(void)
990 return lp_parm_const_string(-1, "winbindd", "socket dir", get_dyn_WINBINDD_SOCKET_DIR());
993 char *get_winbind_priv_pipe_dir(void)
995 return state_path(WINBINDD_PRIV_SOCKET_SUBDIR);
998 static bool winbindd_setup_listeners(void)
1000 struct winbindd_listen_state *pub_state = NULL;
1001 struct winbindd_listen_state *priv_state = NULL;
1002 struct tevent_fd *fde;
1003 int rc;
1005 pub_state = talloc(winbind_event_context(),
1006 struct winbindd_listen_state);
1007 if (!pub_state) {
1008 goto failed;
1011 pub_state->privileged = false;
1012 pub_state->fd = create_pipe_sock(
1013 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME, 0755);
1014 if (pub_state->fd == -1) {
1015 goto failed;
1017 rc = listen(pub_state->fd, 5);
1018 if (rc < 0) {
1019 goto failed;
1022 fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
1023 TEVENT_FD_READ, winbindd_listen_fde_handler,
1024 pub_state);
1025 if (fde == NULL) {
1026 close(pub_state->fd);
1027 goto failed;
1029 tevent_fd_set_auto_close(fde);
1031 priv_state = talloc(winbind_event_context(),
1032 struct winbindd_listen_state);
1033 if (!priv_state) {
1034 goto failed;
1037 priv_state->privileged = true;
1038 priv_state->fd = create_pipe_sock(
1039 get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
1040 if (priv_state->fd == -1) {
1041 goto failed;
1043 rc = listen(priv_state->fd, 5);
1044 if (rc < 0) {
1045 goto failed;
1048 fde = tevent_add_fd(winbind_event_context(), priv_state,
1049 priv_state->fd, TEVENT_FD_READ,
1050 winbindd_listen_fde_handler, priv_state);
1051 if (fde == NULL) {
1052 close(priv_state->fd);
1053 goto failed;
1055 tevent_fd_set_auto_close(fde);
1057 return true;
1058 failed:
1059 TALLOC_FREE(pub_state);
1060 TALLOC_FREE(priv_state);
1061 return false;
1064 bool winbindd_use_idmap_cache(void)
1066 return !opt_nocache;
1069 bool winbindd_use_cache(void)
1071 return !opt_nocache;
1074 void winbindd_register_handlers(bool foreground)
1076 /* Setup signal handlers */
1078 if (!winbindd_setup_sig_term_handler(true))
1079 exit(1);
1080 if (!winbindd_setup_stdin_handler(true, foreground))
1081 exit(1);
1082 if (!winbindd_setup_sig_hup_handler(NULL))
1083 exit(1);
1084 if (!winbindd_setup_sig_chld_handler())
1085 exit(1);
1086 if (!winbindd_setup_sig_usr2_handler())
1087 exit(1);
1089 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1092 * Ensure all cache and idmap caches are consistent
1093 * and initialized before we startup.
1095 if (!winbindd_cache_validate_and_initialize()) {
1096 exit(1);
1099 /* get broadcast messages */
1101 if (!serverid_register(procid_self(),
1102 FLAG_MSG_GENERAL |
1103 FLAG_MSG_WINBIND |
1104 FLAG_MSG_DBWRAP)) {
1105 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1106 exit(1);
1109 /* React on 'smbcontrol winbindd reload-config' in the same way
1110 as to SIGHUP signal */
1111 messaging_register(winbind_messaging_context(), NULL,
1112 MSG_SMB_CONF_UPDATED, msg_reload_services);
1113 messaging_register(winbind_messaging_context(), NULL,
1114 MSG_SHUTDOWN, msg_shutdown);
1116 /* Handle online/offline messages. */
1117 messaging_register(winbind_messaging_context(), NULL,
1118 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1119 messaging_register(winbind_messaging_context(), NULL,
1120 MSG_WINBIND_ONLINE, winbind_msg_online);
1121 messaging_register(winbind_messaging_context(), NULL,
1122 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1124 messaging_register(winbind_messaging_context(), NULL,
1125 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1127 messaging_register(winbind_messaging_context(), NULL,
1128 MSG_WINBIND_VALIDATE_CACHE,
1129 winbind_msg_validate_cache);
1131 messaging_register(winbind_messaging_context(), NULL,
1132 MSG_WINBIND_DUMP_DOMAIN_LIST,
1133 winbind_msg_dump_domain_list);
1135 messaging_register(winbind_messaging_context(), NULL,
1136 MSG_WINBIND_IP_DROPPED,
1137 winbind_msg_ip_dropped_parent);
1139 /* Register handler for MSG_DEBUG. */
1140 messaging_register(winbind_messaging_context(), NULL,
1141 MSG_DEBUG,
1142 winbind_msg_debug);
1144 netsamlogon_cache_init(); /* Non-critical */
1146 /* clear the cached list of trusted domains */
1148 wcache_tdc_clear();
1150 if (!init_domain_list()) {
1151 DEBUG(0,("unable to initialize domain list\n"));
1152 exit(1);
1155 init_idmap_child();
1156 init_locator_child();
1158 smb_nscd_flush_user_cache();
1159 smb_nscd_flush_group_cache();
1161 if (lp_allow_trusted_domains()) {
1162 if (tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1163 rescan_trusted_domains, NULL) == NULL) {
1164 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1165 exit(1);
1171 struct winbindd_addrchanged_state {
1172 struct addrchange_context *ctx;
1173 struct tevent_context *ev;
1174 struct messaging_context *msg_ctx;
1177 static void winbindd_addr_changed(struct tevent_req *req);
1179 static void winbindd_init_addrchange(TALLOC_CTX *mem_ctx,
1180 struct tevent_context *ev,
1181 struct messaging_context *msg_ctx)
1183 struct winbindd_addrchanged_state *state;
1184 struct tevent_req *req;
1185 NTSTATUS status;
1187 state = talloc(mem_ctx, struct winbindd_addrchanged_state);
1188 if (state == NULL) {
1189 DEBUG(10, ("talloc failed\n"));
1190 return;
1192 state->ev = ev;
1193 state->msg_ctx = msg_ctx;
1195 status = addrchange_context_create(state, &state->ctx);
1196 if (!NT_STATUS_IS_OK(status)) {
1197 DEBUG(10, ("addrchange_context_create failed: %s\n",
1198 nt_errstr(status)));
1199 TALLOC_FREE(state);
1200 return;
1202 req = addrchange_send(state, ev, state->ctx);
1203 if (req == NULL) {
1204 DEBUG(0, ("addrchange_send failed\n"));
1205 TALLOC_FREE(state);
1206 return;
1208 tevent_req_set_callback(req, winbindd_addr_changed, state);
1211 static void winbindd_addr_changed(struct tevent_req *req)
1213 struct winbindd_addrchanged_state *state = tevent_req_callback_data(
1214 req, struct winbindd_addrchanged_state);
1215 enum addrchange_type type;
1216 struct sockaddr_storage addr;
1217 NTSTATUS status;
1219 status = addrchange_recv(req, &type, &addr);
1220 TALLOC_FREE(req);
1221 if (!NT_STATUS_IS_OK(status)) {
1222 DEBUG(10, ("addrchange_recv failed: %s, stop listening\n",
1223 nt_errstr(status)));
1224 TALLOC_FREE(state);
1225 return;
1227 if (type == ADDRCHANGE_DEL) {
1228 char addrstr[INET6_ADDRSTRLEN];
1229 DATA_BLOB blob;
1231 print_sockaddr(addrstr, sizeof(addrstr), &addr);
1233 DEBUG(3, ("winbindd: kernel (AF_NETLINK) dropped ip %s\n",
1234 addrstr));
1236 blob = data_blob_const(addrstr, strlen(addrstr)+1);
1238 status = messaging_send(state->msg_ctx,
1239 messaging_server_id(state->msg_ctx),
1240 MSG_WINBIND_IP_DROPPED, &blob);
1241 if (!NT_STATUS_IS_OK(status)) {
1242 DEBUG(10, ("messaging_send failed: %s - ignoring\n",
1243 nt_errstr(status)));
1246 req = addrchange_send(state, state->ev, state->ctx);
1247 if (req == NULL) {
1248 DEBUG(0, ("addrchange_send failed\n"));
1249 TALLOC_FREE(state);
1250 return;
1252 tevent_req_set_callback(req, winbindd_addr_changed, state);
1255 /* Main function */
1257 int main(int argc, char **argv, char **envp)
1259 static bool is_daemon = False;
1260 static bool Fork = True;
1261 static bool log_stdout = False;
1262 static bool no_process_group = False;
1263 enum {
1264 OPT_DAEMON = 1000,
1265 OPT_FORK,
1266 OPT_NO_PROCESS_GROUP,
1267 OPT_LOG_STDOUT
1269 struct poptOption long_options[] = {
1270 POPT_AUTOHELP
1271 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1272 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1273 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1274 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1275 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1276 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1277 POPT_COMMON_SAMBA
1278 POPT_TABLEEND
1280 poptContext pc;
1281 int opt;
1282 TALLOC_CTX *frame;
1283 NTSTATUS status;
1286 * Do this before any other talloc operation
1288 talloc_enable_null_tracking();
1289 frame = talloc_stackframe();
1291 setup_logging("winbindd", DEBUG_DEFAULT_STDOUT);
1293 /* glibc (?) likes to print "User defined signal 1" and exit if a
1294 SIGUSR[12] is received before a handler is installed */
1296 CatchSignal(SIGUSR1, SIG_IGN);
1297 CatchSignal(SIGUSR2, SIG_IGN);
1299 fault_setup();
1300 dump_core_setup("winbindd", lp_logfile());
1302 load_case_tables();
1304 /* Initialise for running in non-root mode */
1306 sec_init();
1308 set_remote_machine_name("winbindd", False);
1310 /* Set environment variable so we don't recursively call ourselves.
1311 This may also be useful interactively. */
1313 if ( !winbind_off() ) {
1314 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1315 exit(1);
1318 /* Initialise samba/rpc client stuff */
1320 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1322 while ((opt = poptGetNextOpt(pc)) != -1) {
1323 switch (opt) {
1324 /* Don't become a daemon */
1325 case OPT_DAEMON:
1326 is_daemon = True;
1327 break;
1328 case 'i':
1329 interactive = True;
1330 log_stdout = True;
1331 Fork = False;
1332 break;
1333 case OPT_FORK:
1334 Fork = false;
1335 break;
1336 case OPT_NO_PROCESS_GROUP:
1337 no_process_group = true;
1338 break;
1339 case OPT_LOG_STDOUT:
1340 log_stdout = true;
1341 break;
1342 case 'n':
1343 opt_nocache = true;
1344 break;
1345 default:
1346 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1347 poptBadOption(pc, 0), poptStrerror(opt));
1348 poptPrintUsage(pc, stderr, 0);
1349 exit(1);
1353 dump_core_setup("winbindd", lp_logfile());
1354 if (is_daemon && interactive) {
1355 d_fprintf(stderr,"\nERROR: "
1356 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1357 poptPrintUsage(pc, stderr, 0);
1358 exit(1);
1361 if (log_stdout && Fork) {
1362 d_fprintf(stderr, "\nERROR: "
1363 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1364 poptPrintUsage(pc, stderr, 0);
1365 exit(1);
1368 poptFreeContext(pc);
1370 if (!override_logfile) {
1371 char *lfile = NULL;
1372 if (asprintf(&lfile,"%s/log.winbindd",
1373 get_dyn_LOGFILEBASE()) > 0) {
1374 lp_set_logfile(lfile);
1375 SAFE_FREE(lfile);
1379 if (log_stdout) {
1380 setup_logging("winbindd", DEBUG_STDOUT);
1381 } else {
1382 setup_logging("winbindd", DEBUG_FILE);
1384 reopen_logs();
1386 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1387 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1389 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1390 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
1391 exit(1);
1393 dump_core_setup("winbindd", lp_logfile());
1395 /* Initialise messaging system */
1397 if (winbind_messaging_context() == NULL) {
1398 exit(1);
1401 if (!reload_services_file(NULL)) {
1402 DEBUG(0, ("error opening config file\n"));
1403 exit(1);
1406 if (!directory_exist(lp_lockdir())) {
1407 mkdir(lp_lockdir(), 0755);
1410 if (!directory_exist(lp_piddir())) {
1411 mkdir(lp_piddir(), 0755);
1414 /* Setup names. */
1416 if (!init_names())
1417 exit(1);
1419 load_interfaces();
1421 if (!secrets_init()) {
1423 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1424 return False;
1427 /* Unblock all signals we are interested in as they may have been
1428 blocked by the parent process. */
1430 BlockSignals(False, SIGINT);
1431 BlockSignals(False, SIGQUIT);
1432 BlockSignals(False, SIGTERM);
1433 BlockSignals(False, SIGUSR1);
1434 BlockSignals(False, SIGUSR2);
1435 BlockSignals(False, SIGHUP);
1436 BlockSignals(False, SIGCHLD);
1438 if (!interactive)
1439 become_daemon(Fork, no_process_group, log_stdout);
1441 pidfile_create("winbindd");
1443 #if HAVE_SETPGID
1445 * If we're interactive we want to set our own process group for
1446 * signal management.
1448 if (interactive && !no_process_group)
1449 setpgid( (pid_t)0, (pid_t)0);
1450 #endif
1452 TimeInit();
1454 /* Don't use winbindd_reinit_after_fork here as
1455 * we're just starting up and haven't created any
1456 * winbindd-specific resources we must free yet. JRA.
1459 status = reinit_after_fork(winbind_messaging_context(),
1460 winbind_event_context(),
1461 false);
1462 if (!NT_STATUS_IS_OK(status)) {
1463 DEBUG(0,("reinit_after_fork() failed\n"));
1464 exit(1);
1468 * Do not initialize the parent-child-pipe before becoming
1469 * a daemon: this is used to detect a died parent in the child
1470 * process.
1472 status = init_before_fork();
1473 if (!NT_STATUS_IS_OK(status)) {
1474 DEBUG(0, ("init_before_fork failed: %s\n", nt_errstr(status)));
1475 exit(1);
1478 winbindd_register_handlers(!Fork);
1480 status = init_system_session_info();
1481 if (!NT_STATUS_IS_OK(status)) {
1482 DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
1483 nt_errstr(status)));
1484 exit(1);
1487 rpc_lsarpc_init(NULL);
1488 rpc_samr_init(NULL);
1490 winbindd_init_addrchange(NULL, winbind_event_context(),
1491 winbind_messaging_context());
1493 /* setup listen sockets */
1495 if (!winbindd_setup_listeners()) {
1496 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1497 exit(1);
1500 TALLOC_FREE(frame);
1501 /* Loop waiting for requests */
1502 while (1) {
1503 frame = talloc_stackframe();
1505 if (tevent_loop_once(winbind_event_context()) == -1) {
1506 DEBUG(1, ("tevent_loop_once() failed: %s\n",
1507 strerror(errno)));
1508 return 1;
1511 TALLOC_FREE(frame);
1514 return 0;