s3-auth: Rename to init_system_session_info().
[Samba/gebeck_regimport.git] / source3 / winbindd / winbindd.c
blob22056e26caf0fa8a1eb4971f448008f57eeb93ce
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_global(get_dyn_CONFIGFILE());
84 reopen_logs();
85 load_interfaces();
87 return(ret);
91 static void winbindd_status(void)
93 struct winbindd_cli_state *tmp;
95 DEBUG(0, ("winbindd status:\n"));
97 /* Print client state information */
99 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
101 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
102 DEBUG(2, ("\tclient list:\n"));
103 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
104 DEBUGADD(2, ("\t\tpid %lu, sock %d (%s)\n",
105 (unsigned long)tmp->pid, tmp->sock,
106 client_is_idle(tmp) ? "idle" : "active"));
111 /* Flush client cache */
113 static void flush_caches(void)
115 /* We need to invalidate cached user list entries on a SIGHUP
116 otherwise cached access denied errors due to restrict anonymous
117 hang around until the sequence number changes. */
119 if (!wcache_invalidate_cache()) {
120 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
121 if (!winbindd_cache_validate_and_initialize()) {
122 exit(1);
127 static void flush_caches_noinit(void)
130 * We need to invalidate cached user list entries on a SIGHUP
131 * otherwise cached access denied errors due to restrict anonymous
132 * hang around until the sequence number changes.
133 * NB
134 * Skip uninitialized domains when flush cache.
135 * If domain is not initialized, it means it is never
136 * used or never become online. look, wcache_invalidate_cache()
137 * -> get_cache() -> init_dc_connection(). It causes a lot of traffic
138 * for unused domains and large traffic for primay domain's DC if there
139 * are many domains..
142 if (!wcache_invalidate_cache_noinit()) {
143 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
144 if (!winbindd_cache_validate_and_initialize()) {
145 exit(1);
150 /* Handle the signal by unlinking socket and exiting */
152 static void terminate(bool is_parent)
154 if (is_parent) {
155 /* When parent goes away we should
156 * remove the socket file. Not so
157 * when children terminate.
159 char *path = NULL;
161 if (asprintf(&path, "%s/%s",
162 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
163 unlink(path);
164 SAFE_FREE(path);
168 idmap_close();
170 trustdom_cache_shutdown();
172 gencache_stabilize();
174 #if 0
175 if (interactive) {
176 TALLOC_CTX *mem_ctx = talloc_init("end_description");
177 char *description = talloc_describe_all(mem_ctx);
179 DEBUG(3, ("tallocs left:\n%s\n", description));
180 talloc_destroy(mem_ctx);
182 #endif
184 if (is_parent) {
185 serverid_deregister(procid_self());
186 pidfile_unlink();
189 exit(0);
192 static void winbindd_sig_term_handler(struct tevent_context *ev,
193 struct tevent_signal *se,
194 int signum,
195 int count,
196 void *siginfo,
197 void *private_data)
199 bool *is_parent = talloc_get_type_abort(private_data, bool);
201 DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
202 signum, (int)*is_parent));
203 terminate(*is_parent);
207 handle stdin becoming readable when we are in --foreground mode
209 static void winbindd_stdin_handler(struct tevent_context *ev,
210 struct tevent_fd *fde,
211 uint16_t flags,
212 void *private_data)
214 char c;
215 if (read(0, &c, 1) != 1) {
216 bool *is_parent = talloc_get_type_abort(private_data, bool);
218 /* we have reached EOF on stdin, which means the
219 parent has exited. Shutdown the server */
220 DEBUG(0,("EOF on stdin (is_parent=%d)\n",
221 (int)*is_parent));
222 terminate(*is_parent);
226 bool winbindd_setup_sig_term_handler(bool parent)
228 struct tevent_signal *se;
229 bool *is_parent;
231 is_parent = talloc(winbind_event_context(), bool);
232 if (!is_parent) {
233 return false;
236 *is_parent = parent;
238 se = tevent_add_signal(winbind_event_context(),
239 is_parent,
240 SIGTERM, 0,
241 winbindd_sig_term_handler,
242 is_parent);
243 if (!se) {
244 DEBUG(0,("failed to setup SIGTERM handler"));
245 talloc_free(is_parent);
246 return false;
249 se = tevent_add_signal(winbind_event_context(),
250 is_parent,
251 SIGINT, 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 se = tevent_add_signal(winbind_event_context(),
261 is_parent,
262 SIGQUIT, 0,
263 winbindd_sig_term_handler,
264 is_parent);
265 if (!se) {
266 DEBUG(0,("failed to setup SIGINT handler"));
267 talloc_free(is_parent);
268 return false;
271 return true;
274 bool winbindd_setup_stdin_handler(bool parent, bool foreground)
276 bool *is_parent;
278 if (foreground) {
279 is_parent = talloc(winbind_event_context(), bool);
280 if (!is_parent) {
281 return false;
284 *is_parent = parent;
286 /* if we are running in the foreground then look for
287 EOF on stdin, and exit if it happens. This allows
288 us to die if the parent process dies
290 tevent_add_fd(winbind_event_context(), is_parent, 0, TEVENT_FD_READ, winbindd_stdin_handler, is_parent);
293 return true;
296 static void winbindd_sig_hup_handler(struct tevent_context *ev,
297 struct tevent_signal *se,
298 int signum,
299 int count,
300 void *siginfo,
301 void *private_data)
303 const char *file = (const char *)private_data;
305 DEBUG(1,("Reloading services after SIGHUP\n"));
306 flush_caches_noinit();
307 reload_services_file(file);
310 bool winbindd_setup_sig_hup_handler(const char *lfile)
312 struct tevent_signal *se;
313 char *file = NULL;
315 if (lfile) {
316 file = talloc_strdup(winbind_event_context(),
317 lfile);
318 if (!file) {
319 return false;
323 se = tevent_add_signal(winbind_event_context(),
324 winbind_event_context(),
325 SIGHUP, 0,
326 winbindd_sig_hup_handler,
327 file);
328 if (!se) {
329 return false;
332 return true;
335 static void winbindd_sig_chld_handler(struct tevent_context *ev,
336 struct tevent_signal *se,
337 int signum,
338 int count,
339 void *siginfo,
340 void *private_data)
342 pid_t pid;
344 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
345 winbind_child_died(pid);
349 static bool winbindd_setup_sig_chld_handler(void)
351 struct tevent_signal *se;
353 se = tevent_add_signal(winbind_event_context(),
354 winbind_event_context(),
355 SIGCHLD, 0,
356 winbindd_sig_chld_handler,
357 NULL);
358 if (!se) {
359 return false;
362 return true;
365 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
366 struct tevent_signal *se,
367 int signum,
368 int count,
369 void *siginfo,
370 void *private_data)
372 winbindd_status();
375 static bool winbindd_setup_sig_usr2_handler(void)
377 struct tevent_signal *se;
379 se = tevent_add_signal(winbind_event_context(),
380 winbind_event_context(),
381 SIGUSR2, 0,
382 winbindd_sig_usr2_handler,
383 NULL);
384 if (!se) {
385 return false;
388 return true;
391 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
392 static void msg_reload_services(struct messaging_context *msg,
393 void *private_data,
394 uint32_t msg_type,
395 struct server_id server_id,
396 DATA_BLOB *data)
398 /* Flush various caches */
399 flush_caches();
400 reload_services_file((const char *) private_data);
403 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
404 static void msg_shutdown(struct messaging_context *msg,
405 void *private_data,
406 uint32_t msg_type,
407 struct server_id server_id,
408 DATA_BLOB *data)
410 /* only the parent waits for this message */
411 DEBUG(0,("Got shutdown message\n"));
412 terminate(true);
416 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
417 void *private_data,
418 uint32_t msg_type,
419 struct server_id server_id,
420 DATA_BLOB *data)
422 uint8 ret;
423 pid_t child_pid;
424 NTSTATUS status;
426 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
427 "message.\n"));
430 * call the validation code from a child:
431 * so we don't block the main winbindd and the validation
432 * code can safely use fork/waitpid...
434 child_pid = fork();
436 if (child_pid == -1) {
437 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
438 strerror(errno)));
439 return;
442 if (child_pid != 0) {
443 /* parent */
444 DEBUG(5, ("winbind_msg_validate_cache: child created with "
445 "pid %d.\n", (int)child_pid));
446 return;
449 /* child */
451 status = winbindd_reinit_after_fork(NULL, NULL);
452 if (!NT_STATUS_IS_OK(status)) {
453 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
454 nt_errstr(status)));
455 _exit(0);
458 /* install default SIGCHLD handler: validation code uses fork/waitpid */
459 CatchSignal(SIGCHLD, SIG_DFL);
461 ret = (uint8)winbindd_validate_cache_nobackup();
462 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
463 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
464 (size_t)1);
465 _exit(0);
468 static struct winbindd_dispatch_table {
469 enum winbindd_cmd cmd;
470 void (*fn)(struct winbindd_cli_state *state);
471 const char *winbindd_cmd_name;
472 } dispatch_table[] = {
474 /* Enumeration functions */
476 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
477 "LIST_TRUSTDOM" },
479 /* Miscellaneous */
481 { WINBINDD_INFO, winbindd_info, "INFO" },
482 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
483 "INTERFACE_VERSION" },
484 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
485 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
486 { WINBINDD_DC_INFO, winbindd_dc_info, "DC_INFO" },
487 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
488 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
489 "WINBINDD_PRIV_PIPE_DIR" },
491 /* Credential cache access */
492 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
493 { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
495 /* End of list */
497 { WINBINDD_NUM_CMDS, NULL, "NONE" }
500 struct winbindd_async_dispatch_table {
501 enum winbindd_cmd cmd;
502 const char *cmd_name;
503 struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
504 struct tevent_context *ev,
505 struct winbindd_cli_state *cli,
506 struct winbindd_request *request);
507 NTSTATUS (*recv_req)(struct tevent_req *req,
508 struct winbindd_response *presp);
511 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
512 { WINBINDD_PING, "PING",
513 wb_ping_send, wb_ping_recv },
514 { WINBINDD_LOOKUPSID, "LOOKUPSID",
515 winbindd_lookupsid_send, winbindd_lookupsid_recv },
516 { WINBINDD_LOOKUPSIDS, "LOOKUPSIDS",
517 winbindd_lookupsids_send, winbindd_lookupsids_recv },
518 { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
519 winbindd_lookupname_send, winbindd_lookupname_recv },
520 { WINBINDD_SID_TO_UID, "SID_TO_UID",
521 winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
522 { WINBINDD_SID_TO_GID, "SID_TO_GID",
523 winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
524 { WINBINDD_UID_TO_SID, "UID_TO_SID",
525 winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
526 { WINBINDD_GID_TO_SID, "GID_TO_SID",
527 winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
528 { WINBINDD_SIDS_TO_XIDS, "SIDS_TO_XIDS",
529 winbindd_sids_to_xids_send, winbindd_sids_to_xids_recv },
530 { WINBINDD_GETPWSID, "GETPWSID",
531 winbindd_getpwsid_send, winbindd_getpwsid_recv },
532 { WINBINDD_GETPWNAM, "GETPWNAM",
533 winbindd_getpwnam_send, winbindd_getpwnam_recv },
534 { WINBINDD_GETPWUID, "GETPWUID",
535 winbindd_getpwuid_send, winbindd_getpwuid_recv },
536 { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
537 winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
538 { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
539 winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
540 { WINBINDD_GETGROUPS, "GETGROUPS",
541 winbindd_getgroups_send, winbindd_getgroups_recv },
542 { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
543 winbindd_show_sequence_send, winbindd_show_sequence_recv },
544 { WINBINDD_GETGRGID, "GETGRGID",
545 winbindd_getgrgid_send, winbindd_getgrgid_recv },
546 { WINBINDD_GETGRNAM, "GETGRNAM",
547 winbindd_getgrnam_send, winbindd_getgrnam_recv },
548 { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
549 winbindd_getusersids_send, winbindd_getusersids_recv },
550 { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
551 winbindd_lookuprids_send, winbindd_lookuprids_recv },
552 { WINBINDD_SETPWENT, "SETPWENT",
553 winbindd_setpwent_send, winbindd_setpwent_recv },
554 { WINBINDD_GETPWENT, "GETPWENT",
555 winbindd_getpwent_send, winbindd_getpwent_recv },
556 { WINBINDD_ENDPWENT, "ENDPWENT",
557 winbindd_endpwent_send, winbindd_endpwent_recv },
558 { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
559 winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
560 { WINBINDD_GETDCNAME, "GETDCNAME",
561 winbindd_getdcname_send, winbindd_getdcname_recv },
562 { WINBINDD_SETGRENT, "SETGRENT",
563 winbindd_setgrent_send, winbindd_setgrent_recv },
564 { WINBINDD_GETGRENT, "GETGRENT",
565 winbindd_getgrent_send, winbindd_getgrent_recv },
566 { WINBINDD_ENDGRENT, "ENDGRENT",
567 winbindd_endgrent_send, winbindd_endgrent_recv },
568 { WINBINDD_LIST_USERS, "LIST_USERS",
569 winbindd_list_users_send, winbindd_list_users_recv },
570 { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
571 winbindd_list_groups_send, winbindd_list_groups_recv },
572 { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
573 winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
574 { WINBINDD_PING_DC, "PING_DC",
575 winbindd_ping_dc_send, winbindd_ping_dc_recv },
576 { WINBINDD_PAM_AUTH, "PAM_AUTH",
577 winbindd_pam_auth_send, winbindd_pam_auth_recv },
578 { WINBINDD_PAM_LOGOFF, "PAM_LOGOFF",
579 winbindd_pam_logoff_send, winbindd_pam_logoff_recv },
580 { WINBINDD_PAM_CHAUTHTOK, "PAM_CHAUTHTOK",
581 winbindd_pam_chauthtok_send, winbindd_pam_chauthtok_recv },
582 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, "PAM_CHNG_PSWD_AUTH_CRAP",
583 winbindd_pam_chng_pswd_auth_crap_send,
584 winbindd_pam_chng_pswd_auth_crap_recv },
585 { WINBINDD_WINS_BYIP, "WINS_BYIP",
586 winbindd_wins_byip_send, winbindd_wins_byip_recv },
587 { WINBINDD_WINS_BYNAME, "WINS_BYNAME",
588 winbindd_wins_byname_send, winbindd_wins_byname_recv },
590 { 0, NULL, NULL, NULL }
593 static struct winbindd_async_dispatch_table async_priv_table[] = {
594 { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
595 winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
596 { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
597 winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
598 { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
599 winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
600 { WINBINDD_PAM_AUTH_CRAP, "PAM_AUTH_CRAP",
601 winbindd_pam_auth_crap_send, winbindd_pam_auth_crap_recv },
603 { 0, NULL, NULL, NULL }
606 static void wb_request_done(struct tevent_req *req);
608 static void process_request(struct winbindd_cli_state *state)
610 struct winbindd_dispatch_table *table = dispatch_table;
611 struct winbindd_async_dispatch_table *atable;
613 state->mem_ctx = talloc_named(state, 0, "winbind request");
614 if (state->mem_ctx == NULL)
615 return;
617 /* Remember who asked us. */
618 state->pid = state->request->pid;
620 state->cmd_name = "unknown request";
621 state->recv_fn = NULL;
623 /* Process command */
625 for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
626 if (state->request->cmd == atable->cmd) {
627 break;
631 if ((atable->send_req == NULL) && state->privileged) {
632 for (atable = async_priv_table; atable->send_req;
633 atable += 1) {
634 if (state->request->cmd == atable->cmd) {
635 break;
640 if (atable->send_req != NULL) {
641 struct tevent_req *req;
643 state->cmd_name = atable->cmd_name;
644 state->recv_fn = atable->recv_req;
646 DEBUG(10, ("process_request: Handling async request %d:%s\n",
647 (int)state->pid, state->cmd_name));
649 req = atable->send_req(state->mem_ctx, winbind_event_context(),
650 state, state->request);
651 if (req == NULL) {
652 DEBUG(0, ("process_request: atable->send failed for "
653 "%s\n", atable->cmd_name));
654 request_error(state);
655 return;
657 tevent_req_set_callback(req, wb_request_done, state);
658 return;
661 state->response = talloc_zero(state->mem_ctx,
662 struct winbindd_response);
663 if (state->response == NULL) {
664 DEBUG(10, ("talloc failed\n"));
665 remove_client(state);
666 return;
668 state->response->result = WINBINDD_PENDING;
669 state->response->length = sizeof(struct winbindd_response);
671 for (table = dispatch_table; table->fn; table++) {
672 if (state->request->cmd == table->cmd) {
673 DEBUG(10,("process_request: request fn %s\n",
674 table->winbindd_cmd_name ));
675 state->cmd_name = table->winbindd_cmd_name;
676 table->fn(state);
677 break;
681 if (!table->fn) {
682 DEBUG(10,("process_request: unknown request fn number %d\n",
683 (int)state->request->cmd ));
684 request_error(state);
688 static void wb_request_done(struct tevent_req *req)
690 struct winbindd_cli_state *state = tevent_req_callback_data(
691 req, struct winbindd_cli_state);
692 NTSTATUS status;
694 state->response = talloc_zero(state->mem_ctx,
695 struct winbindd_response);
696 if (state->response == NULL) {
697 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
698 (int)state->pid, state->cmd_name));
699 remove_client(state);
700 return;
702 state->response->result = WINBINDD_PENDING;
703 state->response->length = sizeof(struct winbindd_response);
705 status = state->recv_fn(req, state->response);
706 TALLOC_FREE(req);
708 DEBUG(10,("wb_request_done[%d:%s]: %s\n",
709 (int)state->pid, state->cmd_name, nt_errstr(status)));
711 if (!NT_STATUS_IS_OK(status)) {
712 request_error(state);
713 return;
715 request_ok(state);
719 * This is the main event loop of winbind requests. It goes through a
720 * state-machine of 3 read/write requests, 4 if you have extra data to send.
722 * An idle winbind client has a read request of 4 bytes outstanding,
723 * finalizing function is request_len_recv, checking the length. request_recv
724 * then processes the packet. The processing function then at some point has
725 * to call request_finished which schedules sending the response.
728 static void request_finished(struct winbindd_cli_state *state);
730 static void winbind_client_request_read(struct tevent_req *req);
731 static void winbind_client_response_written(struct tevent_req *req);
733 static void request_finished(struct winbindd_cli_state *state)
735 struct tevent_req *req;
737 TALLOC_FREE(state->request);
739 req = wb_resp_write_send(state, winbind_event_context(),
740 state->out_queue, state->sock,
741 state->response);
742 if (req == NULL) {
743 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
744 (int)state->pid, state->cmd_name));
745 remove_client(state);
746 return;
748 tevent_req_set_callback(req, winbind_client_response_written, state);
751 static void winbind_client_response_written(struct tevent_req *req)
753 struct winbindd_cli_state *state = tevent_req_callback_data(
754 req, struct winbindd_cli_state);
755 ssize_t ret;
756 int err;
758 ret = wb_resp_write_recv(req, &err);
759 TALLOC_FREE(req);
760 if (ret == -1) {
761 close(state->sock);
762 state->sock = -1;
763 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
764 (int)state->pid, state->cmd_name, strerror(err)));
765 remove_client(state);
766 return;
769 DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
770 "to client\n", (int)state->pid, state->cmd_name));
772 TALLOC_FREE(state->mem_ctx);
773 state->response = NULL;
774 state->cmd_name = "no request";
775 state->recv_fn = NULL;
777 req = wb_req_read_send(state, winbind_event_context(), state->sock,
778 WINBINDD_MAX_EXTRA_DATA);
779 if (req == NULL) {
780 remove_client(state);
781 return;
783 tevent_req_set_callback(req, winbind_client_request_read, state);
786 void request_error(struct winbindd_cli_state *state)
788 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
789 state->response->result = WINBINDD_ERROR;
790 request_finished(state);
793 void request_ok(struct winbindd_cli_state *state)
795 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
796 state->response->result = WINBINDD_OK;
797 request_finished(state);
800 /* Process a new connection by adding it to the client connection list */
802 static void new_connection(int listen_sock, bool privileged)
804 struct sockaddr_un sunaddr;
805 struct winbindd_cli_state *state;
806 struct tevent_req *req;
807 socklen_t len;
808 int sock;
810 /* Accept connection */
812 len = sizeof(sunaddr);
814 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr, &len);
816 if (sock == -1) {
817 if (errno != EINTR) {
818 DEBUG(0, ("Faild to accept socket - %s\n",
819 strerror(errno)));
821 return;
824 DEBUG(6,("accepted socket %d\n", sock));
826 /* Create new connection structure */
828 if ((state = talloc_zero(NULL, struct winbindd_cli_state)) == NULL) {
829 close(sock);
830 return;
833 state->sock = sock;
835 state->out_queue = tevent_queue_create(state, "winbind client reply");
836 if (state->out_queue == NULL) {
837 close(sock);
838 TALLOC_FREE(state);
839 return;
842 state->last_access = time(NULL);
844 state->privileged = privileged;
846 req = wb_req_read_send(state, winbind_event_context(), state->sock,
847 WINBINDD_MAX_EXTRA_DATA);
848 if (req == NULL) {
849 TALLOC_FREE(state);
850 close(sock);
851 return;
853 tevent_req_set_callback(req, winbind_client_request_read, state);
855 /* Add to connection list */
857 winbindd_add_client(state);
860 static void winbind_client_request_read(struct tevent_req *req)
862 struct winbindd_cli_state *state = tevent_req_callback_data(
863 req, struct winbindd_cli_state);
864 ssize_t ret;
865 int err;
867 ret = wb_req_read_recv(req, state, &state->request, &err);
868 TALLOC_FREE(req);
869 if (ret == -1) {
870 if (err == EPIPE) {
871 DEBUG(6, ("closing socket %d, client exited\n",
872 state->sock));
873 } else {
874 DEBUG(2, ("Could not read client request from fd %d: "
875 "%s\n", state->sock, strerror(err)));
877 close(state->sock);
878 state->sock = -1;
879 remove_client(state);
880 return;
882 process_request(state);
885 /* Remove a client connection from client connection list */
887 static void remove_client(struct winbindd_cli_state *state)
889 char c = 0;
890 int nwritten;
892 /* It's a dead client - hold a funeral */
894 if (state == NULL) {
895 return;
898 if (state->sock != -1) {
899 /* tell client, we are closing ... */
900 nwritten = write(state->sock, &c, sizeof(c));
901 if (nwritten == -1) {
902 DEBUG(2, ("final write to client failed: %s\n",
903 strerror(errno)));
906 /* Close socket */
908 close(state->sock);
909 state->sock = -1;
912 TALLOC_FREE(state->mem_ctx);
914 /* Remove from list and free */
916 winbindd_remove_client(state);
917 TALLOC_FREE(state);
920 /* Is a client idle? */
922 static bool client_is_idle(struct winbindd_cli_state *state) {
923 return (state->response == NULL &&
924 !state->pwent_state && !state->grent_state);
927 /* Shutdown client connection which has been idle for the longest time */
929 static bool remove_idle_client(void)
931 struct winbindd_cli_state *state, *remove_state = NULL;
932 time_t last_access = 0;
933 int nidle = 0;
935 for (state = winbindd_client_list(); state; state = state->next) {
936 if (client_is_idle(state)) {
937 nidle++;
938 if (!last_access || state->last_access < last_access) {
939 last_access = state->last_access;
940 remove_state = state;
945 if (remove_state) {
946 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
947 nidle, remove_state->sock, (unsigned int)remove_state->pid));
948 remove_client(remove_state);
949 return True;
952 return False;
955 struct winbindd_listen_state {
956 bool privileged;
957 int fd;
960 static void winbindd_listen_fde_handler(struct tevent_context *ev,
961 struct tevent_fd *fde,
962 uint16_t flags,
963 void *private_data)
965 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
966 struct winbindd_listen_state);
968 while (winbindd_num_clients() > lp_winbind_max_clients() - 1) {
969 DEBUG(5,("winbindd: Exceeding %d client "
970 "connections, removing idle "
971 "connection.\n", lp_winbind_max_clients()));
972 if (!remove_idle_client()) {
973 DEBUG(0,("winbindd: Exceeding %d "
974 "client connections, no idle "
975 "connection found\n",
976 lp_winbind_max_clients()));
977 break;
980 new_connection(s->fd, s->privileged);
984 * Winbindd socket accessor functions
987 const char *get_winbind_pipe_dir(void)
989 return lp_parm_const_string(-1, "winbindd", "socket dir", get_dyn_WINBINDD_SOCKET_DIR());
992 char *get_winbind_priv_pipe_dir(void)
994 return state_path(WINBINDD_PRIV_SOCKET_SUBDIR);
997 static bool winbindd_setup_listeners(void)
999 struct winbindd_listen_state *pub_state = NULL;
1000 struct winbindd_listen_state *priv_state = NULL;
1001 struct tevent_fd *fde;
1002 int rc;
1004 pub_state = talloc(winbind_event_context(),
1005 struct winbindd_listen_state);
1006 if (!pub_state) {
1007 goto failed;
1010 pub_state->privileged = false;
1011 pub_state->fd = create_pipe_sock(
1012 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME, 0755);
1013 if (pub_state->fd == -1) {
1014 goto failed;
1016 rc = listen(pub_state->fd, 5);
1017 if (rc < 0) {
1018 goto failed;
1021 fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
1022 TEVENT_FD_READ, winbindd_listen_fde_handler,
1023 pub_state);
1024 if (fde == NULL) {
1025 close(pub_state->fd);
1026 goto failed;
1028 tevent_fd_set_auto_close(fde);
1030 priv_state = talloc(winbind_event_context(),
1031 struct winbindd_listen_state);
1032 if (!priv_state) {
1033 goto failed;
1036 priv_state->privileged = true;
1037 priv_state->fd = create_pipe_sock(
1038 get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
1039 if (priv_state->fd == -1) {
1040 goto failed;
1042 rc = listen(priv_state->fd, 5);
1043 if (rc < 0) {
1044 goto failed;
1047 fde = tevent_add_fd(winbind_event_context(), priv_state,
1048 priv_state->fd, TEVENT_FD_READ,
1049 winbindd_listen_fde_handler, priv_state);
1050 if (fde == NULL) {
1051 close(priv_state->fd);
1052 goto failed;
1054 tevent_fd_set_auto_close(fde);
1056 return true;
1057 failed:
1058 TALLOC_FREE(pub_state);
1059 TALLOC_FREE(priv_state);
1060 return false;
1063 bool winbindd_use_idmap_cache(void)
1065 return !opt_nocache;
1068 bool winbindd_use_cache(void)
1070 return !opt_nocache;
1073 void winbindd_register_handlers(bool foreground)
1075 /* Setup signal handlers */
1077 if (!winbindd_setup_sig_term_handler(true))
1078 exit(1);
1079 if (!winbindd_setup_stdin_handler(true, foreground))
1080 exit(1);
1081 if (!winbindd_setup_sig_hup_handler(NULL))
1082 exit(1);
1083 if (!winbindd_setup_sig_chld_handler())
1084 exit(1);
1085 if (!winbindd_setup_sig_usr2_handler())
1086 exit(1);
1088 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1091 * Ensure all cache and idmap caches are consistent
1092 * and initialized before we startup.
1094 if (!winbindd_cache_validate_and_initialize()) {
1095 exit(1);
1098 /* get broadcast messages */
1100 if (!serverid_register(procid_self(),
1101 FLAG_MSG_GENERAL |
1102 FLAG_MSG_WINBIND |
1103 FLAG_MSG_DBWRAP)) {
1104 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1105 exit(1);
1108 /* React on 'smbcontrol winbindd reload-config' in the same way
1109 as to SIGHUP signal */
1110 messaging_register(winbind_messaging_context(), NULL,
1111 MSG_SMB_CONF_UPDATED, msg_reload_services);
1112 messaging_register(winbind_messaging_context(), NULL,
1113 MSG_SHUTDOWN, msg_shutdown);
1115 /* Handle online/offline messages. */
1116 messaging_register(winbind_messaging_context(), NULL,
1117 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1118 messaging_register(winbind_messaging_context(), NULL,
1119 MSG_WINBIND_ONLINE, winbind_msg_online);
1120 messaging_register(winbind_messaging_context(), NULL,
1121 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1123 messaging_register(winbind_messaging_context(), NULL,
1124 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1126 messaging_register(winbind_messaging_context(), NULL,
1127 MSG_WINBIND_VALIDATE_CACHE,
1128 winbind_msg_validate_cache);
1130 messaging_register(winbind_messaging_context(), NULL,
1131 MSG_WINBIND_DUMP_DOMAIN_LIST,
1132 winbind_msg_dump_domain_list);
1134 messaging_register(winbind_messaging_context(), NULL,
1135 MSG_WINBIND_IP_DROPPED,
1136 winbind_msg_ip_dropped_parent);
1138 /* Register handler for MSG_DEBUG. */
1139 messaging_register(winbind_messaging_context(), NULL,
1140 MSG_DEBUG,
1141 winbind_msg_debug);
1143 netsamlogon_cache_init(); /* Non-critical */
1145 /* clear the cached list of trusted domains */
1147 wcache_tdc_clear();
1149 if (!init_domain_list()) {
1150 DEBUG(0,("unable to initialize domain list\n"));
1151 exit(1);
1154 init_idmap_child();
1155 init_locator_child();
1157 smb_nscd_flush_user_cache();
1158 smb_nscd_flush_group_cache();
1160 if (lp_allow_trusted_domains()) {
1161 if (tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1162 rescan_trusted_domains, NULL) == NULL) {
1163 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1164 exit(1);
1170 struct winbindd_addrchanged_state {
1171 struct addrchange_context *ctx;
1172 struct tevent_context *ev;
1173 struct messaging_context *msg_ctx;
1176 static void winbindd_addr_changed(struct tevent_req *req);
1178 static void winbindd_init_addrchange(TALLOC_CTX *mem_ctx,
1179 struct tevent_context *ev,
1180 struct messaging_context *msg_ctx)
1182 struct winbindd_addrchanged_state *state;
1183 struct tevent_req *req;
1184 NTSTATUS status;
1186 state = talloc(mem_ctx, struct winbindd_addrchanged_state);
1187 if (state == NULL) {
1188 DEBUG(10, ("talloc failed\n"));
1189 return;
1191 state->ev = ev;
1192 state->msg_ctx = msg_ctx;
1194 status = addrchange_context_create(state, &state->ctx);
1195 if (!NT_STATUS_IS_OK(status)) {
1196 DEBUG(10, ("addrchange_context_create failed: %s\n",
1197 nt_errstr(status)));
1198 TALLOC_FREE(state);
1199 return;
1201 req = addrchange_send(state, ev, state->ctx);
1202 if (req == NULL) {
1203 DEBUG(0, ("addrchange_send failed\n"));
1204 TALLOC_FREE(state);
1205 return;
1207 tevent_req_set_callback(req, winbindd_addr_changed, state);
1210 static void winbindd_addr_changed(struct tevent_req *req)
1212 struct winbindd_addrchanged_state *state = tevent_req_callback_data(
1213 req, struct winbindd_addrchanged_state);
1214 enum addrchange_type type;
1215 struct sockaddr_storage addr;
1216 NTSTATUS status;
1218 status = addrchange_recv(req, &type, &addr);
1219 TALLOC_FREE(req);
1220 if (!NT_STATUS_IS_OK(status)) {
1221 DEBUG(10, ("addrchange_recv failed: %s, stop listening\n",
1222 nt_errstr(status)));
1223 TALLOC_FREE(state);
1224 return;
1226 if (type == ADDRCHANGE_DEL) {
1227 char addrstr[INET6_ADDRSTRLEN];
1228 DATA_BLOB blob;
1230 print_sockaddr(addrstr, sizeof(addrstr), &addr);
1232 DEBUG(3, ("winbindd: kernel (AF_NETLINK) dropped ip %s\n",
1233 addrstr));
1235 blob = data_blob_const(addrstr, strlen(addrstr)+1);
1237 status = messaging_send(state->msg_ctx,
1238 messaging_server_id(state->msg_ctx),
1239 MSG_WINBIND_IP_DROPPED, &blob);
1240 if (!NT_STATUS_IS_OK(status)) {
1241 DEBUG(10, ("messaging_send failed: %s - ignoring\n",
1242 nt_errstr(status)));
1245 req = addrchange_send(state, state->ev, state->ctx);
1246 if (req == NULL) {
1247 DEBUG(0, ("addrchange_send failed\n"));
1248 TALLOC_FREE(state);
1249 return;
1251 tevent_req_set_callback(req, winbindd_addr_changed, state);
1254 /* Main function */
1256 int main(int argc, char **argv, char **envp)
1258 static bool is_daemon = False;
1259 static bool Fork = True;
1260 static bool log_stdout = False;
1261 static bool no_process_group = False;
1262 enum {
1263 OPT_DAEMON = 1000,
1264 OPT_FORK,
1265 OPT_NO_PROCESS_GROUP,
1266 OPT_LOG_STDOUT
1268 struct poptOption long_options[] = {
1269 POPT_AUTOHELP
1270 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1271 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1272 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1273 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1274 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1275 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1276 POPT_COMMON_SAMBA
1277 POPT_TABLEEND
1279 poptContext pc;
1280 int opt;
1281 TALLOC_CTX *frame;
1282 NTSTATUS status;
1285 * Do this before any other talloc operation
1287 talloc_enable_null_tracking();
1288 frame = talloc_stackframe();
1290 setup_logging("winbindd", DEBUG_DEFAULT_STDOUT);
1292 /* glibc (?) likes to print "User defined signal 1" and exit if a
1293 SIGUSR[12] is received before a handler is installed */
1295 CatchSignal(SIGUSR1, SIG_IGN);
1296 CatchSignal(SIGUSR2, SIG_IGN);
1298 fault_setup();
1299 dump_core_setup("winbindd", lp_logfile());
1301 load_case_tables();
1303 /* Initialise for running in non-root mode */
1305 sec_init();
1307 set_remote_machine_name("winbindd", False);
1309 /* Set environment variable so we don't recursively call ourselves.
1310 This may also be useful interactively. */
1312 if ( !winbind_off() ) {
1313 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1314 exit(1);
1317 /* Initialise samba/rpc client stuff */
1319 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1321 while ((opt = poptGetNextOpt(pc)) != -1) {
1322 switch (opt) {
1323 /* Don't become a daemon */
1324 case OPT_DAEMON:
1325 is_daemon = True;
1326 break;
1327 case 'i':
1328 interactive = True;
1329 log_stdout = True;
1330 Fork = False;
1331 break;
1332 case OPT_FORK:
1333 Fork = false;
1334 break;
1335 case OPT_NO_PROCESS_GROUP:
1336 no_process_group = true;
1337 break;
1338 case OPT_LOG_STDOUT:
1339 log_stdout = true;
1340 break;
1341 case 'n':
1342 opt_nocache = true;
1343 break;
1344 default:
1345 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1346 poptBadOption(pc, 0), poptStrerror(opt));
1347 poptPrintUsage(pc, stderr, 0);
1348 exit(1);
1352 if (is_daemon && interactive) {
1353 d_fprintf(stderr,"\nERROR: "
1354 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1355 poptPrintUsage(pc, stderr, 0);
1356 exit(1);
1359 if (log_stdout && Fork) {
1360 d_fprintf(stderr, "\nERROR: "
1361 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1362 poptPrintUsage(pc, stderr, 0);
1363 exit(1);
1366 poptFreeContext(pc);
1368 if (!override_logfile) {
1369 char *lfile = NULL;
1370 if (asprintf(&lfile,"%s/log.winbindd",
1371 get_dyn_LOGFILEBASE()) > 0) {
1372 lp_set_logfile(lfile);
1373 SAFE_FREE(lfile);
1377 if (log_stdout) {
1378 setup_logging("winbindd", DEBUG_STDOUT);
1379 } else {
1380 setup_logging("winbindd", DEBUG_FILE);
1382 reopen_logs();
1384 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1385 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1387 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1388 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
1389 exit(1);
1392 /* Initialise messaging system */
1394 if (winbind_messaging_context() == NULL) {
1395 exit(1);
1398 if (!reload_services_file(NULL)) {
1399 DEBUG(0, ("error opening config file\n"));
1400 exit(1);
1403 if (!directory_exist(lp_lockdir())) {
1404 mkdir(lp_lockdir(), 0755);
1407 if (!directory_exist(lp_piddir())) {
1408 mkdir(lp_piddir(), 0755);
1411 /* Setup names. */
1413 if (!init_names())
1414 exit(1);
1416 load_interfaces();
1418 if (!secrets_init()) {
1420 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1421 return False;
1424 /* Unblock all signals we are interested in as they may have been
1425 blocked by the parent process. */
1427 BlockSignals(False, SIGINT);
1428 BlockSignals(False, SIGQUIT);
1429 BlockSignals(False, SIGTERM);
1430 BlockSignals(False, SIGUSR1);
1431 BlockSignals(False, SIGUSR2);
1432 BlockSignals(False, SIGHUP);
1433 BlockSignals(False, SIGCHLD);
1435 if (!interactive)
1436 become_daemon(Fork, no_process_group, log_stdout);
1438 pidfile_create("winbindd");
1440 #if HAVE_SETPGID
1442 * If we're interactive we want to set our own process group for
1443 * signal management.
1445 if (interactive && !no_process_group)
1446 setpgid( (pid_t)0, (pid_t)0);
1447 #endif
1449 TimeInit();
1451 /* Don't use winbindd_reinit_after_fork here as
1452 * we're just starting up and haven't created any
1453 * winbindd-specific resources we must free yet. JRA.
1456 status = reinit_after_fork(winbind_messaging_context(),
1457 winbind_event_context(),
1458 false);
1459 if (!NT_STATUS_IS_OK(status)) {
1460 DEBUG(0,("reinit_after_fork() failed\n"));
1461 exit(1);
1465 * Do not initialize the parent-child-pipe before becoming
1466 * a daemon: this is used to detect a died parent in the child
1467 * process.
1469 status = init_before_fork();
1470 if (!NT_STATUS_IS_OK(status)) {
1471 DEBUG(0, ("init_before_fork failed: %s\n", nt_errstr(status)));
1472 exit(1);
1475 winbindd_register_handlers(!Fork);
1477 status = init_system_session_info();
1478 if (!NT_STATUS_IS_OK(status)) {
1479 DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
1480 nt_errstr(status)));
1481 exit(1);
1484 rpc_lsarpc_init(NULL);
1485 rpc_samr_init(NULL);
1487 winbindd_init_addrchange(NULL, winbind_event_context(),
1488 winbind_messaging_context());
1490 /* setup listen sockets */
1492 if (!winbindd_setup_listeners()) {
1493 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1494 exit(1);
1497 TALLOC_FREE(frame);
1498 /* Loop waiting for requests */
1499 while (1) {
1500 frame = talloc_stackframe();
1502 if (tevent_loop_once(winbind_event_context()) == -1) {
1503 DEBUG(1, ("tevent_loop_once() failed: %s\n",
1504 strerror(errno)));
1505 return 1;
1508 TALLOC_FREE(frame);
1511 return 0;