WHATSNEW: Update changes since 3.3.0.
[Samba/gbeck.git] / source / winbindd / winbindd.c
blobe235c9653493a10b1c0e9da1c45f1369c56cae59
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 == NULL) {
51 ctx = messaging_init(NULL, server_id_self(),
52 winbind_event_context());
54 if (ctx == NULL) {
55 DEBUG(0, ("Could not init winbind messaging context.\n"));
57 return ctx;
60 /* Reload configuration */
62 static bool reload_services_file(const char *lfile)
64 bool ret;
66 if (lp_loaded()) {
67 const char *fname = lp_configfile();
69 if (file_exist(fname,NULL) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
70 set_dyn_CONFIGFILE(fname);
74 /* if this is a child, restore the logfile to the special
75 name - <domain>, idmap, etc. */
76 if (lfile && *lfile) {
77 lp_set_logfile(lfile);
80 reopen_logs();
81 ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
83 reopen_logs();
84 load_interfaces();
86 return(ret);
90 /**************************************************************************** **
91 Handle a fault..
92 **************************************************************************** */
94 static void fault_quit(void)
96 dump_core();
99 static void winbindd_status(void)
101 struct winbindd_cli_state *tmp;
103 DEBUG(0, ("winbindd status:\n"));
105 /* Print client state information */
107 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
109 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
110 DEBUG(2, ("\tclient list:\n"));
111 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
112 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
113 (unsigned long)tmp->pid, tmp->sock));
118 /* Print winbindd status to log file */
120 static void print_winbindd_status(void)
122 winbindd_status();
125 /* Flush client cache */
127 static void flush_caches(void)
129 /* We need to invalidate cached user list entries on a SIGHUP
130 otherwise cached access denied errors due to restrict anonymous
131 hang around until the sequence number changes. */
133 if (!wcache_invalidate_cache()) {
134 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
135 if (!winbindd_cache_validate_and_initialize()) {
136 exit(1);
141 /* Handle the signal by unlinking socket and exiting */
143 static void terminate(bool is_parent)
145 if (is_parent) {
146 /* When parent goes away we should
147 * remove the socket file. Not so
148 * when children terminate.
150 char *path = NULL;
152 if (asprintf(&path, "%s/%s",
153 get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
154 unlink(path);
155 SAFE_FREE(path);
159 idmap_close();
161 trustdom_cache_shutdown();
163 #if 0
164 if (interactive) {
165 TALLOC_CTX *mem_ctx = talloc_init("end_description");
166 char *description = talloc_describe_all(mem_ctx);
168 DEBUG(3, ("tallocs left:\n%s\n", description));
169 talloc_destroy(mem_ctx);
171 #endif
173 exit(0);
176 static SIG_ATOMIC_T do_sigterm = 0;
178 static void termination_handler(int signum)
180 do_sigterm = 1;
181 sys_select_signal(signum);
184 static SIG_ATOMIC_T do_sigusr2 = 0;
186 static void sigusr2_handler(int signum)
188 do_sigusr2 = 1;
189 sys_select_signal(SIGUSR2);
192 static SIG_ATOMIC_T do_sighup = 0;
194 static void sighup_handler(int signum)
196 do_sighup = 1;
197 sys_select_signal(SIGHUP);
200 static SIG_ATOMIC_T do_sigchld = 0;
202 static void sigchld_handler(int signum)
204 do_sigchld = 1;
205 sys_select_signal(SIGCHLD);
208 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
209 static void msg_reload_services(struct messaging_context *msg,
210 void *private_data,
211 uint32_t msg_type,
212 struct server_id server_id,
213 DATA_BLOB *data)
215 /* Flush various caches */
216 flush_caches();
217 reload_services_file((const char *) private_data);
220 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
221 static void msg_shutdown(struct messaging_context *msg,
222 void *private_data,
223 uint32_t msg_type,
224 struct server_id server_id,
225 DATA_BLOB *data)
227 do_sigterm = 1;
231 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
232 void *private_data,
233 uint32_t msg_type,
234 struct server_id server_id,
235 DATA_BLOB *data)
237 uint8 ret;
238 pid_t child_pid;
239 struct sigaction act;
240 struct sigaction oldact;
242 DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
243 "message.\n"));
246 * call the validation code from a child:
247 * so we don't block the main winbindd and the validation
248 * code can safely use fork/waitpid...
250 CatchChild();
251 child_pid = sys_fork();
253 if (child_pid == -1) {
254 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
255 strerror(errno)));
256 return;
259 if (child_pid != 0) {
260 /* parent */
261 DEBUG(5, ("winbind_msg_validate_cache: child created with "
262 "pid %d.\n", child_pid));
263 return;
266 /* child */
268 /* install default SIGCHLD handler: validation code uses fork/waitpid */
269 ZERO_STRUCT(act);
270 act.sa_handler = SIG_DFL;
271 #ifdef SA_RESTART
272 /* We *want* SIGALRM to interrupt a system call. */
273 act.sa_flags = SA_RESTART;
274 #endif
275 sigemptyset(&act.sa_mask);
276 sigaddset(&act.sa_mask,SIGCHLD);
277 sigaction(SIGCHLD,&act,&oldact);
279 ret = (uint8)winbindd_validate_cache_nobackup();
280 DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
281 messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
282 (size_t)1);
283 _exit(0);
286 static struct winbindd_dispatch_table {
287 enum winbindd_cmd cmd;
288 void (*fn)(struct winbindd_cli_state *state);
289 const char *winbindd_cmd_name;
290 } dispatch_table[] = {
292 /* User functions */
294 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
295 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
297 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
298 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
299 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
301 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
302 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
303 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
304 "GETUSERDOMGROUPS" },
306 /* Group functions */
308 { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
309 { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
310 { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
311 { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
312 { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
313 { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
315 /* PAM auth functions */
317 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
318 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
319 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
320 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
321 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
323 /* Enumeration functions */
325 { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
326 { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
327 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
328 "LIST_TRUSTDOM" },
329 { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
331 /* SID related functions */
333 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
334 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
335 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
337 /* Lookup related functions */
339 { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
340 { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
341 { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
342 { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
343 { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
344 { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
345 { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
346 { WINBINDD_REMOVE_MAPPING, winbindd_remove_mapping, "REMOVE_MAPPING" },
347 { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
349 /* Miscellaneous */
351 { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
352 { WINBINDD_PING, winbindd_ping, "PING" },
353 { WINBINDD_INFO, winbindd_info, "INFO" },
354 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
355 "INTERFACE_VERSION" },
356 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
357 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
358 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
359 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
360 "WINBINDD_PRIV_PIPE_DIR" },
361 { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
362 { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
364 /* Credential cache access */
365 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
367 /* WINS functions */
369 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
370 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
372 /* End of list */
374 { WINBINDD_NUM_CMDS, NULL, "NONE" }
377 static void process_request(struct winbindd_cli_state *state)
379 struct winbindd_dispatch_table *table = dispatch_table;
381 /* Free response data - we may be interrupted and receive another
382 command before being able to send this data off. */
384 SAFE_FREE(state->response.extra_data.data);
386 ZERO_STRUCT(state->response);
388 state->response.result = WINBINDD_PENDING;
389 state->response.length = sizeof(struct winbindd_response);
391 state->mem_ctx = talloc_init("winbind request");
392 if (state->mem_ctx == NULL)
393 return;
395 /* Remember who asked us. */
396 state->pid = state->request.pid;
398 /* Process command */
400 for (table = dispatch_table; table->fn; table++) {
401 if (state->request.cmd == table->cmd) {
402 DEBUG(10,("process_request: request fn %s\n",
403 table->winbindd_cmd_name ));
404 table->fn(state);
405 break;
409 if (!table->fn) {
410 DEBUG(10,("process_request: unknown request fn number %d\n",
411 (int)state->request.cmd ));
412 request_error(state);
417 * A list of file descriptors being monitored by select in the main processing
418 * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
421 static struct winbindd_fd_event *fd_events = NULL;
423 void add_fd_event(struct winbindd_fd_event *ev)
425 struct winbindd_fd_event *match;
427 /* only add unique winbindd_fd_event structs */
429 for (match=fd_events; match; match=match->next ) {
430 #ifdef DEVELOPER
431 SMB_ASSERT( match != ev );
432 #else
433 if ( match == ev )
434 return;
435 #endif
438 DLIST_ADD(fd_events, ev);
441 void remove_fd_event(struct winbindd_fd_event *ev)
443 DLIST_REMOVE(fd_events, ev);
447 * Handler for winbindd_fd_events to complete a read/write request, set up by
448 * setup_async_read/setup_async_write.
451 static void rw_callback(struct winbindd_fd_event *event, int flags)
453 size_t todo;
454 ssize_t done = 0;
456 todo = event->length - event->done;
458 if (event->flags & EVENT_FD_WRITE) {
459 SMB_ASSERT(flags == EVENT_FD_WRITE);
460 done = sys_write(event->fd,
461 &((char *)event->data)[event->done],
462 todo);
464 if (done <= 0) {
465 event->flags = 0;
466 event->finished(event->private_data, False);
467 return;
471 if (event->flags & EVENT_FD_READ) {
472 SMB_ASSERT(flags == EVENT_FD_READ);
473 done = sys_read(event->fd, &((char *)event->data)[event->done],
474 todo);
476 if (done <= 0) {
477 event->flags = 0;
478 event->finished(event->private_data, False);
479 return;
483 event->done += done;
485 if (event->done == event->length) {
486 event->flags = 0;
487 event->finished(event->private_data, True);
492 * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
493 * when the request is completed or an error had occurred.
496 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
497 void (*finished)(void *private_data, bool success),
498 void *private_data)
500 SMB_ASSERT(event->flags == 0);
501 event->data = data;
502 event->length = length;
503 event->done = 0;
504 event->handler = rw_callback;
505 event->finished = finished;
506 event->private_data = private_data;
507 event->flags = EVENT_FD_READ;
510 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
511 void (*finished)(void *private_data, bool success),
512 void *private_data)
514 SMB_ASSERT(event->flags == 0);
515 event->data = data;
516 event->length = length;
517 event->done = 0;
518 event->handler = rw_callback;
519 event->finished = finished;
520 event->private_data = private_data;
521 event->flags = EVENT_FD_WRITE;
525 * This is the main event loop of winbind requests. It goes through a
526 * state-machine of 3 read/write requests, 4 if you have extra data to send.
528 * An idle winbind client has a read request of 4 bytes outstanding,
529 * finalizing function is request_len_recv, checking the length. request_recv
530 * then processes the packet. The processing function then at some point has
531 * to call request_finished which schedules sending the response.
534 static void request_len_recv(void *private_data, bool success);
535 static void request_recv(void *private_data, bool success);
536 static void request_main_recv(void *private_data, bool success);
537 static void request_finished(struct winbindd_cli_state *state);
538 static void response_main_sent(void *private_data, bool success);
539 static void response_extra_sent(void *private_data, bool success);
541 static void response_extra_sent(void *private_data, bool success)
543 struct winbindd_cli_state *state =
544 talloc_get_type_abort(private_data, struct winbindd_cli_state);
546 TALLOC_FREE(state->mem_ctx);
548 if (!success) {
549 state->finished = True;
550 return;
553 SAFE_FREE(state->response.extra_data.data);
555 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
556 request_len_recv, state);
559 static void response_main_sent(void *private_data, bool success)
561 struct winbindd_cli_state *state =
562 talloc_get_type_abort(private_data, struct winbindd_cli_state);
564 if (!success) {
565 state->finished = True;
566 return;
569 if (state->response.length == sizeof(state->response)) {
570 TALLOC_FREE(state->mem_ctx);
572 setup_async_read(&state->fd_event, &state->request,
573 sizeof(uint32), request_len_recv, state);
574 return;
577 setup_async_write(&state->fd_event, state->response.extra_data.data,
578 state->response.length - sizeof(state->response),
579 response_extra_sent, state);
582 static void request_finished(struct winbindd_cli_state *state)
584 /* Make sure request.extra_data is freed when finish processing a request */
585 SAFE_FREE(state->request.extra_data.data);
586 setup_async_write(&state->fd_event, &state->response,
587 sizeof(state->response), response_main_sent, state);
590 void request_error(struct winbindd_cli_state *state)
592 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
593 state->response.result = WINBINDD_ERROR;
594 request_finished(state);
597 void request_ok(struct winbindd_cli_state *state)
599 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
600 state->response.result = WINBINDD_OK;
601 request_finished(state);
604 static void request_len_recv(void *private_data, bool success)
606 struct winbindd_cli_state *state =
607 talloc_get_type_abort(private_data, struct winbindd_cli_state);
609 if (!success) {
610 state->finished = True;
611 return;
614 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
615 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
616 *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
617 state->finished = True;
618 return;
621 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
622 sizeof(state->request) - sizeof(uint32),
623 request_main_recv, state);
626 static void request_main_recv(void *private_data, bool success)
628 struct winbindd_cli_state *state =
629 talloc_get_type_abort(private_data, struct winbindd_cli_state);
631 if (!success) {
632 state->finished = True;
633 return;
636 if (state->request.extra_len == 0) {
637 state->request.extra_data.data = NULL;
638 request_recv(state, True);
639 return;
642 if ((!state->privileged) &&
643 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
644 DEBUG(3, ("Got request with %d bytes extra data on "
645 "unprivileged socket\n", (int)state->request.extra_len));
646 state->request.extra_data.data = NULL;
647 state->finished = True;
648 return;
651 state->request.extra_data.data =
652 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
654 if (state->request.extra_data.data == NULL) {
655 DEBUG(0, ("malloc failed\n"));
656 state->finished = True;
657 return;
660 /* Ensure null termination */
661 state->request.extra_data.data[state->request.extra_len] = '\0';
663 setup_async_read(&state->fd_event, state->request.extra_data.data,
664 state->request.extra_len, request_recv, state);
667 static void request_recv(void *private_data, bool success)
669 struct winbindd_cli_state *state =
670 talloc_get_type_abort(private_data, struct winbindd_cli_state);
672 if (!success) {
673 state->finished = True;
674 return;
677 process_request(state);
680 /* Process a new connection by adding it to the client connection list */
682 static void new_connection(int listen_sock, bool privileged)
684 struct sockaddr_un sunaddr;
685 struct winbindd_cli_state *state;
686 socklen_t len;
687 int sock;
689 /* Accept connection */
691 len = sizeof(sunaddr);
693 do {
694 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
695 } while (sock == -1 && errno == EINTR);
697 if (sock == -1)
698 return;
700 DEBUG(6,("accepted socket %d\n", sock));
702 /* Create new connection structure */
704 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
705 close(sock);
706 return;
709 state->sock = sock;
711 state->last_access = time(NULL);
713 state->privileged = privileged;
715 state->fd_event.fd = state->sock;
716 state->fd_event.flags = 0;
717 add_fd_event(&state->fd_event);
719 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
720 request_len_recv, state);
722 /* Add to connection list */
724 winbindd_add_client(state);
727 /* Remove a client connection from client connection list */
729 static void remove_client(struct winbindd_cli_state *state)
731 char c = 0;
732 int nwritten;
734 /* It's a dead client - hold a funeral */
736 if (state == NULL) {
737 return;
740 /* tell client, we are closing ... */
741 nwritten = write(state->sock, &c, sizeof(c));
742 if (nwritten == -1) {
743 DEBUG(2, ("final write to client failed: %s\n",
744 strerror(errno)));
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 TALLOC_FREE(state->mem_ctx);
763 remove_fd_event(&state->fd_event);
765 /* Remove from list and free */
767 winbindd_remove_client(state);
768 TALLOC_FREE(state);
771 /* Shutdown client connection which has been idle for the longest time */
773 static bool remove_idle_client(void)
775 struct winbindd_cli_state *state, *remove_state = NULL;
776 time_t last_access = 0;
777 int nidle = 0;
779 for (state = winbindd_client_list(); state; state = state->next) {
780 if (state->response.result != WINBINDD_PENDING &&
781 !state->getpwent_state && !state->getgrent_state) {
782 nidle++;
783 if (!last_access || state->last_access < last_access) {
784 last_access = state->last_access;
785 remove_state = state;
790 if (remove_state) {
791 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
792 nidle, remove_state->sock, (unsigned int)remove_state->pid));
793 remove_client(remove_state);
794 return True;
797 return False;
800 /* check if HUP has been received and reload files */
801 void winbind_check_sighup(const char *lfile)
803 if (do_sighup) {
805 DEBUG(3, ("got SIGHUP\n"));
807 flush_caches();
808 reload_services_file(lfile);
810 do_sighup = 0;
814 /* check if TERM has been received */
815 void winbind_check_sigterm(bool is_parent)
817 if (do_sigterm)
818 terminate(is_parent);
821 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
822 non-forking, non-threaded model which allows us to handle many
823 simultaneous connections while remaining impervious to many denial of
824 service attacks. */
826 static void process_loop(void)
828 struct winbindd_cli_state *state;
829 struct winbindd_fd_event *ev;
830 fd_set r_fds, w_fds;
831 int maxfd, listen_sock, listen_priv_sock, selret;
832 struct timeval timeout, ev_timeout;
834 /* Open Sockets here to get stuff going ASAP */
835 listen_sock = open_winbindd_socket();
836 listen_priv_sock = open_winbindd_priv_socket();
838 if (listen_sock == -1 || listen_priv_sock == -1) {
839 perror("open_winbind_socket");
840 exit(1);
843 /* We'll be doing this a lot */
845 /* Handle messages */
847 message_dispatch(winbind_messaging_context());
849 run_events(winbind_event_context(), 0, NULL, NULL);
851 /* refresh the trusted domain cache */
853 rescan_trusted_domains();
855 /* Initialise fd lists for select() */
857 maxfd = MAX(listen_sock, listen_priv_sock);
859 FD_ZERO(&r_fds);
860 FD_ZERO(&w_fds);
861 FD_SET(listen_sock, &r_fds);
862 FD_SET(listen_priv_sock, &r_fds);
864 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
865 timeout.tv_usec = 0;
867 /* Check for any event timeouts. */
868 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
869 timeout = timeval_min(&timeout, &ev_timeout);
872 /* Set up client readers and writers */
874 state = winbindd_client_list();
876 while (state) {
878 struct winbindd_cli_state *next = state->next;
880 /* Dispose of client connection if it is marked as
881 finished */
883 if (state->finished)
884 remove_client(state);
886 state = next;
889 for (ev = fd_events; ev; ev = ev->next) {
890 if (ev->flags & EVENT_FD_READ) {
891 FD_SET(ev->fd, &r_fds);
892 maxfd = MAX(ev->fd, maxfd);
894 if (ev->flags & EVENT_FD_WRITE) {
895 FD_SET(ev->fd, &w_fds);
896 maxfd = MAX(ev->fd, maxfd);
900 /* Call select */
902 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
904 if (selret == 0) {
905 goto no_fds_ready;
908 if (selret == -1) {
909 if (errno == EINTR) {
910 goto no_fds_ready;
913 /* Select error, something is badly wrong */
915 perror("select");
916 exit(1);
919 /* selret > 0 */
921 ev = fd_events;
922 while (ev != NULL) {
923 struct winbindd_fd_event *next = ev->next;
924 int flags = 0;
925 if (FD_ISSET(ev->fd, &r_fds))
926 flags |= EVENT_FD_READ;
927 if (FD_ISSET(ev->fd, &w_fds))
928 flags |= EVENT_FD_WRITE;
929 if (flags)
930 ev->handler(ev, flags);
931 ev = next;
934 if (FD_ISSET(listen_sock, &r_fds)) {
935 while (winbindd_num_clients() >
936 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
937 DEBUG(5,("winbindd: Exceeding %d client "
938 "connections, removing idle "
939 "connection.\n",
940 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
941 if (!remove_idle_client()) {
942 DEBUG(0,("winbindd: Exceeding %d "
943 "client connections, no idle "
944 "connection found\n",
945 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
946 break;
949 /* new, non-privileged connection */
950 new_connection(listen_sock, False);
953 if (FD_ISSET(listen_priv_sock, &r_fds)) {
954 while (winbindd_num_clients() >
955 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
956 DEBUG(5,("winbindd: Exceeding %d client "
957 "connections, removing idle "
958 "connection.\n",
959 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
960 if (!remove_idle_client()) {
961 DEBUG(0,("winbindd: Exceeding %d "
962 "client connections, no idle "
963 "connection found\n",
964 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
965 break;
968 /* new, privileged connection */
969 new_connection(listen_priv_sock, True);
972 no_fds_ready:
974 #if 0
975 winbindd_check_cache_size(time(NULL));
976 #endif
978 /* Check signal handling things */
980 winbind_check_sigterm(true);
981 winbind_check_sighup(NULL);
983 if (do_sigusr2) {
984 print_winbindd_status();
985 do_sigusr2 = 0;
988 if (do_sigchld) {
989 pid_t pid;
991 do_sigchld = 0;
993 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
994 winbind_child_died(pid);
999 /* Main function */
1001 int main(int argc, char **argv, char **envp)
1003 static bool is_daemon = False;
1004 static bool Fork = True;
1005 static bool log_stdout = False;
1006 static bool no_process_group = False;
1007 enum {
1008 OPT_DAEMON = 1000,
1009 OPT_FORK,
1010 OPT_NO_PROCESS_GROUP,
1011 OPT_LOG_STDOUT
1013 struct poptOption long_options[] = {
1014 POPT_AUTOHELP
1015 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1016 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1017 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1018 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1019 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1020 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1021 POPT_COMMON_SAMBA
1022 POPT_TABLEEND
1024 poptContext pc;
1025 int opt;
1026 TALLOC_CTX *frame = talloc_stackframe();
1028 /* glibc (?) likes to print "User defined signal 1" and exit if a
1029 SIGUSR[12] is received before a handler is installed */
1031 CatchSignal(SIGUSR1, SIG_IGN);
1032 CatchSignal(SIGUSR2, SIG_IGN);
1034 fault_setup((void (*)(void *))fault_quit );
1035 dump_core_setup("winbindd");
1037 load_case_tables();
1039 /* Initialise for running in non-root mode */
1041 sec_init();
1043 set_remote_machine_name("winbindd", False);
1045 /* Set environment variable so we don't recursively call ourselves.
1046 This may also be useful interactively. */
1048 if ( !winbind_off() ) {
1049 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1050 exit(1);
1053 /* Initialise samba/rpc client stuff */
1055 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1057 while ((opt = poptGetNextOpt(pc)) != -1) {
1058 switch (opt) {
1059 /* Don't become a daemon */
1060 case OPT_DAEMON:
1061 is_daemon = True;
1062 break;
1063 case 'i':
1064 interactive = True;
1065 log_stdout = True;
1066 Fork = False;
1067 break;
1068 case OPT_FORK:
1069 Fork = false;
1070 break;
1071 case OPT_NO_PROCESS_GROUP:
1072 no_process_group = true;
1073 break;
1074 case OPT_LOG_STDOUT:
1075 log_stdout = true;
1076 break;
1077 case 'n':
1078 opt_nocache = true;
1079 break;
1080 default:
1081 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1082 poptBadOption(pc, 0), poptStrerror(opt));
1083 poptPrintUsage(pc, stderr, 0);
1084 exit(1);
1088 if (is_daemon && interactive) {
1089 d_fprintf(stderr,"\nERROR: "
1090 "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1091 poptPrintUsage(pc, stderr, 0);
1092 exit(1);
1095 if (log_stdout && Fork) {
1096 d_fprintf(stderr, "\nERROR: "
1097 "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1098 poptPrintUsage(pc, stderr, 0);
1099 exit(1);
1102 poptFreeContext(pc);
1104 if (!override_logfile) {
1105 char *lfile = NULL;
1106 if (asprintf(&lfile,"%s/log.winbindd",
1107 get_dyn_LOGFILEBASE()) > 0) {
1108 lp_set_logfile(lfile);
1109 SAFE_FREE(lfile);
1112 setup_logging("winbindd", log_stdout);
1113 reopen_logs();
1115 DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1116 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1118 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1119 DEBUG(0, ("error opening config file\n"));
1120 exit(1);
1123 /* Initialise messaging system */
1125 if (winbind_messaging_context() == NULL) {
1126 exit(1);
1129 if (!reload_services_file(NULL)) {
1130 DEBUG(0, ("error opening config file\n"));
1131 exit(1);
1134 if (!directory_exist(lp_lockdir(), NULL)) {
1135 mkdir(lp_lockdir(), 0755);
1138 /* Setup names. */
1140 if (!init_names())
1141 exit(1);
1143 load_interfaces();
1145 if (!secrets_init()) {
1147 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1148 return False;
1151 /* Enable netbios namecache */
1153 namecache_enable();
1155 /* Unblock all signals we are interested in as they may have been
1156 blocked by the parent process. */
1158 BlockSignals(False, SIGINT);
1159 BlockSignals(False, SIGQUIT);
1160 BlockSignals(False, SIGTERM);
1161 BlockSignals(False, SIGUSR1);
1162 BlockSignals(False, SIGUSR2);
1163 BlockSignals(False, SIGHUP);
1164 BlockSignals(False, SIGCHLD);
1166 /* Setup signal handlers */
1168 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1169 CatchSignal(SIGQUIT, termination_handler);
1170 CatchSignal(SIGTERM, termination_handler);
1171 CatchSignal(SIGCHLD, sigchld_handler);
1173 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1175 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1176 CatchSignal(SIGHUP, sighup_handler);
1178 if (!interactive)
1179 become_daemon(Fork, no_process_group);
1181 pidfile_create("winbindd");
1183 #if HAVE_SETPGID
1185 * If we're interactive we want to set our own process group for
1186 * signal management.
1188 if (interactive && !no_process_group)
1189 setpgid( (pid_t)0, (pid_t)0);
1190 #endif
1192 TimeInit();
1194 /* Don't use winbindd_reinit_after_fork here as
1195 * we're just starting up and haven't created any
1196 * winbindd-specific resources we must free yet. JRA.
1199 if (!reinit_after_fork(winbind_messaging_context(),
1200 winbind_event_context(), false)) {
1201 DEBUG(0,("reinit_after_fork() failed\n"));
1202 exit(1);
1206 * Ensure all cache and idmap caches are consistent
1207 * and initialized before we startup.
1209 if (!winbindd_cache_validate_and_initialize()) {
1210 exit(1);
1213 /* get broadcast messages */
1214 claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1216 /* React on 'smbcontrol winbindd reload-config' in the same way
1217 as to SIGHUP signal */
1218 messaging_register(winbind_messaging_context(), NULL,
1219 MSG_SMB_CONF_UPDATED, msg_reload_services);
1220 messaging_register(winbind_messaging_context(), NULL,
1221 MSG_SHUTDOWN, msg_shutdown);
1223 /* Handle online/offline messages. */
1224 messaging_register(winbind_messaging_context(), NULL,
1225 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1226 messaging_register(winbind_messaging_context(), NULL,
1227 MSG_WINBIND_ONLINE, winbind_msg_online);
1228 messaging_register(winbind_messaging_context(), NULL,
1229 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1231 messaging_register(winbind_messaging_context(), NULL,
1232 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1234 messaging_register(winbind_messaging_context(), NULL,
1235 MSG_WINBIND_VALIDATE_CACHE,
1236 winbind_msg_validate_cache);
1238 messaging_register(winbind_messaging_context(), NULL,
1239 MSG_WINBIND_DUMP_DOMAIN_LIST,
1240 winbind_msg_dump_domain_list);
1242 /* Register handler for MSG_DEBUG. */
1243 messaging_register(winbind_messaging_context(), NULL,
1244 MSG_DEBUG,
1245 winbind_msg_debug);
1247 netsamlogon_cache_init(); /* Non-critical */
1249 /* clear the cached list of trusted domains */
1251 wcache_tdc_clear();
1253 if (!init_domain_list()) {
1254 DEBUG(0,("unable to initialize domain list\n"));
1255 exit(1);
1258 init_idmap_child();
1259 init_locator_child();
1261 smb_nscd_flush_user_cache();
1262 smb_nscd_flush_group_cache();
1264 /* Loop waiting for requests */
1266 TALLOC_FREE(frame);
1267 while (1) {
1268 frame = talloc_stackframe();
1269 process_loop();
1270 TALLOC_FREE(frame);
1273 return 0;