Fix a memleak caused by a crappy get_sorted_dc_list() API
[Samba.git] / source / winbindd / winbindd.c
blobc017916f09a5a7c4ff32cd6b421c17f3f7546e70
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"
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
31 bool opt_nocache = False;
32 static bool interactive = False;
34 extern bool override_logfile;
36 struct event_context *winbind_event_context(void)
38 static struct event_context *ctx;
40 if (!ctx && !(ctx = event_context_init(NULL))) {
41 smb_panic("Could not init winbind event context");
43 return ctx;
46 struct messaging_context *winbind_messaging_context(void)
48 static struct messaging_context *ctx;
50 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
51 winbind_event_context()))) {
52 smb_panic("Could not init winbind messaging context");
54 return ctx;
57 /* Reload configuration */
59 static bool reload_services_file(void)
61 bool ret;
63 if (lp_loaded()) {
64 const char *fname = lp_configfile();
66 if (file_exist(fname,NULL) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
67 set_dyn_CONFIGFILE(fname);
71 reopen_logs();
72 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
74 reopen_logs();
75 load_interfaces();
77 return(ret);
81 /**************************************************************************** **
82 Handle a fault..
83 **************************************************************************** */
85 static void fault_quit(void)
87 dump_core();
90 static void winbindd_status(void)
92 struct winbindd_cli_state *tmp;
94 DEBUG(0, ("winbindd status:\n"));
96 /* Print client state information */
98 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
100 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
101 DEBUG(2, ("\tclient list:\n"));
102 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
103 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
104 (unsigned long)tmp->pid, tmp->sock));
109 /* Print winbindd status to log file */
111 static void print_winbindd_status(void)
113 winbindd_status();
116 /* Flush client cache */
118 static void flush_caches(void)
120 /* We need to invalidate cached user list entries on a SIGHUP
121 otherwise cached access denied errors due to restrict anonymous
122 hang around until the sequence number changes. */
124 if (!wcache_invalidate_cache()) {
125 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
126 if (!winbindd_cache_validate_and_initialize()) {
127 exit(1);
132 /* Handle the signal by unlinking socket and exiting */
134 static void terminate(bool is_parent)
136 if (is_parent) {
137 /* When parent goes away we should
138 * remove the socket file. Not so
139 * when children terminate.
141 char *path = NULL;
143 if (asprintf(&path, "%s/%s",
144 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
145 unlink(path);
146 SAFE_FREE(path);
150 idmap_close();
152 trustdom_cache_shutdown();
154 #if 0
155 if (interactive) {
156 TALLOC_CTX *mem_ctx = talloc_init("end_description");
157 char *description = talloc_describe_all(mem_ctx);
159 DEBUG(3, ("tallocs left:\n%s\n", description));
160 talloc_destroy(mem_ctx);
162 #endif
164 exit(0);
167 static bool do_sigterm;
169 static void termination_handler(int signum)
171 do_sigterm = True;
172 sys_select_signal(signum);
175 static bool do_sigusr2;
177 static void sigusr2_handler(int signum)
179 do_sigusr2 = True;
180 sys_select_signal(SIGUSR2);
183 static bool do_sighup;
185 static void sighup_handler(int signum)
187 do_sighup = True;
188 sys_select_signal(SIGHUP);
191 static bool do_sigchld;
193 static void sigchld_handler(int signum)
195 do_sigchld = True;
196 sys_select_signal(SIGCHLD);
199 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
200 static void msg_reload_services(struct messaging_context *msg,
201 void *private_data,
202 uint32_t msg_type,
203 struct server_id server_id,
204 DATA_BLOB *data)
206 /* Flush various caches */
207 flush_caches();
208 reload_services_file();
211 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
212 static void msg_shutdown(struct messaging_context *msg,
213 void *private_data,
214 uint32_t msg_type,
215 struct server_id server_id,
216 DATA_BLOB *data)
218 do_sigterm = True;
222 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
223 void *private_data,
224 uint32_t msg_type,
225 struct server_id server_id,
226 DATA_BLOB *data)
228 uint8 ret;
229 pid_t child_pid;
230 struct sigaction act;
231 struct sigaction oldact;
233 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
234 "message.\n"));
237 * call the validation code from a child:
238 * so we don't block the main winbindd and the validation
239 * code can safely use fork/waitpid...
241 CatchChild();
242 child_pid = sys_fork();
244 if (child_pid == -1) {
245 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
246 strerror(errno)));
247 return;
250 if (child_pid != 0) {
251 /* parent */
252 DEBUG(5, ("winbind_msg_validate_cache: child created with "
253 "pid %d.\n", child_pid));
254 return;
257 /* child */
259 /* install default SIGCHLD handler: validation code uses fork/waitpid */
260 ZERO_STRUCT(act);
261 act.sa_handler = SIG_DFL;
262 #ifdef SA_RESTART
263 /* We *want* SIGALRM to interrupt a system call. */
264 act.sa_flags = SA_RESTART;
265 #endif
266 sigemptyset(&act.sa_mask);
267 sigaddset(&act.sa_mask,SIGCHLD);
268 sigaction(SIGCHLD,&act,&oldact);
270 ret = (uint8)winbindd_validate_cache_nobackup();
271 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
272 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
273 (size_t)1);
274 _exit(0);
277 static struct winbindd_dispatch_table {
278 enum winbindd_cmd cmd;
279 void (*fn)(struct winbindd_cli_state *state);
280 const char *winbindd_cmd_name;
281 } dispatch_table[] = {
283 /* User functions */
285 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
286 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
288 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
289 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
290 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
292 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
293 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
294 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
295 "GETUSERDOMGROUPS" },
297 /* Group functions */
299 { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
300 { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
301 { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
302 { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
303 { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
304 { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
306 /* PAM auth functions */
308 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
309 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
310 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
311 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
312 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
314 /* Enumeration functions */
316 { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
317 { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
318 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
319 "LIST_TRUSTDOM" },
320 { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
322 /* SID related functions */
324 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
325 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
326 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
328 /* Lookup related functions */
330 { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
331 { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
332 { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
333 { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
334 #if 0 /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
335 { WINBINDD_SIDS_TO_XIDS, winbindd_sids_to_unixids, "SIDS_TO_XIDS" },
336 #endif /* end DISABLED */
337 { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
338 { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
339 { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
340 { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
342 /* Miscellaneous */
344 { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
345 { WINBINDD_PING, winbindd_ping, "PING" },
346 { WINBINDD_INFO, winbindd_info, "INFO" },
347 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
348 "INTERFACE_VERSION" },
349 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
350 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
351 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
352 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
353 "WINBINDD_PRIV_PIPE_DIR" },
354 { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
355 { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
357 /* Credential cache access */
358 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
360 /* WINS functions */
362 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
363 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
365 /* End of list */
367 { WINBINDD_NUM_CMDS, NULL, "NONE" }
370 static void process_request(struct winbindd_cli_state *state)
372 struct winbindd_dispatch_table *table = dispatch_table;
374 /* Free response data - we may be interrupted and receive another
375 command before being able to send this data off. */
377 SAFE_FREE(state->response.extra_data.data);
379 ZERO_STRUCT(state->response);
381 state->response.result = WINBINDD_PENDING;
382 state->response.length = sizeof(struct winbindd_response);
384 state->mem_ctx = talloc_init("winbind request");
385 if (state->mem_ctx == NULL)
386 return;
388 /* Remember who asked us. */
389 state->pid = state->request.pid;
391 /* Process command */
393 for (table = dispatch_table; table->fn; table++) {
394 if (state->request.cmd == table->cmd) {
395 DEBUG(10,("process_request: request fn %s\n",
396 table->winbindd_cmd_name ));
397 table->fn(state);
398 break;
402 if (!table->fn) {
403 DEBUG(10,("process_request: unknown request fn number %d\n",
404 (int)state->request.cmd ));
405 request_error(state);
410 * A list of file descriptors being monitored by select in the main processing
411 * loop. fd_event->handler is called whenever the socket is readable/writable.
414 static struct fd_event *fd_events = NULL;
416 void add_fd_event(struct fd_event *ev)
418 struct fd_event *match;
420 /* only add unique fd_event structs */
422 for (match=fd_events; match; match=match->next ) {
423 #ifdef DEVELOPER
424 SMB_ASSERT( match != ev );
425 #else
426 if ( match == ev )
427 return;
428 #endif
431 DLIST_ADD(fd_events, ev);
434 void remove_fd_event(struct fd_event *ev)
436 DLIST_REMOVE(fd_events, ev);
440 * Handler for fd_events to complete a read/write request, set up by
441 * setup_async_read/setup_async_write.
444 static void rw_callback(struct fd_event *event, int flags)
446 size_t todo;
447 ssize_t done = 0;
449 todo = event->length - event->done;
451 if (event->flags & EVENT_FD_WRITE) {
452 SMB_ASSERT(flags == EVENT_FD_WRITE);
453 done = sys_write(event->fd,
454 &((char *)event->data)[event->done],
455 todo);
457 if (done <= 0) {
458 event->flags = 0;
459 event->finished(event->private_data, False);
460 return;
464 if (event->flags & EVENT_FD_READ) {
465 SMB_ASSERT(flags == EVENT_FD_READ);
466 done = sys_read(event->fd, &((char *)event->data)[event->done],
467 todo);
469 if (done <= 0) {
470 event->flags = 0;
471 event->finished(event->private_data, False);
472 return;
476 event->done += done;
478 if (event->done == event->length) {
479 event->flags = 0;
480 event->finished(event->private_data, True);
485 * Request an async read/write on a fd_event structure. (*finished) is called
486 * when the request is completed or an error had occurred.
489 void setup_async_read(struct fd_event *event, void *data, size_t length,
490 void (*finished)(void *private_data, bool success),
491 void *private_data)
493 SMB_ASSERT(event->flags == 0);
494 event->data = data;
495 event->length = length;
496 event->done = 0;
497 event->handler = rw_callback;
498 event->finished = finished;
499 event->private_data = private_data;
500 event->flags = EVENT_FD_READ;
503 void setup_async_write(struct fd_event *event, void *data, size_t length,
504 void (*finished)(void *private_data, bool success),
505 void *private_data)
507 SMB_ASSERT(event->flags == 0);
508 event->data = data;
509 event->length = length;
510 event->done = 0;
511 event->handler = rw_callback;
512 event->finished = finished;
513 event->private_data = private_data;
514 event->flags = EVENT_FD_WRITE;
518 * This is the main event loop of winbind requests. It goes through a
519 * state-machine of 3 read/write requests, 4 if you have extra data to send.
521 * An idle winbind client has a read request of 4 bytes outstanding,
522 * finalizing function is request_len_recv, checking the length. request_recv
523 * then processes the packet. The processing function then at some point has
524 * to call request_finished which schedules sending the response.
527 static void request_len_recv(void *private_data, bool success);
528 static void request_recv(void *private_data, bool success);
529 static void request_main_recv(void *private_data, bool success);
530 static void request_finished(struct winbindd_cli_state *state);
531 void request_finished_cont(void *private_data, bool success);
532 static void response_main_sent(void *private_data, bool success);
533 static void response_extra_sent(void *private_data, bool success);
535 static void response_extra_sent(void *private_data, bool success)
537 struct winbindd_cli_state *state =
538 talloc_get_type_abort(private_data, struct winbindd_cli_state);
540 if (state->mem_ctx != NULL) {
541 talloc_destroy(state->mem_ctx);
542 state->mem_ctx = NULL;
545 if (!success) {
546 state->finished = True;
547 return;
550 SAFE_FREE(state->request.extra_data.data);
551 SAFE_FREE(state->response.extra_data.data);
553 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
554 request_len_recv, state);
557 static void response_main_sent(void *private_data, bool success)
559 struct winbindd_cli_state *state =
560 talloc_get_type_abort(private_data, struct winbindd_cli_state);
562 if (!success) {
563 state->finished = True;
564 return;
567 if (state->response.length == sizeof(state->response)) {
568 if (state->mem_ctx != NULL) {
569 talloc_destroy(state->mem_ctx);
570 state->mem_ctx = NULL;
573 setup_async_read(&state->fd_event, &state->request,
574 sizeof(uint32), request_len_recv, state);
575 return;
578 setup_async_write(&state->fd_event, state->response.extra_data.data,
579 state->response.length - sizeof(state->response),
580 response_extra_sent, state);
583 static void request_finished(struct winbindd_cli_state *state)
585 setup_async_write(&state->fd_event, &state->response,
586 sizeof(state->response), response_main_sent, state);
589 void request_error(struct winbindd_cli_state *state)
591 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
592 state->response.result = WINBINDD_ERROR;
593 request_finished(state);
596 void request_ok(struct winbindd_cli_state *state)
598 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
599 state->response.result = WINBINDD_OK;
600 request_finished(state);
603 void request_finished_cont(void *private_data, bool success)
605 struct winbindd_cli_state *state =
606 talloc_get_type_abort(private_data, struct winbindd_cli_state);
608 if (success)
609 request_ok(state);
610 else
611 request_error(state);
614 static void request_len_recv(void *private_data, bool success)
616 struct winbindd_cli_state *state =
617 talloc_get_type_abort(private_data, struct winbindd_cli_state);
619 if (!success) {
620 state->finished = True;
621 return;
624 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
625 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
626 *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
627 state->finished = True;
628 return;
631 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
632 sizeof(state->request) - sizeof(uint32),
633 request_main_recv, state);
636 static void request_main_recv(void *private_data, bool success)
638 struct winbindd_cli_state *state =
639 talloc_get_type_abort(private_data, struct winbindd_cli_state);
641 if (!success) {
642 state->finished = True;
643 return;
646 if (state->request.extra_len == 0) {
647 state->request.extra_data.data = NULL;
648 request_recv(state, True);
649 return;
652 if ((!state->privileged) &&
653 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
654 DEBUG(3, ("Got request with %d bytes extra data on "
655 "unprivileged socket\n", (int)state->request.extra_len));
656 state->request.extra_data.data = NULL;
657 state->finished = True;
658 return;
661 state->request.extra_data.data =
662 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
664 if (state->request.extra_data.data == NULL) {
665 DEBUG(0, ("malloc failed\n"));
666 state->finished = True;
667 return;
670 /* Ensure null termination */
671 state->request.extra_data.data[state->request.extra_len] = '\0';
673 setup_async_read(&state->fd_event, state->request.extra_data.data,
674 state->request.extra_len, request_recv, state);
677 static void request_recv(void *private_data, bool success)
679 struct winbindd_cli_state *state =
680 talloc_get_type_abort(private_data, struct winbindd_cli_state);
682 if (!success) {
683 state->finished = True;
684 return;
687 process_request(state);
690 /* Process a new connection by adding it to the client connection list */
692 static void new_connection(int listen_sock, bool privileged)
694 struct sockaddr_un sunaddr;
695 struct winbindd_cli_state *state;
696 socklen_t len;
697 int sock;
699 /* Accept connection */
701 len = sizeof(sunaddr);
703 do {
704 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
705 } while (sock == -1 && errno == EINTR);
707 if (sock == -1)
708 return;
710 DEBUG(6,("accepted socket %d\n", sock));
712 /* Create new connection structure */
714 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
715 close(sock);
716 return;
719 state->sock = sock;
721 state->last_access = time(NULL);
723 state->privileged = privileged;
725 state->fd_event.fd = state->sock;
726 state->fd_event.flags = 0;
727 add_fd_event(&state->fd_event);
729 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
730 request_len_recv, state);
732 /* Add to connection list */
734 winbindd_add_client(state);
737 /* Remove a client connection from client connection list */
739 static void remove_client(struct winbindd_cli_state *state)
741 /* It's a dead client - hold a funeral */
743 if (state == NULL) {
744 return;
747 /* Close socket */
749 close(state->sock);
751 /* Free any getent state */
753 free_getent_state(state->getpwent_state);
754 free_getent_state(state->getgrent_state);
756 /* We may have some extra data that was not freed if the client was
757 killed unexpectedly */
759 SAFE_FREE(state->response.extra_data.data);
761 if (state->mem_ctx != NULL) {
762 talloc_destroy(state->mem_ctx);
763 state->mem_ctx = NULL;
766 remove_fd_event(&state->fd_event);
768 /* Remove from list and free */
770 winbindd_remove_client(state);
771 TALLOC_FREE(state);
774 /* Shutdown client connection which has been idle for the longest time */
776 static bool remove_idle_client(void)
778 struct winbindd_cli_state *state, *remove_state = NULL;
779 time_t last_access = 0;
780 int nidle = 0;
782 for (state = winbindd_client_list(); state; state = state->next) {
783 if (state->response.result != WINBINDD_PENDING &&
784 !state->getpwent_state && !state->getgrent_state) {
785 nidle++;
786 if (!last_access || state->last_access < last_access) {
787 last_access = state->last_access;
788 remove_state = state;
793 if (remove_state) {
794 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
795 nidle, remove_state->sock, (unsigned int)remove_state->pid));
796 remove_client(remove_state);
797 return True;
800 return False;
803 /* check if HUP has been received and reload files */
804 void winbind_check_sighup(void)
806 if (do_sighup) {
808 DEBUG(3, ("got SIGHUP\n"));
810 flush_caches();
811 reload_services_file();
813 do_sighup = False;
817 /* check if TERM has been received */
818 void winbind_check_sigterm(bool is_parent)
820 if (do_sigterm)
821 terminate(is_parent);
824 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
825 non-forking, non-threaded model which allows us to handle many
826 simultaneous connections while remaining impervious to many denial of
827 service attacks. */
829 static void process_loop(void)
831 struct winbindd_cli_state *state;
832 struct fd_event *ev;
833 fd_set r_fds, w_fds;
834 int maxfd, listen_sock, listen_priv_sock, selret;
835 struct timeval timeout, ev_timeout;
837 /* Open Sockets here to get stuff going ASAP */
838 listen_sock = open_winbindd_socket();
839 listen_priv_sock = open_winbindd_priv_socket();
841 if (listen_sock == -1 || listen_priv_sock == -1) {
842 perror("open_winbind_socket");
843 exit(1);
846 /* We'll be doing this a lot */
848 /* Handle messages */
850 message_dispatch(winbind_messaging_context());
852 run_events(winbind_event_context(), 0, NULL, NULL);
854 /* refresh the trusted domain cache */
856 rescan_trusted_domains();
858 /* Initialise fd lists for select() */
860 maxfd = MAX(listen_sock, listen_priv_sock);
862 FD_ZERO(&r_fds);
863 FD_ZERO(&w_fds);
864 FD_SET(listen_sock, &r_fds);
865 FD_SET(listen_priv_sock, &r_fds);
867 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
868 timeout.tv_usec = 0;
870 /* Check for any event timeouts. */
871 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
872 timeout = timeval_min(&timeout, &ev_timeout);
875 /* Set up client readers and writers */
877 state = winbindd_client_list();
879 while (state) {
881 struct winbindd_cli_state *next = state->next;
883 /* Dispose of client connection if it is marked as
884 finished */
886 if (state->finished)
887 remove_client(state);
889 state = next;
892 for (ev = fd_events; ev; ev = ev->next) {
893 if (ev->flags & EVENT_FD_READ) {
894 FD_SET(ev->fd, &r_fds);
895 maxfd = MAX(ev->fd, maxfd);
897 if (ev->flags & EVENT_FD_WRITE) {
898 FD_SET(ev->fd, &w_fds);
899 maxfd = MAX(ev->fd, maxfd);
903 /* Call select */
905 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
907 if (selret == 0) {
908 goto no_fds_ready;
911 if (selret == -1) {
912 if (errno == EINTR) {
913 goto no_fds_ready;
916 /* Select error, something is badly wrong */
918 perror("select");
919 exit(1);
922 /* selret > 0 */
924 ev = fd_events;
925 while (ev != NULL) {
926 struct fd_event *next = ev->next;
927 int flags = 0;
928 if (FD_ISSET(ev->fd, &r_fds))
929 flags |= EVENT_FD_READ;
930 if (FD_ISSET(ev->fd, &w_fds))
931 flags |= EVENT_FD_WRITE;
932 if (flags)
933 ev->handler(ev, flags);
934 ev = next;
937 if (FD_ISSET(listen_sock, &r_fds)) {
938 while (winbindd_num_clients() >
939 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
940 DEBUG(5,("winbindd: Exceeding %d client "
941 "connections, removing idle "
942 "connection.\n",
943 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
944 if (!remove_idle_client()) {
945 DEBUG(0,("winbindd: Exceeding %d "
946 "client connections, no idle "
947 "connection found\n",
948 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
949 break;
952 /* new, non-privileged connection */
953 new_connection(listen_sock, False);
956 if (FD_ISSET(listen_priv_sock, &r_fds)) {
957 while (winbindd_num_clients() >
958 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
959 DEBUG(5,("winbindd: Exceeding %d client "
960 "connections, removing idle "
961 "connection.\n",
962 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
963 if (!remove_idle_client()) {
964 DEBUG(0,("winbindd: Exceeding %d "
965 "client connections, no idle "
966 "connection found\n",
967 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
968 break;
971 /* new, privileged connection */
972 new_connection(listen_priv_sock, True);
975 no_fds_ready:
977 #if 0
978 winbindd_check_cache_size(time(NULL));
979 #endif
981 /* Check signal handling things */
983 winbind_check_sigterm(true);
984 winbind_check_sighup();
986 if (do_sigusr2) {
987 print_winbindd_status();
988 do_sigusr2 = False;
991 if (do_sigchld) {
992 pid_t pid;
994 do_sigchld = False;
996 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
997 winbind_child_died(pid);
1002 /* Main function */
1004 int main(int argc, char **argv, char **envp)
1006 static bool is_daemon = False;
1007 static bool Fork = True;
1008 static bool log_stdout = False;
1009 static bool no_process_group = False;
1010 enum {
1011 OPT_DAEMON = 1000,
1012 OPT_FORK,
1013 OPT_NO_PROCESS_GROUP,
1014 OPT_LOG_STDOUT
1016 struct poptOption long_options[] = {
1017 POPT_AUTOHELP
1018 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1019 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1020 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1021 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1022 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1023 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1024 POPT_COMMON_SAMBA
1025 POPT_TABLEEND
1027 poptContext pc;
1028 int opt;
1029 TALLOC_CTX *frame = talloc_stackframe();
1031 /* glibc (?) likes to print "User defined signal 1" and exit if a
1032 SIGUSR[12] is received before a handler is installed */
1034 CatchSignal(SIGUSR1, SIG_IGN);
1035 CatchSignal(SIGUSR2, SIG_IGN);
1037 fault_setup((void (*)(void *))fault_quit );
1038 dump_core_setup("winbindd");
1040 load_case_tables();
1042 db_tdb2_setup_messaging(NULL, false);
1044 /* Initialise for running in non-root mode */
1046 sec_init();
1048 set_remote_machine_name("winbindd", False);
1050 /* Set environment variable so we don't recursively call ourselves.
1051 This may also be useful interactively. */
1053 if ( !winbind_off() ) {
1054 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1055 exit(1);
1058 /* Initialise samba/rpc client stuff */
1060 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1062 while ((opt = poptGetNextOpt(pc)) != -1) {
1063 switch (opt) {
1064 /* Don't become a daemon */
1065 case OPT_DAEMON:
1066 is_daemon = True;
1067 break;
1068 case 'i':
1069 interactive = True;
1070 log_stdout = True;
1071 Fork = False;
1072 break;
1073 case OPT_FORK:
1074 Fork = false;
1075 break;
1076 case OPT_NO_PROCESS_GROUP:
1077 no_process_group = true;
1078 break;
1079 case OPT_LOG_STDOUT:
1080 log_stdout = true;
1081 break;
1082 case 'n':
1083 opt_nocache = true;
1084 break;
1085 default:
1086 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1087 poptBadOption(pc, 0), poptStrerror(opt));
1088 poptPrintUsage(pc, stderr, 0);
1089 exit(1);
1093 if (is_daemon && interactive) {
1094 d_fprintf(stderr,"\nERROR: "
1095 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1096 poptPrintUsage(pc, stderr, 0);
1097 exit(1);
1100 if (log_stdout && Fork) {
1101 d_fprintf(stderr, "\nERROR: "
1102 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1103 poptPrintUsage(pc, stderr, 0);
1104 exit(1);
1107 poptFreeContext(pc);
1109 if (!override_logfile) {
1110 char *logfile = NULL;
1111 if (asprintf(&logfile,"%s/log.winbindd",
1112 get_dyn_LOGFILEBASE()) > 0) {
1113 lp_set_logfile(logfile);
1114 SAFE_FREE(logfile);
1117 setup_logging("winbindd", log_stdout);
1118 reopen_logs();
1120 DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1121 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1123 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1124 DEBUG(0, ("error opening config file\n"));
1125 exit(1);
1128 /* Initialise messaging system */
1130 if (winbind_messaging_context() == NULL) {
1131 DEBUG(0, ("unable to initialize messaging system\n"));
1132 exit(1);
1135 db_tdb2_setup_messaging(winbind_messaging_context(), true);
1137 if (!reload_services_file()) {
1138 DEBUG(0, ("error opening config file\n"));
1139 exit(1);
1142 if (!directory_exist(lp_lockdir(), NULL)) {
1143 mkdir(lp_lockdir(), 0755);
1146 /* Setup names. */
1148 if (!init_names())
1149 exit(1);
1151 load_interfaces();
1153 if (!secrets_init()) {
1155 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1156 return False;
1159 /* Enable netbios namecache */
1161 namecache_enable();
1163 /* Winbind daemon initialisation */
1165 if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1166 DEBUG(1, ("Could not init idmap cache!\n"));
1169 /* Unblock all signals we are interested in as they may have been
1170 blocked by the parent process. */
1172 BlockSignals(False, SIGINT);
1173 BlockSignals(False, SIGQUIT);
1174 BlockSignals(False, SIGTERM);
1175 BlockSignals(False, SIGUSR1);
1176 BlockSignals(False, SIGUSR2);
1177 BlockSignals(False, SIGHUP);
1178 BlockSignals(False, SIGCHLD);
1180 /* Setup signal handlers */
1182 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1183 CatchSignal(SIGQUIT, termination_handler);
1184 CatchSignal(SIGTERM, termination_handler);
1185 CatchSignal(SIGCHLD, sigchld_handler);
1187 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1189 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1190 CatchSignal(SIGHUP, sighup_handler);
1192 if (!interactive)
1193 become_daemon(Fork, no_process_group);
1195 pidfile_create("winbindd");
1197 #if HAVE_SETPGID
1199 * If we're interactive we want to set our own process group for
1200 * signal management.
1202 if (interactive && !no_process_group)
1203 setpgid( (pid_t)0, (pid_t)0);
1204 #endif
1206 TimeInit();
1208 if (!reinit_after_fork(winbind_messaging_context(), false)) {
1209 DEBUG(0,("reinit_after_fork() failed\n"));
1210 exit(1);
1214 * Ensure all cache and idmap caches are consistent
1215 * and initialized before we startup.
1217 if (!winbindd_cache_validate_and_initialize()) {
1218 exit(1);
1221 /* get broadcast messages */
1222 claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1224 /* React on 'smbcontrol winbindd reload-config' in the same way
1225 as to SIGHUP signal */
1226 messaging_register(winbind_messaging_context(), NULL,
1227 MSG_SMB_CONF_UPDATED, msg_reload_services);
1228 messaging_register(winbind_messaging_context(), NULL,
1229 MSG_SHUTDOWN, msg_shutdown);
1231 /* Handle online/offline messages. */
1232 messaging_register(winbind_messaging_context(), NULL,
1233 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1234 messaging_register(winbind_messaging_context(), NULL,
1235 MSG_WINBIND_ONLINE, winbind_msg_online);
1236 messaging_register(winbind_messaging_context(), NULL,
1237 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1239 messaging_register(winbind_messaging_context(), NULL,
1240 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1242 messaging_register(winbind_messaging_context(), NULL,
1243 MSG_WINBIND_VALIDATE_CACHE,
1244 winbind_msg_validate_cache);
1246 messaging_register(winbind_messaging_context(), NULL,
1247 MSG_WINBIND_DUMP_DOMAIN_LIST,
1248 winbind_msg_dump_domain_list);
1250 netsamlogon_cache_init(); /* Non-critical */
1252 /* clear the cached list of trusted domains */
1254 wcache_tdc_clear();
1256 if (!init_domain_list()) {
1257 DEBUG(0,("unable to initialize domain list\n"));
1258 exit(1);
1261 init_idmap_child();
1262 init_locator_child();
1264 smb_nscd_flush_user_cache();
1265 smb_nscd_flush_group_cache();
1267 /* Loop waiting for requests */
1269 TALLOC_FREE(frame);
1270 while (1) {
1271 frame = talloc_stackframe();
1272 process_loop();
1273 TALLOC_FREE(frame);
1276 return 0;