s3: Fix a long-standing problem with recycled PIDs
[Samba/gebeck_regimport.git] / source3 / winbindd / winbindd.c
blobafb1ba53facd4ea9a9eb8ac27780383738ef2702
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;
399 struct sigaction act;
400 struct sigaction oldact;
402 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
403 "message.\n"));
406 * call the validation code from a child:
407 * so we don't block the main winbindd and the validation
408 * code can safely use fork/waitpid...
410 CatchChild();
411 child_pid = sys_fork();
413 if (child_pid == -1) {
414 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
415 strerror(errno)));
416 return;
419 if (child_pid != 0) {
420 /* parent */
421 DEBUG(5, ("winbind_msg_validate_cache: child created with "
422 "pid %d.\n", (int)child_pid));
423 return;
426 /* child */
428 /* install default SIGCHLD handler: validation code uses fork/waitpid */
429 ZERO_STRUCT(act);
430 act.sa_handler = SIG_DFL;
431 #ifdef SA_RESTART
432 /* We *want* SIGALRM to interrupt a system call. */
433 act.sa_flags = SA_RESTART;
434 #endif
435 sigemptyset(&act.sa_mask);
436 sigaddset(&act.sa_mask,SIGCHLD);
437 sigaction(SIGCHLD,&act,&oldact);
439 ret = (uint8)winbindd_validate_cache_nobackup();
440 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
441 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
442 (size_t)1);
443 _exit(0);
446 static struct winbindd_dispatch_table {
447 enum winbindd_cmd cmd;
448 void (*fn)(struct winbindd_cli_state *state);
449 const char *winbindd_cmd_name;
450 } dispatch_table[] = {
452 /* PAM auth functions */
454 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
455 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
456 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
457 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
458 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
460 /* Enumeration functions */
462 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
463 "LIST_TRUSTDOM" },
465 /* Miscellaneous */
467 { WINBINDD_INFO, winbindd_info, "INFO" },
468 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
469 "INTERFACE_VERSION" },
470 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
471 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
472 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
473 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
474 "WINBINDD_PRIV_PIPE_DIR" },
476 /* Credential cache access */
477 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
478 { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
480 /* WINS functions */
482 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
483 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
485 /* End of list */
487 { WINBINDD_NUM_CMDS, NULL, "NONE" }
490 struct winbindd_async_dispatch_table {
491 enum winbindd_cmd cmd;
492 const char *cmd_name;
493 struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
494 struct tevent_context *ev,
495 struct winbindd_cli_state *cli,
496 struct winbindd_request *request);
497 NTSTATUS (*recv_req)(struct tevent_req *req,
498 struct winbindd_response *presp);
501 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
502 { WINBINDD_PING, "PING",
503 wb_ping_send, wb_ping_recv },
504 { WINBINDD_LOOKUPSID, "LOOKUPSID",
505 winbindd_lookupsid_send, winbindd_lookupsid_recv },
506 { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
507 winbindd_lookupname_send, winbindd_lookupname_recv },
508 { WINBINDD_SID_TO_UID, "SID_TO_UID",
509 winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
510 { WINBINDD_SID_TO_GID, "SID_TO_GID",
511 winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
512 { WINBINDD_UID_TO_SID, "UID_TO_SID",
513 winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
514 { WINBINDD_GID_TO_SID, "GID_TO_SID",
515 winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
516 { WINBINDD_GETPWSID, "GETPWSID",
517 winbindd_getpwsid_send, winbindd_getpwsid_recv },
518 { WINBINDD_GETPWNAM, "GETPWNAM",
519 winbindd_getpwnam_send, winbindd_getpwnam_recv },
520 { WINBINDD_GETPWUID, "GETPWUID",
521 winbindd_getpwuid_send, winbindd_getpwuid_recv },
522 { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
523 winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
524 { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
525 winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
526 { WINBINDD_GETGROUPS, "GETGROUPS",
527 winbindd_getgroups_send, winbindd_getgroups_recv },
528 { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
529 winbindd_show_sequence_send, winbindd_show_sequence_recv },
530 { WINBINDD_GETGRGID, "GETGRGID",
531 winbindd_getgrgid_send, winbindd_getgrgid_recv },
532 { WINBINDD_GETGRNAM, "GETGRNAM",
533 winbindd_getgrnam_send, winbindd_getgrnam_recv },
534 { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
535 winbindd_getusersids_send, winbindd_getusersids_recv },
536 { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
537 winbindd_lookuprids_send, winbindd_lookuprids_recv },
538 { WINBINDD_SETPWENT, "SETPWENT",
539 winbindd_setpwent_send, winbindd_setpwent_recv },
540 { WINBINDD_GETPWENT, "GETPWENT",
541 winbindd_getpwent_send, winbindd_getpwent_recv },
542 { WINBINDD_ENDPWENT, "ENDPWENT",
543 winbindd_endpwent_send, winbindd_endpwent_recv },
544 { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
545 winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
546 { WINBINDD_GETDCNAME, "GETDCNAME",
547 winbindd_getdcname_send, winbindd_getdcname_recv },
548 { WINBINDD_SETGRENT, "SETGRENT",
549 winbindd_setgrent_send, winbindd_setgrent_recv },
550 { WINBINDD_GETGRENT, "GETGRENT",
551 winbindd_getgrent_send, winbindd_getgrent_recv },
552 { WINBINDD_ENDGRENT, "ENDGRENT",
553 winbindd_endgrent_send, winbindd_endgrent_recv },
554 { WINBINDD_LIST_USERS, "LIST_USERS",
555 winbindd_list_users_send, winbindd_list_users_recv },
556 { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
557 winbindd_list_groups_send, winbindd_list_groups_recv },
558 { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
559 winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
560 { WINBINDD_PING_DC, "PING_DC",
561 winbindd_ping_dc_send, winbindd_ping_dc_recv },
563 { 0, NULL, NULL, NULL }
566 static struct winbindd_async_dispatch_table async_priv_table[] = {
567 { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
568 winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
569 { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
570 winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
571 { WINBINDD_SET_MAPPING, "SET_MAPPING",
572 winbindd_set_mapping_send, winbindd_set_mapping_recv },
573 { WINBINDD_REMOVE_MAPPING, "SET_MAPPING",
574 winbindd_remove_mapping_send, winbindd_remove_mapping_recv },
575 { WINBINDD_SET_HWM, "SET_HWM",
576 winbindd_set_hwm_send, winbindd_set_hwm_recv },
577 { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
578 winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
580 { 0, NULL, NULL, NULL }
583 static void wb_request_done(struct tevent_req *req);
585 static void process_request(struct winbindd_cli_state *state)
587 struct winbindd_dispatch_table *table = dispatch_table;
588 struct winbindd_async_dispatch_table *atable;
590 state->mem_ctx = talloc_init("winbind request");
591 if (state->mem_ctx == NULL)
592 return;
594 /* Remember who asked us. */
595 state->pid = state->request->pid;
597 state->cmd_name = "unknown request";
598 state->recv_fn = NULL;
600 /* Process command */
602 for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
603 if (state->request->cmd == atable->cmd) {
604 break;
608 if ((atable->send_req == NULL) && state->privileged) {
609 for (atable = async_priv_table; atable->send_req;
610 atable += 1) {
611 if (state->request->cmd == atable->cmd) {
612 break;
617 if (atable->send_req != NULL) {
618 struct tevent_req *req;
620 state->cmd_name = atable->cmd_name;
621 state->recv_fn = atable->recv_req;
623 DEBUG(10, ("process_request: Handling async request %d:%s\n",
624 (int)state->pid, state->cmd_name));
626 req = atable->send_req(state->mem_ctx, winbind_event_context(),
627 state, state->request);
628 if (req == NULL) {
629 DEBUG(0, ("process_request: atable->send failed for "
630 "%s\n", atable->cmd_name));
631 request_error(state);
632 return;
634 tevent_req_set_callback(req, wb_request_done, state);
635 return;
638 state->response = talloc_zero(state->mem_ctx,
639 struct winbindd_response);
640 if (state->response == NULL) {
641 DEBUG(10, ("talloc failed\n"));
642 remove_client(state);
643 return;
645 state->response->result = WINBINDD_PENDING;
646 state->response->length = sizeof(struct winbindd_response);
648 for (table = dispatch_table; table->fn; table++) {
649 if (state->request->cmd == table->cmd) {
650 DEBUG(10,("process_request: request fn %s\n",
651 table->winbindd_cmd_name ));
652 state->cmd_name = table->winbindd_cmd_name;
653 table->fn(state);
654 break;
658 if (!table->fn) {
659 DEBUG(10,("process_request: unknown request fn number %d\n",
660 (int)state->request->cmd ));
661 request_error(state);
665 static void wb_request_done(struct tevent_req *req)
667 struct winbindd_cli_state *state = tevent_req_callback_data(
668 req, struct winbindd_cli_state);
669 NTSTATUS status;
671 state->response = talloc_zero(state, struct winbindd_response);
672 if (state->response == NULL) {
673 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
674 (int)state->pid, state->cmd_name));
675 remove_client(state);
676 return;
678 state->response->result = WINBINDD_PENDING;
679 state->response->length = sizeof(struct winbindd_response);
681 status = state->recv_fn(req, state->response);
682 TALLOC_FREE(req);
684 DEBUG(10,("wb_request_done[%d:%s]: %s\n",
685 (int)state->pid, state->cmd_name, nt_errstr(status)));
687 if (!NT_STATUS_IS_OK(status)) {
688 request_error(state);
689 return;
691 request_ok(state);
695 * This is the main event loop of winbind requests. It goes through a
696 * state-machine of 3 read/write requests, 4 if you have extra data to send.
698 * An idle winbind client has a read request of 4 bytes outstanding,
699 * finalizing function is request_len_recv, checking the length. request_recv
700 * then processes the packet. The processing function then at some point has
701 * to call request_finished which schedules sending the response.
704 static void request_finished(struct winbindd_cli_state *state);
706 static void winbind_client_request_read(struct tevent_req *req);
707 static void winbind_client_response_written(struct tevent_req *req);
709 static void request_finished(struct winbindd_cli_state *state)
711 struct tevent_req *req;
713 TALLOC_FREE(state->request);
715 req = wb_resp_write_send(state, winbind_event_context(),
716 state->out_queue, state->sock,
717 state->response);
718 if (req == NULL) {
719 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
720 (int)state->pid, state->cmd_name));
721 remove_client(state);
722 return;
724 tevent_req_set_callback(req, winbind_client_response_written, state);
727 static void winbind_client_response_written(struct tevent_req *req)
729 struct winbindd_cli_state *state = tevent_req_callback_data(
730 req, struct winbindd_cli_state);
731 ssize_t ret;
732 int err;
734 ret = wb_resp_write_recv(req, &err);
735 TALLOC_FREE(req);
736 if (ret == -1) {
737 close(state->sock);
738 state->sock = -1;
739 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
740 (int)state->pid, state->cmd_name, strerror(err)));
741 remove_client(state);
742 return;
745 DEBUG(10,("winbind_client_response_written[%d:%s]: deliverd response to client\n",
746 (int)state->pid, state->cmd_name));
748 TALLOC_FREE(state->mem_ctx);
749 state->response = NULL;
750 state->cmd_name = "no request";
751 state->recv_fn = NULL;
753 req = wb_req_read_send(state, winbind_event_context(), state->sock,
754 WINBINDD_MAX_EXTRA_DATA);
755 if (req == NULL) {
756 remove_client(state);
757 return;
759 tevent_req_set_callback(req, winbind_client_request_read, state);
762 void request_error(struct winbindd_cli_state *state)
764 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
765 state->response->result = WINBINDD_ERROR;
766 request_finished(state);
769 void request_ok(struct winbindd_cli_state *state)
771 SMB_ASSERT(state->response->result == WINBINDD_PENDING);
772 state->response->result = WINBINDD_OK;
773 request_finished(state);
776 /* Process a new connection by adding it to the client connection list */
778 static void new_connection(int listen_sock, bool privileged)
780 struct sockaddr_un sunaddr;
781 struct winbindd_cli_state *state;
782 struct tevent_req *req;
783 socklen_t len;
784 int sock;
786 /* Accept connection */
788 len = sizeof(sunaddr);
790 do {
791 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
792 &len);
793 } while (sock == -1 && errno == EINTR);
795 if (sock == -1)
796 return;
798 DEBUG(6,("accepted socket %d\n", sock));
800 /* Create new connection structure */
802 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
803 close(sock);
804 return;
807 state->sock = sock;
809 state->out_queue = tevent_queue_create(state, "winbind client reply");
810 if (state->out_queue == NULL) {
811 close(sock);
812 TALLOC_FREE(state);
813 return;
816 state->last_access = time(NULL);
818 state->privileged = privileged;
820 req = wb_req_read_send(state, winbind_event_context(), state->sock,
821 WINBINDD_MAX_EXTRA_DATA);
822 if (req == NULL) {
823 TALLOC_FREE(state);
824 close(sock);
825 return;
827 tevent_req_set_callback(req, winbind_client_request_read, state);
829 /* Add to connection list */
831 winbindd_add_client(state);
834 static void winbind_client_request_read(struct tevent_req *req)
836 struct winbindd_cli_state *state = tevent_req_callback_data(
837 req, struct winbindd_cli_state);
838 ssize_t ret;
839 int err;
841 ret = wb_req_read_recv(req, state, &state->request, &err);
842 TALLOC_FREE(req);
843 if (ret == -1) {
844 if (err == EPIPE) {
845 DEBUG(6, ("closing socket %d, client exited\n",
846 state->sock));
847 } else {
848 DEBUG(2, ("Could not read client request from fd %d: "
849 "%s\n", state->sock, strerror(err)));
851 close(state->sock);
852 state->sock = -1;
853 remove_client(state);
854 return;
856 process_request(state);
859 /* Remove a client connection from client connection list */
861 static void remove_client(struct winbindd_cli_state *state)
863 char c = 0;
864 int nwritten;
866 /* It's a dead client - hold a funeral */
868 if (state == NULL) {
869 return;
872 if (state->sock != -1) {
873 /* tell client, we are closing ... */
874 nwritten = write(state->sock, &c, sizeof(c));
875 if (nwritten == -1) {
876 DEBUG(2, ("final write to client failed: %s\n",
877 strerror(errno)));
880 /* Close socket */
882 close(state->sock);
883 state->sock = -1;
886 TALLOC_FREE(state->mem_ctx);
888 /* Remove from list and free */
890 winbindd_remove_client(state);
891 TALLOC_FREE(state);
894 /* Shutdown client connection which has been idle for the longest time */
896 static bool remove_idle_client(void)
898 struct winbindd_cli_state *state, *remove_state = NULL;
899 time_t last_access = 0;
900 int nidle = 0;
902 for (state = winbindd_client_list(); state; state = state->next) {
903 if (state->response == NULL &&
904 !state->pwent_state && !state->grent_state) {
905 nidle++;
906 if (!last_access || state->last_access < last_access) {
907 last_access = state->last_access;
908 remove_state = state;
913 if (remove_state) {
914 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
915 nidle, remove_state->sock, (unsigned int)remove_state->pid));
916 remove_client(remove_state);
917 return True;
920 return False;
923 struct winbindd_listen_state {
924 bool privileged;
925 int fd;
928 static void winbindd_listen_fde_handler(struct tevent_context *ev,
929 struct tevent_fd *fde,
930 uint16_t flags,
931 void *private_data)
933 struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
934 struct winbindd_listen_state);
936 while (winbindd_num_clients() >
937 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
938 DEBUG(5,("winbindd: Exceeding %d client "
939 "connections, removing idle "
940 "connection.\n",
941 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
942 if (!remove_idle_client()) {
943 DEBUG(0,("winbindd: Exceeding %d "
944 "client connections, no idle "
945 "connection found\n",
946 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
947 break;
950 new_connection(s->fd, s->privileged);
953 static bool winbindd_setup_listeners(void)
955 struct winbindd_listen_state *pub_state = NULL;
956 struct winbindd_listen_state *priv_state = NULL;
957 struct tevent_fd *fde;
959 pub_state = talloc(winbind_event_context(),
960 struct winbindd_listen_state);
961 if (!pub_state) {
962 goto failed;
965 pub_state->privileged = false;
966 pub_state->fd = open_winbindd_socket();
967 if (pub_state->fd == -1) {
968 goto failed;
971 fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
972 TEVENT_FD_READ, winbindd_listen_fde_handler,
973 pub_state);
974 if (fde == NULL) {
975 close(pub_state->fd);
976 goto failed;
978 tevent_fd_set_auto_close(fde);
980 priv_state = talloc(winbind_event_context(),
981 struct winbindd_listen_state);
982 if (!priv_state) {
983 goto failed;
986 priv_state->privileged = true;
987 priv_state->fd = open_winbindd_priv_socket();
988 if (priv_state->fd == -1) {
989 goto failed;
992 fde = tevent_add_fd(winbind_event_context(), priv_state,
993 priv_state->fd, TEVENT_FD_READ,
994 winbindd_listen_fde_handler, priv_state);
995 if (fde == NULL) {
996 close(priv_state->fd);
997 goto failed;
999 tevent_fd_set_auto_close(fde);
1001 return true;
1002 failed:
1003 TALLOC_FREE(pub_state);
1004 TALLOC_FREE(priv_state);
1005 return false;
1008 bool winbindd_use_idmap_cache(void)
1010 return !opt_nocache;
1013 bool winbindd_use_cache(void)
1015 return !opt_nocache;
1018 /* Main function */
1020 int main(int argc, char **argv, char **envp)
1022 static bool is_daemon = False;
1023 static bool Fork = True;
1024 static bool log_stdout = False;
1025 static bool no_process_group = False;
1026 enum {
1027 OPT_DAEMON = 1000,
1028 OPT_FORK,
1029 OPT_NO_PROCESS_GROUP,
1030 OPT_LOG_STDOUT
1032 struct poptOption long_options[] = {
1033 POPT_AUTOHELP
1034 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1035 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1036 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1037 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1038 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1039 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1040 POPT_COMMON_SAMBA
1041 POPT_TABLEEND
1043 poptContext pc;
1044 int opt;
1045 TALLOC_CTX *frame = talloc_stackframe();
1046 struct tevent_timer *te;
1048 /* glibc (?) likes to print "User defined signal 1" and exit if a
1049 SIGUSR[12] is received before a handler is installed */
1051 CatchSignal(SIGUSR1, SIG_IGN);
1052 CatchSignal(SIGUSR2, SIG_IGN);
1054 fault_setup((void (*)(void *))fault_quit );
1055 dump_core_setup("winbindd");
1057 load_case_tables();
1059 /* Initialise for running in non-root mode */
1061 sec_init();
1063 set_remote_machine_name("winbindd", False);
1065 /* Set environment variable so we don't recursively call ourselves.
1066 This may also be useful interactively. */
1068 if ( !winbind_off() ) {
1069 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1070 exit(1);
1073 /* Initialise samba/rpc client stuff */
1075 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1077 while ((opt = poptGetNextOpt(pc)) != -1) {
1078 switch (opt) {
1079 /* Don't become a daemon */
1080 case OPT_DAEMON:
1081 is_daemon = True;
1082 break;
1083 case 'i':
1084 interactive = True;
1085 log_stdout = True;
1086 Fork = False;
1087 break;
1088 case OPT_FORK:
1089 Fork = false;
1090 break;
1091 case OPT_NO_PROCESS_GROUP:
1092 no_process_group = true;
1093 break;
1094 case OPT_LOG_STDOUT:
1095 log_stdout = true;
1096 break;
1097 case 'n':
1098 opt_nocache = true;
1099 break;
1100 default:
1101 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1102 poptBadOption(pc, 0), poptStrerror(opt));
1103 poptPrintUsage(pc, stderr, 0);
1104 exit(1);
1108 if (is_daemon && interactive) {
1109 d_fprintf(stderr,"\nERROR: "
1110 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1111 poptPrintUsage(pc, stderr, 0);
1112 exit(1);
1115 if (log_stdout && Fork) {
1116 d_fprintf(stderr, "\nERROR: "
1117 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1118 poptPrintUsage(pc, stderr, 0);
1119 exit(1);
1122 poptFreeContext(pc);
1124 if (!override_logfile) {
1125 char *lfile = NULL;
1126 if (asprintf(&lfile,"%s/log.winbindd",
1127 get_dyn_LOGFILEBASE()) > 0) {
1128 lp_set_logfile(lfile);
1129 SAFE_FREE(lfile);
1132 setup_logging("winbindd", log_stdout);
1133 reopen_logs();
1135 DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1136 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1138 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1139 DEBUG(0, ("error opening config file\n"));
1140 exit(1);
1143 /* Initialise messaging system */
1145 if (winbind_messaging_context() == NULL) {
1146 exit(1);
1149 if (!reload_services_file(NULL)) {
1150 DEBUG(0, ("error opening config file\n"));
1151 exit(1);
1154 if (!directory_exist(lp_lockdir())) {
1155 mkdir(lp_lockdir(), 0755);
1158 /* Setup names. */
1160 if (!init_names())
1161 exit(1);
1163 load_interfaces();
1165 if (!secrets_init()) {
1167 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1168 return False;
1171 /* Enable netbios namecache */
1173 namecache_enable();
1175 /* Unblock all signals we are interested in as they may have been
1176 blocked by the parent process. */
1178 BlockSignals(False, SIGINT);
1179 BlockSignals(False, SIGQUIT);
1180 BlockSignals(False, SIGTERM);
1181 BlockSignals(False, SIGUSR1);
1182 BlockSignals(False, SIGUSR2);
1183 BlockSignals(False, SIGHUP);
1184 BlockSignals(False, SIGCHLD);
1186 if (!interactive)
1187 become_daemon(Fork, no_process_group);
1189 pidfile_create("winbindd");
1191 #if HAVE_SETPGID
1193 * If we're interactive we want to set our own process group for
1194 * signal management.
1196 if (interactive && !no_process_group)
1197 setpgid( (pid_t)0, (pid_t)0);
1198 #endif
1200 TimeInit();
1202 /* Don't use winbindd_reinit_after_fork here as
1203 * we're just starting up and haven't created any
1204 * winbindd-specific resources we must free yet. JRA.
1207 if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1208 winbind_event_context(),
1209 false))) {
1210 DEBUG(0,("reinit_after_fork() failed\n"));
1211 exit(1);
1214 /* Setup signal handlers */
1216 if (!winbindd_setup_sig_term_handler(true))
1217 exit(1);
1218 if (!winbindd_setup_sig_hup_handler(NULL))
1219 exit(1);
1220 if (!winbindd_setup_sig_chld_handler())
1221 exit(1);
1222 if (!winbindd_setup_sig_usr2_handler())
1223 exit(1);
1225 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1228 * Ensure all cache and idmap caches are consistent
1229 * and initialized before we startup.
1231 if (!winbindd_cache_validate_and_initialize()) {
1232 exit(1);
1235 /* get broadcast messages */
1237 if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1238 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1239 exit(1);
1242 /* React on 'smbcontrol winbindd reload-config' in the same way
1243 as to SIGHUP signal */
1244 messaging_register(winbind_messaging_context(), NULL,
1245 MSG_SMB_CONF_UPDATED, msg_reload_services);
1246 messaging_register(winbind_messaging_context(), NULL,
1247 MSG_SHUTDOWN, msg_shutdown);
1249 /* Handle online/offline messages. */
1250 messaging_register(winbind_messaging_context(), NULL,
1251 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1252 messaging_register(winbind_messaging_context(), NULL,
1253 MSG_WINBIND_ONLINE, winbind_msg_online);
1254 messaging_register(winbind_messaging_context(), NULL,
1255 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1257 messaging_register(winbind_messaging_context(), NULL,
1258 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1260 messaging_register(winbind_messaging_context(), NULL,
1261 MSG_WINBIND_VALIDATE_CACHE,
1262 winbind_msg_validate_cache);
1264 messaging_register(winbind_messaging_context(), NULL,
1265 MSG_WINBIND_DUMP_DOMAIN_LIST,
1266 winbind_msg_dump_domain_list);
1268 /* Register handler for MSG_DEBUG. */
1269 messaging_register(winbind_messaging_context(), NULL,
1270 MSG_DEBUG,
1271 winbind_msg_debug);
1273 netsamlogon_cache_init(); /* Non-critical */
1275 /* clear the cached list of trusted domains */
1277 wcache_tdc_clear();
1279 if (!init_domain_list()) {
1280 DEBUG(0,("unable to initialize domain list\n"));
1281 exit(1);
1284 init_idmap_child();
1285 init_locator_child();
1287 smb_nscd_flush_user_cache();
1288 smb_nscd_flush_group_cache();
1290 /* setup listen sockets */
1292 if (!winbindd_setup_listeners()) {
1293 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1294 exit(1);
1297 te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1298 rescan_trusted_domains, NULL);
1299 if (te == NULL) {
1300 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1301 exit(1);
1304 TALLOC_FREE(frame);
1305 /* Loop waiting for requests */
1306 while (1) {
1307 frame = talloc_stackframe();
1309 if (tevent_loop_once(winbind_event_context()) == -1) {
1310 DEBUG(1, ("tevent_loop_once() failed: %s\n",
1311 strerror(errno)));
1312 return 1;
1315 TALLOC_FREE(frame);
1318 return 0;