s3: Convert WINBINDD_PAM_AUTH to the new async API
[Samba/ekacnet.git] / source3 / winbindd / winbindd.c
blobd9335d08d53c00b7da9449ed58f8f18b13754725
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind daemon for ntdom nss module
6 Copyright (C) by Tim Potter 2000-2002
7 Copyright (C) Andrew Tridgell 2002
8 Copyright (C) Jelmer Vernooij 2003
9 Copyright (C) Volker Lendecke 2004
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "includes.h"
26 #include "winbindd.h"
27 #include "../../nsswitch/libwbclient/wbc_async.h"
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_WINBIND
32 static void remove_client(struct winbindd_cli_state *state);
34 static bool opt_nocache = False;
35 static bool interactive = False;
37 extern bool override_logfile;
39 struct event_context *winbind_event_context(void)
41 static struct event_context *ctx;
43 if (!ctx && !(ctx = event_context_init(NULL))) {
44 smb_panic("Could not init winbind event context");
46 return ctx;
49 struct messaging_context *winbind_messaging_context(void)
51 static struct messaging_context *ctx;
53 if (ctx == NULL) {
54 ctx = messaging_init(NULL, procid_self(),
55 winbind_event_context());
57 if (ctx == NULL) {
58 DEBUG(0, ("Could not init winbind messaging context.\n"));
60 return ctx;
63 /* Reload configuration */
65 static bool reload_services_file(const char *lfile)
67 bool ret;
69 if (lp_loaded()) {
70 const char *fname = lp_configfile();
72 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
73 set_dyn_CONFIGFILE(fname);
77 /* if this is a child, restore the logfile to the special
78 name - <domain>, idmap, etc. */
79 if (lfile && *lfile) {
80 lp_set_logfile(lfile);
83 reopen_logs();
84 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
86 reopen_logs();
87 load_interfaces();
89 return(ret);
93 /**************************************************************************** **
94 Handle a fault..
95 **************************************************************************** */
97 static void fault_quit(void)
99 dump_core();
102 static void winbindd_status(void)
104 struct winbindd_cli_state *tmp;
106 DEBUG(0, ("winbindd status:\n"));
108 /* Print client state information */
110 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
112 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
113 DEBUG(2, ("\tclient list:\n"));
114 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
115 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
116 (unsigned long)tmp->pid, tmp->sock));
121 /* Print winbindd status to log file */
123 static void print_winbindd_status(void)
125 winbindd_status();
128 /* Flush client cache */
130 static void flush_caches(void)
132 /* We need to invalidate cached user list entries on a SIGHUP
133 otherwise cached access denied errors due to restrict anonymous
134 hang around until the sequence number changes. */
136 if (!wcache_invalidate_cache()) {
137 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
138 if (!winbindd_cache_validate_and_initialize()) {
139 exit(1);
144 static void flush_caches_noinit(void)
147 * We need to invalidate cached user list entries on a SIGHUP
148 * otherwise cached access denied errors due to restrict anonymous
149 * hang around until the sequence number changes.
150 * NB
151 * Skip uninitialized domains when flush cache.
152 * If domain is not initialized, it means it is never
153 * used or never become online. look, wcache_invalidate_cache()
154 * -> get_cache() -> init_dc_connection(). It causes a lot of traffic
155 * for unused domains and large traffic for primay domain's DC if there
156 * are many domains..
159 if (!wcache_invalidate_cache_noinit()) {
160 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
161 if (!winbindd_cache_validate_and_initialize()) {
162 exit(1);
167 /* Handle the signal by unlinking socket and exiting */
169 static void terminate(bool is_parent)
171 if (is_parent) {
172 /* When parent goes away we should
173 * remove the socket file. Not so
174 * when children terminate.
176 char *path = NULL;
178 if (asprintf(&path, "%s/%s",
179 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
180 unlink(path);
181 SAFE_FREE(path);
185 idmap_close();
187 trustdom_cache_shutdown();
189 gencache_stabilize();
191 #if 0
192 if (interactive) {
193 TALLOC_CTX *mem_ctx = talloc_init("end_description");
194 char *description = talloc_describe_all(mem_ctx);
196 DEBUG(3, ("tallocs left:\n%s\n", description));
197 talloc_destroy(mem_ctx);
199 #endif
201 if (is_parent) {
202 serverid_deregister_self();
203 pidfile_unlink();
206 exit(0);
209 static void winbindd_sig_term_handler(struct tevent_context *ev,
210 struct tevent_signal *se,
211 int signum,
212 int count,
213 void *siginfo,
214 void *private_data)
216 bool *is_parent = talloc_get_type_abort(private_data, bool);
218 DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
219 signum, (int)*is_parent));
220 terminate(*is_parent);
223 bool winbindd_setup_sig_term_handler(bool parent)
225 struct tevent_signal *se;
226 bool *is_parent;
228 is_parent = talloc(winbind_event_context(), bool);
229 if (!is_parent) {
230 return false;
233 *is_parent = parent;
235 se = tevent_add_signal(winbind_event_context(),
236 is_parent,
237 SIGTERM, 0,
238 winbindd_sig_term_handler,
239 is_parent);
240 if (!se) {
241 DEBUG(0,("failed to setup SIGTERM handler"));
242 talloc_free(is_parent);
243 return false;
246 se = tevent_add_signal(winbind_event_context(),
247 is_parent,
248 SIGINT, 0,
249 winbindd_sig_term_handler,
250 is_parent);
251 if (!se) {
252 DEBUG(0,("failed to setup SIGINT handler"));
253 talloc_free(is_parent);
254 return false;
257 se = tevent_add_signal(winbind_event_context(),
258 is_parent,
259 SIGQUIT, 0,
260 winbindd_sig_term_handler,
261 is_parent);
262 if (!se) {
263 DEBUG(0,("failed to setup SIGINT handler"));
264 talloc_free(is_parent);
265 return false;
268 return true;
271 static void winbindd_sig_hup_handler(struct tevent_context *ev,
272 struct tevent_signal *se,
273 int signum,
274 int count,
275 void *siginfo,
276 void *private_data)
278 const char *file = (const char *)private_data;
280 DEBUG(1,("Reloading services after SIGHUP\n"));
281 flush_caches_noinit();
282 reload_services_file(file);
285 bool winbindd_setup_sig_hup_handler(const char *lfile)
287 struct tevent_signal *se;
288 char *file = NULL;
290 if (lfile) {
291 file = talloc_strdup(winbind_event_context(),
292 lfile);
293 if (!file) {
294 return false;
298 se = tevent_add_signal(winbind_event_context(),
299 winbind_event_context(),
300 SIGHUP, 0,
301 winbindd_sig_hup_handler,
302 file);
303 if (!se) {
304 return false;
307 return true;
310 static void winbindd_sig_chld_handler(struct tevent_context *ev,
311 struct tevent_signal *se,
312 int signum,
313 int count,
314 void *siginfo,
315 void *private_data)
317 pid_t pid;
319 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
320 winbind_child_died(pid);
324 static bool winbindd_setup_sig_chld_handler(void)
326 struct tevent_signal *se;
328 se = tevent_add_signal(winbind_event_context(),
329 winbind_event_context(),
330 SIGCHLD, 0,
331 winbindd_sig_chld_handler,
332 NULL);
333 if (!se) {
334 return false;
337 return true;
340 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
341 struct tevent_signal *se,
342 int signum,
343 int count,
344 void *siginfo,
345 void *private_data)
347 print_winbindd_status();
350 static bool winbindd_setup_sig_usr2_handler(void)
352 struct tevent_signal *se;
354 se = tevent_add_signal(winbind_event_context(),
355 winbind_event_context(),
356 SIGUSR2, 0,
357 winbindd_sig_usr2_handler,
358 NULL);
359 if (!se) {
360 return false;
363 return true;
366 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
367 static void msg_reload_services(struct messaging_context *msg,
368 void *private_data,
369 uint32_t msg_type,
370 struct server_id server_id,
371 DATA_BLOB *data)
373 /* Flush various caches */
374 flush_caches();
375 reload_services_file((const char *) private_data);
378 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
379 static void msg_shutdown(struct messaging_context *msg,
380 void *private_data,
381 uint32_t msg_type,
382 struct server_id server_id,
383 DATA_BLOB *data)
385 /* only the parent waits for this message */
386 DEBUG(0,("Got shutdown message\n"));
387 terminate(true);
391 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
392 void *private_data,
393 uint32_t msg_type,
394 struct server_id server_id,
395 DATA_BLOB *data)
397 uint8 ret;
398 pid_t child_pid;
400 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
401 "message.\n"));
404 * call the validation code from a child:
405 * so we don't block the main winbindd and the validation
406 * code can safely use fork/waitpid...
408 child_pid = sys_fork();
410 if (child_pid == -1) {
411 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
412 strerror(errno)));
413 return;
416 if (child_pid != 0) {
417 /* parent */
418 DEBUG(5, ("winbind_msg_validate_cache: child created with "
419 "pid %d.\n", (int)child_pid));
420 return;
423 /* child */
425 if (!winbindd_reinit_after_fork(NULL)) {
426 _exit(0);
429 /* install default SIGCHLD handler: validation code uses fork/waitpid */
430 CatchSignal(SIGCHLD, SIG_DFL);
432 ret = (uint8)winbindd_validate_cache_nobackup();
433 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
434 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
435 (size_t)1);
436 _exit(0);
439 static struct winbindd_dispatch_table {
440 enum winbindd_cmd cmd;
441 void (*fn)(struct winbindd_cli_state *state);
442 const char *winbindd_cmd_name;
443 } dispatch_table[] = {
445 /* PAM auth functions */
447 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
448 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
449 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
450 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
452 /* Enumeration functions */
454 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
455 "LIST_TRUSTDOM" },
457 /* Miscellaneous */
459 { WINBINDD_INFO, winbindd_info, "INFO" },
460 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
461 "INTERFACE_VERSION" },
462 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
463 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
464 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
465 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
466 "WINBINDD_PRIV_PIPE_DIR" },
468 /* Credential cache access */
469 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
470 { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
472 /* WINS functions */
474 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
475 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
477 /* End of list */
479 { WINBINDD_NUM_CMDS, NULL, "NONE" }
482 struct winbindd_async_dispatch_table {
483 enum winbindd_cmd cmd;
484 const char *cmd_name;
485 struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
486 struct tevent_context *ev,
487 struct winbindd_cli_state *cli,
488 struct winbindd_request *request);
489 NTSTATUS (*recv_req)(struct tevent_req *req,
490 struct winbindd_response *presp);
493 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
494 { WINBINDD_PING, "PING",
495 wb_ping_send, wb_ping_recv },
496 { WINBINDD_LOOKUPSID, "LOOKUPSID",
497 winbindd_lookupsid_send, winbindd_lookupsid_recv },
498 { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
499 winbindd_lookupname_send, winbindd_lookupname_recv },
500 { WINBINDD_SID_TO_UID, "SID_TO_UID",
501 winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
502 { WINBINDD_SID_TO_GID, "SID_TO_GID",
503 winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
504 { WINBINDD_UID_TO_SID, "UID_TO_SID",
505 winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
506 { WINBINDD_GID_TO_SID, "GID_TO_SID",
507 winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
508 { WINBINDD_GETPWSID, "GETPWSID",
509 winbindd_getpwsid_send, winbindd_getpwsid_recv },
510 { WINBINDD_GETPWNAM, "GETPWNAM",
511 winbindd_getpwnam_send, winbindd_getpwnam_recv },
512 { WINBINDD_GETPWUID, "GETPWUID",
513 winbindd_getpwuid_send, winbindd_getpwuid_recv },
514 { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
515 winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
516 { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
517 winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
518 { WINBINDD_GETGROUPS, "GETGROUPS",
519 winbindd_getgroups_send, winbindd_getgroups_recv },
520 { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
521 winbindd_show_sequence_send, winbindd_show_sequence_recv },
522 { WINBINDD_GETGRGID, "GETGRGID",
523 winbindd_getgrgid_send, winbindd_getgrgid_recv },
524 { WINBINDD_GETGRNAM, "GETGRNAM",
525 winbindd_getgrnam_send, winbindd_getgrnam_recv },
526 { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
527 winbindd_getusersids_send, winbindd_getusersids_recv },
528 { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
529 winbindd_lookuprids_send, winbindd_lookuprids_recv },
530 { WINBINDD_SETPWENT, "SETPWENT",
531 winbindd_setpwent_send, winbindd_setpwent_recv },
532 { WINBINDD_GETPWENT, "GETPWENT",
533 winbindd_getpwent_send, winbindd_getpwent_recv },
534 { WINBINDD_ENDPWENT, "ENDPWENT",
535 winbindd_endpwent_send, winbindd_endpwent_recv },
536 { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
537 winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
538 { WINBINDD_GETDCNAME, "GETDCNAME",
539 winbindd_getdcname_send, winbindd_getdcname_recv },
540 { WINBINDD_SETGRENT, "SETGRENT",
541 winbindd_setgrent_send, winbindd_setgrent_recv },
542 { WINBINDD_GETGRENT, "GETGRENT",
543 winbindd_getgrent_send, winbindd_getgrent_recv },
544 { WINBINDD_ENDGRENT, "ENDGRENT",
545 winbindd_endgrent_send, winbindd_endgrent_recv },
546 { WINBINDD_LIST_USERS, "LIST_USERS",
547 winbindd_list_users_send, winbindd_list_users_recv },
548 { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
549 winbindd_list_groups_send, winbindd_list_groups_recv },
550 { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
551 winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
552 { WINBINDD_PING_DC, "PING_DC",
553 winbindd_ping_dc_send, winbindd_ping_dc_recv },
554 { WINBINDD_PAM_AUTH, "PAM_AUTH",
555 winbindd_pam_auth_send, winbindd_pam_auth_recv },
557 { 0, NULL, NULL, NULL }
560 static struct winbindd_async_dispatch_table async_priv_table[] = {
561 { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
562 winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
563 { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
564 winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
565 { WINBINDD_SET_MAPPING, "SET_MAPPING",
566 winbindd_set_mapping_send, winbindd_set_mapping_recv },
567 { WINBINDD_REMOVE_MAPPING, "SET_MAPPING",
568 winbindd_remove_mapping_send, winbindd_remove_mapping_recv },
569 { WINBINDD_SET_HWM, "SET_HWM",
570 winbindd_set_hwm_send, winbindd_set_hwm_recv },
571 { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
572 winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
574 { 0, NULL, NULL, NULL }
577 static void wb_request_done(struct tevent_req *req);
579 static void process_request(struct winbindd_cli_state *state)
581 struct winbindd_dispatch_table *table = dispatch_table;
582 struct winbindd_async_dispatch_table *atable;
584 state->mem_ctx = talloc_init("winbind request");
585 if (state->mem_ctx == NULL)
586 return;
588 /* Remember who asked us. */
589 state->pid = state->request->pid;
591 state->cmd_name = "unknown request";
592 state->recv_fn = NULL;
594 /* Process command */
596 for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
597 if (state->request->cmd == atable->cmd) {
598 break;
602 if ((atable->send_req == NULL) && state->privileged) {
603 for (atable = async_priv_table; atable->send_req;
604 atable += 1) {
605 if (state->request->cmd == atable->cmd) {
606 break;
611 if (atable->send_req != NULL) {
612 struct tevent_req *req;
614 state->cmd_name = atable->cmd_name;
615 state->recv_fn = atable->recv_req;
617 DEBUG(10, ("process_request: Handling async request %d:%s\n",
618 (int)state->pid, state->cmd_name));
620 req = atable->send_req(state->mem_ctx, winbind_event_context(),
621 state, state->request);
622 if (req == NULL) {
623 DEBUG(0, ("process_request: atable->send failed for "
624 "%s\n", atable->cmd_name));
625 request_error(state);
626 return;
628 tevent_req_set_callback(req, wb_request_done, state);
629 return;
632 state->response = talloc_zero(state->mem_ctx,
633 struct winbindd_response);
634 if (state->response == NULL) {
635 DEBUG(10, ("talloc failed\n"));
636 remove_client(state);
637 return;
639 state->response->result = WINBINDD_PENDING;
640 state->response->length = sizeof(struct winbindd_response);
642 for (table = dispatch_table; table->fn; table++) {
643 if (state->request->cmd == table->cmd) {
644 DEBUG(10,("process_request: request fn %s\n",
645 table->winbindd_cmd_name ));
646 state->cmd_name = table->winbindd_cmd_name;
647 table->fn(state);
648 break;
652 if (!table->fn) {
653 DEBUG(10,("process_request: unknown request fn number %d\n",
654 (int)state->request->cmd ));
655 request_error(state);
659 static void wb_request_done(struct tevent_req *req)
661 struct winbindd_cli_state *state = tevent_req_callback_data(
662 req, struct winbindd_cli_state);
663 NTSTATUS status;
665 state->response = talloc_zero(state->mem_ctx,
666 struct winbindd_response);
667 if (state->response == NULL) {
668 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
669 (int)state->pid, state->cmd_name));
670 remove_client(state);
671 return;
673 state->response->result = WINBINDD_PENDING;
674 state->response->length = sizeof(struct winbindd_response);
676 status = state->recv_fn(req, state->response);
677 TALLOC_FREE(req);
679 DEBUG(10,("wb_request_done[%d:%s]: %s\n",
680 (int)state->pid, state->cmd_name, nt_errstr(status)));
682 if (!NT_STATUS_IS_OK(status)) {
683 request_error(state);
684 return;
686 request_ok(state);
690 * This is the main event loop of winbind requests. It goes through a
691 * state-machine of 3 read/write requests, 4 if you have extra data to send.
693 * An idle winbind client has a read request of 4 bytes outstanding,
694 * finalizing function is request_len_recv, checking the length. request_recv
695 * then processes the packet. The processing function then at some point has
696 * to call request_finished which schedules sending the response.
699 static void request_finished(struct winbindd_cli_state *state);
701 static void winbind_client_request_read(struct tevent_req *req);
702 static void winbind_client_response_written(struct tevent_req *req);
704 static void request_finished(struct winbindd_cli_state *state)
706 struct tevent_req *req;
708 TALLOC_FREE(state->request);
710 req = wb_resp_write_send(state, winbind_event_context(),
711 state->out_queue, state->sock,
712 state->response);
713 if (req == NULL) {
714 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
715 (int)state->pid, state->cmd_name));
716 remove_client(state);
717 return;
719 tevent_req_set_callback(req, winbind_client_response_written, state);
722 static void winbind_client_response_written(struct tevent_req *req)
724 struct winbindd_cli_state *state = tevent_req_callback_data(
725 req, struct winbindd_cli_state);
726 ssize_t ret;
727 int err;
729 ret = wb_resp_write_recv(req, &err);
730 TALLOC_FREE(req);
731 if (ret == -1) {
732 close(state->sock);
733 state->sock = -1;
734 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
735 (int)state->pid, state->cmd_name, strerror(err)));
736 remove_client(state);
737 return;
740 DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
741 "to client\n", (int)state->pid, state->cmd_name));
743 TALLOC_FREE(state->mem_ctx);
744 state->response = NULL;
745 state->cmd_name = "no request";
746 state->recv_fn = NULL;
748 req = wb_req_read_send(state, winbind_event_context(), state->sock,
749 WINBINDD_MAX_EXTRA_DATA);
750 if (req == NULL) {
751 remove_client(state);
752 return;
754 tevent_req_set_callback(req, winbind_client_request_read, state);
757 void request_error(struct winbindd_cli_state *state)
759 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
760 state->response->result = WINBINDD_ERROR;
761 request_finished(state);
764 void request_ok(struct winbindd_cli_state *state)
766 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
767 state->response->result = WINBINDD_OK;
768 request_finished(state);
771 /* Process a new connection by adding it to the client connection list */
773 static void new_connection(int listen_sock, bool privileged)
775 struct sockaddr_un sunaddr;
776 struct winbindd_cli_state *state;
777 struct tevent_req *req;
778 socklen_t len;
779 int sock;
781 /* Accept connection */
783 len = sizeof(sunaddr);
785 do {
786 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
787 &len);
788 } while (sock == -1 && errno == EINTR);
790 if (sock == -1)
791 return;
793 DEBUG(6,("accepted socket %d\n", sock));
795 /* Create new connection structure */
797 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
798 close(sock);
799 return;
802 state->sock = sock;
804 state->out_queue = tevent_queue_create(state, "winbind client reply");
805 if (state->out_queue == NULL) {
806 close(sock);
807 TALLOC_FREE(state);
808 return;
811 state->last_access = time(NULL);
813 state->privileged = privileged;
815 req = wb_req_read_send(state, winbind_event_context(), state->sock,
816 WINBINDD_MAX_EXTRA_DATA);
817 if (req == NULL) {
818 TALLOC_FREE(state);
819 close(sock);
820 return;
822 tevent_req_set_callback(req, winbind_client_request_read, state);
824 /* Add to connection list */
826 winbindd_add_client(state);
829 static void winbind_client_request_read(struct tevent_req *req)
831 struct winbindd_cli_state *state = tevent_req_callback_data(
832 req, struct winbindd_cli_state);
833 ssize_t ret;
834 int err;
836 ret = wb_req_read_recv(req, state, &state->request, &err);
837 TALLOC_FREE(req);
838 if (ret == -1) {
839 if (err == EPIPE) {
840 DEBUG(6, ("closing socket %d, client exited\n",
841 state->sock));
842 } else {
843 DEBUG(2, ("Could not read client request from fd %d: "
844 "%s\n", state->sock, strerror(err)));
846 close(state->sock);
847 state->sock = -1;
848 remove_client(state);
849 return;
851 process_request(state);
854 /* Remove a client connection from client connection list */
856 static void remove_client(struct winbindd_cli_state *state)
858 char c = 0;
859 int nwritten;
861 /* It's a dead client - hold a funeral */
863 if (state == NULL) {
864 return;
867 if (state->sock != -1) {
868 /* tell client, we are closing ... */
869 nwritten = write(state->sock, &c, sizeof(c));
870 if (nwritten == -1) {
871 DEBUG(2, ("final write to client failed: %s\n",
872 strerror(errno)));
875 /* Close socket */
877 close(state->sock);
878 state->sock = -1;
881 TALLOC_FREE(state->mem_ctx);
883 /* Remove from list and free */
885 winbindd_remove_client(state);
886 TALLOC_FREE(state);
889 /* Shutdown client connection which has been idle for the longest time */
891 static bool remove_idle_client(void)
893 struct winbindd_cli_state *state, *remove_state = NULL;
894 time_t last_access = 0;
895 int nidle = 0;
897 for (state = winbindd_client_list(); state; state = state->next) {
898 if (state->response == NULL &&
899 !state->pwent_state && !state->grent_state) {
900 nidle++;
901 if (!last_access || state->last_access < last_access) {
902 last_access = state->last_access;
903 remove_state = state;
908 if (remove_state) {
909 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
910 nidle, remove_state->sock, (unsigned int)remove_state->pid));
911 remove_client(remove_state);
912 return True;
915 return False;
918 struct winbindd_listen_state {
919 bool privileged;
920 int fd;
923 static void winbindd_listen_fde_handler(struct tevent_context *ev,
924 struct tevent_fd *fde,
925 uint16_t flags,
926 void *private_data)
928 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
929 struct winbindd_listen_state);
931 while (winbindd_num_clients() >
932 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
933 DEBUG(5,("winbindd: Exceeding %d client "
934 "connections, removing idle "
935 "connection.\n",
936 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
937 if (!remove_idle_client()) {
938 DEBUG(0,("winbindd: Exceeding %d "
939 "client connections, no idle "
940 "connection found\n",
941 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
942 break;
945 new_connection(s->fd, s->privileged);
948 static bool winbindd_setup_listeners(void)
950 struct winbindd_listen_state *pub_state = NULL;
951 struct winbindd_listen_state *priv_state = NULL;
952 struct tevent_fd *fde;
954 pub_state = talloc(winbind_event_context(),
955 struct winbindd_listen_state);
956 if (!pub_state) {
957 goto failed;
960 pub_state->privileged = false;
961 pub_state->fd = open_winbindd_socket();
962 if (pub_state->fd == -1) {
963 goto failed;
966 fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
967 TEVENT_FD_READ, winbindd_listen_fde_handler,
968 pub_state);
969 if (fde == NULL) {
970 close(pub_state->fd);
971 goto failed;
973 tevent_fd_set_auto_close(fde);
975 priv_state = talloc(winbind_event_context(),
976 struct winbindd_listen_state);
977 if (!priv_state) {
978 goto failed;
981 priv_state->privileged = true;
982 priv_state->fd = open_winbindd_priv_socket();
983 if (priv_state->fd == -1) {
984 goto failed;
987 fde = tevent_add_fd(winbind_event_context(), priv_state,
988 priv_state->fd, TEVENT_FD_READ,
989 winbindd_listen_fde_handler, priv_state);
990 if (fde == NULL) {
991 close(priv_state->fd);
992 goto failed;
994 tevent_fd_set_auto_close(fde);
996 return true;
997 failed:
998 TALLOC_FREE(pub_state);
999 TALLOC_FREE(priv_state);
1000 return false;
1003 bool winbindd_use_idmap_cache(void)
1005 return !opt_nocache;
1008 bool winbindd_use_cache(void)
1010 return !opt_nocache;
1013 /* Main function */
1015 int main(int argc, char **argv, char **envp)
1017 static bool is_daemon = False;
1018 static bool Fork = True;
1019 static bool log_stdout = False;
1020 static bool no_process_group = False;
1021 enum {
1022 OPT_DAEMON = 1000,
1023 OPT_FORK,
1024 OPT_NO_PROCESS_GROUP,
1025 OPT_LOG_STDOUT
1027 struct poptOption long_options[] = {
1028 POPT_AUTOHELP
1029 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1030 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1031 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1032 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1033 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1034 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1035 POPT_COMMON_SAMBA
1036 POPT_TABLEEND
1038 poptContext pc;
1039 int opt;
1040 TALLOC_CTX *frame = talloc_stackframe();
1041 struct tevent_timer *te;
1043 /* glibc (?) likes to print "User defined signal 1" and exit if a
1044 SIGUSR[12] is received before a handler is installed */
1046 CatchSignal(SIGUSR1, SIG_IGN);
1047 CatchSignal(SIGUSR2, SIG_IGN);
1049 fault_setup((void (*)(void *))fault_quit );
1050 dump_core_setup("winbindd");
1052 load_case_tables();
1054 /* Initialise for running in non-root mode */
1056 sec_init();
1058 set_remote_machine_name("winbindd", False);
1060 /* Set environment variable so we don't recursively call ourselves.
1061 This may also be useful interactively. */
1063 if ( !winbind_off() ) {
1064 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1065 exit(1);
1068 /* Initialise samba/rpc client stuff */
1070 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1072 while ((opt = poptGetNextOpt(pc)) != -1) {
1073 switch (opt) {
1074 /* Don't become a daemon */
1075 case OPT_DAEMON:
1076 is_daemon = True;
1077 break;
1078 case 'i':
1079 interactive = True;
1080 log_stdout = True;
1081 Fork = False;
1082 break;
1083 case OPT_FORK:
1084 Fork = false;
1085 break;
1086 case OPT_NO_PROCESS_GROUP:
1087 no_process_group = true;
1088 break;
1089 case OPT_LOG_STDOUT:
1090 log_stdout = true;
1091 break;
1092 case 'n':
1093 opt_nocache = true;
1094 break;
1095 default:
1096 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1097 poptBadOption(pc, 0), poptStrerror(opt));
1098 poptPrintUsage(pc, stderr, 0);
1099 exit(1);
1103 if (is_daemon && interactive) {
1104 d_fprintf(stderr,"\nERROR: "
1105 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1106 poptPrintUsage(pc, stderr, 0);
1107 exit(1);
1110 if (log_stdout && Fork) {
1111 d_fprintf(stderr, "\nERROR: "
1112 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1113 poptPrintUsage(pc, stderr, 0);
1114 exit(1);
1117 poptFreeContext(pc);
1119 if (!override_logfile) {
1120 char *lfile = NULL;
1121 if (asprintf(&lfile,"%s/log.winbindd",
1122 get_dyn_LOGFILEBASE()) > 0) {
1123 lp_set_logfile(lfile);
1124 SAFE_FREE(lfile);
1127 setup_logging("winbindd", log_stdout);
1128 reopen_logs();
1130 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1131 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1133 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1134 DEBUG(0, ("error opening config file\n"));
1135 exit(1);
1138 /* Initialise messaging system */
1140 if (winbind_messaging_context() == NULL) {
1141 exit(1);
1144 if (!reload_services_file(NULL)) {
1145 DEBUG(0, ("error opening config file\n"));
1146 exit(1);
1149 if (!directory_exist(lp_lockdir())) {
1150 mkdir(lp_lockdir(), 0755);
1153 /* Setup names. */
1155 if (!init_names())
1156 exit(1);
1158 load_interfaces();
1160 if (!secrets_init()) {
1162 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1163 return False;
1166 /* Enable netbios namecache */
1168 namecache_enable();
1170 /* Unblock all signals we are interested in as they may have been
1171 blocked by the parent process. */
1173 BlockSignals(False, SIGINT);
1174 BlockSignals(False, SIGQUIT);
1175 BlockSignals(False, SIGTERM);
1176 BlockSignals(False, SIGUSR1);
1177 BlockSignals(False, SIGUSR2);
1178 BlockSignals(False, SIGHUP);
1179 BlockSignals(False, SIGCHLD);
1181 if (!interactive)
1182 become_daemon(Fork, no_process_group, log_stdout);
1184 pidfile_create("winbindd");
1186 #if HAVE_SETPGID
1188 * If we're interactive we want to set our own process group for
1189 * signal management.
1191 if (interactive && !no_process_group)
1192 setpgid( (pid_t)0, (pid_t)0);
1193 #endif
1195 TimeInit();
1197 /* Don't use winbindd_reinit_after_fork here as
1198 * we're just starting up and haven't created any
1199 * winbindd-specific resources we must free yet. JRA.
1202 if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1203 winbind_event_context(),
1204 false))) {
1205 DEBUG(0,("reinit_after_fork() failed\n"));
1206 exit(1);
1209 /* Setup signal handlers */
1211 if (!winbindd_setup_sig_term_handler(true))
1212 exit(1);
1213 if (!winbindd_setup_sig_hup_handler(NULL))
1214 exit(1);
1215 if (!winbindd_setup_sig_chld_handler())
1216 exit(1);
1217 if (!winbindd_setup_sig_usr2_handler())
1218 exit(1);
1220 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1223 * Ensure all cache and idmap caches are consistent
1224 * and initialized before we startup.
1226 if (!winbindd_cache_validate_and_initialize()) {
1227 exit(1);
1230 /* get broadcast messages */
1232 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1233 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1234 exit(1);
1237 /* React on 'smbcontrol winbindd reload-config' in the same way
1238 as to SIGHUP signal */
1239 messaging_register(winbind_messaging_context(), NULL,
1240 MSG_SMB_CONF_UPDATED, msg_reload_services);
1241 messaging_register(winbind_messaging_context(), NULL,
1242 MSG_SHUTDOWN, msg_shutdown);
1244 /* Handle online/offline messages. */
1245 messaging_register(winbind_messaging_context(), NULL,
1246 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1247 messaging_register(winbind_messaging_context(), NULL,
1248 MSG_WINBIND_ONLINE, winbind_msg_online);
1249 messaging_register(winbind_messaging_context(), NULL,
1250 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1252 messaging_register(winbind_messaging_context(), NULL,
1253 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1255 messaging_register(winbind_messaging_context(), NULL,
1256 MSG_WINBIND_VALIDATE_CACHE,
1257 winbind_msg_validate_cache);
1259 messaging_register(winbind_messaging_context(), NULL,
1260 MSG_WINBIND_DUMP_DOMAIN_LIST,
1261 winbind_msg_dump_domain_list);
1263 /* Register handler for MSG_DEBUG. */
1264 messaging_register(winbind_messaging_context(), NULL,
1265 MSG_DEBUG,
1266 winbind_msg_debug);
1268 netsamlogon_cache_init(); /* Non-critical */
1270 /* clear the cached list of trusted domains */
1272 wcache_tdc_clear();
1274 if (!init_domain_list()) {
1275 DEBUG(0,("unable to initialize domain list\n"));
1276 exit(1);
1279 init_idmap_child();
1280 init_locator_child();
1282 smb_nscd_flush_user_cache();
1283 smb_nscd_flush_group_cache();
1285 /* setup listen sockets */
1287 if (!winbindd_setup_listeners()) {
1288 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1289 exit(1);
1292 te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1293 rescan_trusted_domains, NULL);
1294 if (te == NULL) {
1295 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1296 exit(1);
1299 TALLOC_FREE(frame);
1300 /* Loop waiting for requests */
1301 while (1) {
1302 frame = talloc_stackframe();
1304 if (tevent_loop_once(winbind_event_context()) == -1) {
1305 DEBUG(1, ("tevent_loop_once() failed: %s\n",
1306 strerror(errno)));
1307 return 1;
1310 TALLOC_FREE(frame);
1313 return 0;