2 * Copyright (c) 2005 Michael Bushkov <bushman@rsu.ru>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in thereg
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/types.h>
32 #include <sys/event.h>
33 #include <sys/socket.h>
35 #include <sys/param.h>
49 #include "agents/passwd.h"
50 #include "agents/group.h"
51 #include "agents/services.h"
59 #include "singletons.h"
62 #define CONFIG_PATH "/etc/nscd.conf"
64 #define DEFAULT_CONFIG_PATH "nscd.conf"
66 #define MAX_SOCKET_IO_SIZE 4096
68 struct processing_thread_args {
70 struct configuration *the_configuration;
71 struct runtime_env *the_runtime_env;
74 static void accept_connection(struct kevent *, struct runtime_env *,
75 struct configuration *);
76 static void destroy_cache_(cache);
77 static void destroy_runtime_env(struct runtime_env *);
78 static cache init_cache_(struct configuration *);
79 static struct runtime_env *init_runtime_env(struct configuration *);
80 static void processing_loop(cache, struct runtime_env *,
81 struct configuration *);
82 static void process_socket_event(struct kevent *, struct runtime_env *,
83 struct configuration *);
84 static void process_timer_event(struct kevent *, struct runtime_env *,
85 struct configuration *);
86 static void *processing_thread(void *);
87 static void usage(void);
89 void get_time_func(struct timeval *);
95 "usage: nscd [-dnst] [-i cachename] [-I cachename]\n");
100 init_cache_(struct configuration *config)
102 struct cache_params params;
105 struct configuration_entry *config_entry;
109 TRACE_IN(init_cache_);
111 memset(¶ms, 0, sizeof(struct cache_params));
112 params.get_time_func = get_time_func;
113 retval = init_cache(¶ms);
115 size = configuration_get_entries_size(config);
116 for (i = 0; i < size; ++i) {
117 config_entry = configuration_get_entry(config, i);
119 * We should register common entries now - multipart entries
120 * would be registered automatically during the queries.
122 res = register_cache_entry(retval, (struct cache_entry_params *)
123 &config_entry->positive_cache_params);
124 config_entry->positive_cache_entry = find_cache_entry(retval,
125 config_entry->positive_cache_params.entry_name);
126 assert(config_entry->positive_cache_entry !=
127 INVALID_CACHE_ENTRY);
129 res = register_cache_entry(retval, (struct cache_entry_params *)
130 &config_entry->negative_cache_params);
131 config_entry->negative_cache_entry = find_cache_entry(retval,
132 config_entry->negative_cache_params.entry_name);
133 assert(config_entry->negative_cache_entry !=
134 INVALID_CACHE_ENTRY);
137 LOG_MSG_2("cache", "cache was successfully initialized");
138 TRACE_OUT(init_cache_);
143 destroy_cache_(cache the_cache)
145 TRACE_IN(destroy_cache_);
146 destroy_cache(the_cache);
147 TRACE_OUT(destroy_cache_);
151 * Socket and kqueues are prepared here. We have one global queue for both
152 * socket and timers events.
154 static struct runtime_env *
155 init_runtime_env(struct configuration *config)
158 struct sockaddr_un serv_addr;
160 struct kevent eventlist;
161 struct timespec timeout;
163 struct runtime_env *retval;
165 TRACE_IN(init_runtime_env);
166 retval = (struct runtime_env *)calloc(1, sizeof(struct runtime_env));
167 assert(retval != NULL);
169 retval->sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
171 if (config->force_unlink == 1)
172 unlink(config->socket_path);
174 memset(&serv_addr, 0, sizeof(struct sockaddr_un));
175 serv_addr.sun_family = PF_LOCAL;
176 strlcpy(serv_addr.sun_path, config->socket_path,
177 sizeof(serv_addr.sun_path));
178 serv_addr_len = sizeof(serv_addr.sun_family) +
179 strlen(serv_addr.sun_path) + 1;
181 if (bind(retval->sockfd, (struct sockaddr *)&serv_addr,
182 serv_addr_len) == -1) {
183 close(retval->sockfd);
186 LOG_ERR_2("runtime environment", "can't bind socket to path: "
187 "%s", config->socket_path);
188 TRACE_OUT(init_runtime_env);
191 LOG_MSG_2("runtime environment", "using socket %s",
192 config->socket_path);
195 * Here we're marking socket as non-blocking and setting its backlog
196 * to the maximum value
198 chmod(config->socket_path, config->socket_mode);
199 listen(retval->sockfd, -1);
200 fcntl(retval->sockfd, F_SETFL, O_NONBLOCK);
202 retval->queue = kqueue();
203 assert(retval->queue != -1);
205 EV_SET(&eventlist, retval->sockfd, EVFILT_READ, EV_ADD | EV_ONESHOT,
207 memset(&timeout, 0, sizeof(struct timespec));
208 kevent(retval->queue, &eventlist, 1, NULL, 0, &timeout);
210 LOG_MSG_2("runtime environment", "successfully initialized");
211 TRACE_OUT(init_runtime_env);
216 destroy_runtime_env(struct runtime_env *env)
218 TRACE_IN(destroy_runtime_env);
222 TRACE_OUT(destroy_runtime_env);
226 accept_connection(struct kevent *event_data, struct runtime_env *env,
227 struct configuration *config)
229 struct kevent eventlist[2];
230 struct timespec timeout;
231 struct query_state *qstate;
239 TRACE_IN(accept_connection);
240 fd = accept(event_data->ident, NULL, NULL);
242 LOG_ERR_2("accept_connection", "error %d during accept()",
244 TRACE_OUT(accept_connection);
248 if (getpeereid(fd, &euid, &egid) != 0) {
249 LOG_ERR_2("accept_connection", "error %d during getpeereid()",
251 TRACE_OUT(accept_connection);
255 qstate = init_query_state(fd, sizeof(int), euid, egid);
256 if (qstate == NULL) {
257 LOG_ERR_2("accept_connection", "can't init query_state");
258 TRACE_OUT(accept_connection);
262 memset(&timeout, 0, sizeof(struct timespec));
263 EV_SET(&eventlist[0], fd, EVFILT_TIMER, EV_ADD | EV_ONESHOT,
264 0, qstate->timeout.tv_sec * 1000, qstate);
265 EV_SET(&eventlist[1], fd, EVFILT_READ, EV_ADD | EV_ONESHOT,
266 NOTE_LOWAT, qstate->kevent_watermark, qstate);
267 res = kevent(env->queue, eventlist, 2, NULL, 0, &timeout);
269 LOG_ERR_2("accept_connection", "kevent error");
271 TRACE_OUT(accept_connection);
275 process_socket_event(struct kevent *event_data, struct runtime_env *env,
276 struct configuration *config)
278 struct kevent eventlist[2];
279 struct timeval query_timeout;
280 struct timespec kevent_timeout;
284 struct query_state *qstate;
286 TRACE_IN(process_socket_event);
287 eof_res = event_data->flags & EV_EOF ? 1 : 0;
290 memset(&kevent_timeout, 0, sizeof(struct timespec));
291 EV_SET(&eventlist[0], event_data->ident, EVFILT_TIMER, EV_DELETE,
293 nevents = kevent(env->queue, eventlist, 1, NULL, 0, &kevent_timeout);
295 if (errno == ENOENT) {
296 /* the timer is already handling this event */
297 TRACE_OUT(process_socket_event);
300 /* some other error happened */
301 LOG_ERR_2("process_socket_event", "kevent error, errno"
303 TRACE_OUT(process_socket_event);
307 qstate = (struct query_state *)event_data->udata;
310 * If the buffer that is to be send/received is too large,
311 * we send it implicitly, by using query_io_buffer_read and
312 * query_io_buffer_write functions in the query_state. These functions
313 * use the temporary buffer, which is later send/received in parts.
314 * The code below implements buffer splitting/mergind for send/receive
315 * operations. It also does the actual socket IO operations.
317 if (((qstate->use_alternate_io == 0) &&
318 (qstate->kevent_watermark <= event_data->data)) ||
319 ((qstate->use_alternate_io != 0) &&
320 (qstate->io_buffer_watermark <= event_data->data))) {
321 if (qstate->use_alternate_io != 0) {
322 switch (qstate->io_buffer_filter) {
324 io_res = query_socket_read(qstate,
326 qstate->io_buffer_watermark);
328 qstate->use_alternate_io = 0;
329 qstate->process_func = NULL;
331 qstate->io_buffer_p += io_res;
332 if (qstate->io_buffer_p ==
334 qstate->io_buffer_size) {
335 qstate->io_buffer_p =
337 qstate->use_alternate_io = 0;
346 if (qstate->use_alternate_io == 0) {
348 res = qstate->process_func(qstate);
349 } while ((qstate->kevent_watermark == 0) &&
350 (qstate->process_func != NULL) &&
354 qstate->process_func = NULL;
357 if ((qstate->use_alternate_io != 0) &&
358 (qstate->io_buffer_filter == EVFILT_WRITE)) {
359 io_res = query_socket_write(qstate, qstate->io_buffer_p,
360 qstate->io_buffer_watermark);
362 qstate->use_alternate_io = 0;
363 qstate->process_func = NULL;
365 qstate->io_buffer_p += io_res;
368 /* assuming that socket was closed */
369 qstate->process_func = NULL;
370 qstate->use_alternate_io = 0;
373 if (((qstate->process_func == NULL) &&
374 (qstate->use_alternate_io == 0)) ||
375 (eof_res != 0) || (res != 0)) {
376 destroy_query_state(qstate);
377 close(event_data->ident);
378 TRACE_OUT(process_socket_event);
382 /* updating the query_state lifetime variable */
383 get_time_func(&query_timeout);
384 query_timeout.tv_usec = 0;
385 query_timeout.tv_sec -= qstate->creation_time.tv_sec;
386 if (query_timeout.tv_sec > qstate->timeout.tv_sec)
387 query_timeout.tv_sec = 0;
389 query_timeout.tv_sec = qstate->timeout.tv_sec -
390 query_timeout.tv_sec;
392 if ((qstate->use_alternate_io != 0) && (qstate->io_buffer_p ==
393 qstate->io_buffer + qstate->io_buffer_size))
394 qstate->use_alternate_io = 0;
396 if (qstate->use_alternate_io == 0) {
398 * If we must send/receive the large block of data,
399 * we should prepare the query_state's io_XXX fields.
400 * We should also substitute its write_func and read_func
401 * with the query_io_buffer_write and query_io_buffer_read,
402 * which will allow us to implicitly send/receive this large
403 * buffer later (in the subsequent calls to the
404 * process_socket_event).
406 if (qstate->kevent_watermark > MAX_SOCKET_IO_SIZE) {
407 if (qstate->io_buffer != NULL)
408 free(qstate->io_buffer);
410 qstate->io_buffer = (char *)calloc(1,
411 qstate->kevent_watermark);
412 assert(qstate->io_buffer != NULL);
414 qstate->io_buffer_p = qstate->io_buffer;
415 qstate->io_buffer_size = qstate->kevent_watermark;
416 qstate->io_buffer_filter = qstate->kevent_filter;
418 qstate->write_func = query_io_buffer_write;
419 qstate->read_func = query_io_buffer_read;
421 if (qstate->kevent_filter == EVFILT_READ)
422 qstate->use_alternate_io = 1;
424 qstate->io_buffer_watermark = MAX_SOCKET_IO_SIZE;
425 EV_SET(&eventlist[1], event_data->ident,
426 qstate->kevent_filter, EV_ADD | EV_ONESHOT,
427 NOTE_LOWAT, MAX_SOCKET_IO_SIZE, qstate);
429 EV_SET(&eventlist[1], event_data->ident,
430 qstate->kevent_filter, EV_ADD | EV_ONESHOT,
431 NOTE_LOWAT, qstate->kevent_watermark, qstate);
434 if (qstate->io_buffer + qstate->io_buffer_size -
435 qstate->io_buffer_p <
436 MAX_SOCKET_IO_SIZE) {
437 qstate->io_buffer_watermark = qstate->io_buffer +
438 qstate->io_buffer_size - qstate->io_buffer_p;
439 EV_SET(&eventlist[1], event_data->ident,
440 qstate->io_buffer_filter,
441 EV_ADD | EV_ONESHOT, NOTE_LOWAT,
442 qstate->io_buffer_watermark,
445 qstate->io_buffer_watermark = MAX_SOCKET_IO_SIZE;
446 EV_SET(&eventlist[1], event_data->ident,
447 qstate->io_buffer_filter, EV_ADD | EV_ONESHOT,
448 NOTE_LOWAT, MAX_SOCKET_IO_SIZE, qstate);
451 EV_SET(&eventlist[0], event_data->ident, EVFILT_TIMER,
452 EV_ADD | EV_ONESHOT, 0, query_timeout.tv_sec * 1000, qstate);
453 kevent(env->queue, eventlist, 2, NULL, 0, &kevent_timeout);
455 TRACE_OUT(process_socket_event);
459 * This routine is called if timer event has been signaled in the kqueue. It
460 * just closes the socket and destroys the query_state.
463 process_timer_event(struct kevent *event_data, struct runtime_env *env,
464 struct configuration *config)
466 struct query_state *qstate;
468 TRACE_IN(process_timer_event);
469 qstate = (struct query_state *)event_data->udata;
470 destroy_query_state(qstate);
471 close(event_data->ident);
472 TRACE_OUT(process_timer_event);
476 * Processing loop is the basic processing routine, that forms a body of each
480 processing_loop(cache the_cache, struct runtime_env *env,
481 struct configuration *config)
483 struct timespec timeout;
484 const int eventlist_size = 1;
485 struct kevent eventlist[eventlist_size];
488 TRACE_MSG("=> processing_loop");
489 memset(&timeout, 0, sizeof(struct timespec));
490 memset(&eventlist, 0, sizeof(struct kevent) * eventlist_size);
493 nevents = kevent(env->queue, NULL, 0, eventlist,
494 eventlist_size, NULL);
496 * we can only receive 1 event on success
499 struct kevent *event_data;
500 event_data = &eventlist[0];
502 if (event_data->ident == env->sockfd) {
503 for (i = 0; i < event_data->data; ++i)
504 accept_connection(event_data, env, config);
506 EV_SET(eventlist, s_runtime_env->sockfd,
507 EVFILT_READ, EV_ADD | EV_ONESHOT,
510 sizeof(struct timespec));
511 kevent(s_runtime_env->queue, eventlist,
512 1, NULL, 0, &timeout);
515 switch (event_data->filter) {
518 process_socket_event(event_data,
522 process_timer_event(event_data,
530 /* this branch shouldn't be currently executed */
534 TRACE_MSG("<= processing_loop");
538 * Wrapper above the processing loop function. It sets the thread signal mask
539 * to avoid SIGPIPE signals (which can happen if the client works incorrectly).
542 processing_thread(void *data)
544 struct processing_thread_args *args;
547 TRACE_MSG("=> processing_thread");
548 args = (struct processing_thread_args *)data;
551 sigaddset(&new, SIGPIPE);
552 if (pthread_sigmask(SIG_BLOCK, &new, NULL) != 0)
553 LOG_ERR_1("processing thread",
554 "thread can't block the SIGPIPE signal");
556 processing_loop(args->the_cache, args->the_runtime_env,
557 args->the_configuration);
559 TRACE_MSG("<= processing_thread");
565 get_time_func(struct timeval *time)
568 memset(&res, 0, sizeof(struct timespec));
569 clock_gettime(CLOCK_MONOTONIC, &res);
571 time->tv_sec = res.tv_sec;
576 * The idea of _nss_cache_cycle_prevention_function is that nsdispatch will
577 * search for this symbol in the executable. This symbol is the attribute of
578 * the caching daemon. So, if it exists, nsdispatch won't try to connect to
579 * the caching daemon and will just ignore the 'cache' source in the
580 * nsswitch.conf. This method helps to avoid cycles and organize
581 * self-performing requests.
584 _nss_cache_cycle_prevention_function(void)
589 main(int argc, char *argv[])
591 struct processing_thread_args *thread_args;
594 struct pidfh *pidfile;
597 char const *config_file;
598 char const *error_str;
602 int trace_mode_enabled;
603 int force_single_threaded;
604 int do_not_daemonize;
605 int clear_user_cache_entries, clear_all_cache_entries;
606 char *user_config_entry_name, *global_config_entry_name;
608 int daemon_mode, interactive_mode;
611 /* by default all debug messages are omitted */
614 /* parsing command line arguments */
615 trace_mode_enabled = 0;
616 force_single_threaded = 0;
617 do_not_daemonize = 0;
618 clear_user_cache_entries = 0;
619 clear_all_cache_entries = 0;
621 user_config_entry_name = NULL;
622 global_config_entry_name = NULL;
623 while ((res = getopt(argc, argv, "nstdi:I:")) != -1) {
626 do_not_daemonize = 1;
629 force_single_threaded = 1;
632 trace_mode_enabled = 1;
635 clear_user_cache_entries = 1;
637 if (strcmp(optarg, "all") != 0)
638 user_config_entry_name = strdup(optarg);
641 clear_all_cache_entries = 1;
643 if (strcmp(optarg, "all") != 0)
644 global_config_entry_name =
657 daemon_mode = do_not_daemonize | force_single_threaded |
659 interactive_mode = clear_user_cache_entries | clear_all_cache_entries |
662 if ((daemon_mode != 0) && (interactive_mode != 0)) {
663 LOG_ERR_1("main", "daemon mode and interactive_mode arguments "
664 "can't be used together");
668 if (interactive_mode != 0) {
669 FILE *pidfin = fopen(DEFAULT_PIDFILE_PATH, "r");
672 struct nscd_connection_params connection_params;
673 nscd_connection connection;
678 errx(EXIT_FAILURE, "There is no daemon running.");
680 memset(pidbuf, 0, sizeof(pidbuf));
681 fread(pidbuf, sizeof(pidbuf) - 1, 1, pidfin);
684 if (ferror(pidfin) != 0)
685 errx(EXIT_FAILURE, "Can't read from pidfile.");
687 if (sscanf(pidbuf, "%d", &pid) != 1)
688 errx(EXIT_FAILURE, "Invalid pidfile.");
689 LOG_MSG_1("main", "daemon PID is %d", pid);
692 memset(&connection_params, 0,
693 sizeof(struct nscd_connection_params));
694 connection_params.socket_path = DEFAULT_SOCKET_PATH;
695 connection = open_nscd_connection__(&connection_params);
696 if (connection == INVALID_NSCD_CONNECTION)
697 errx(EXIT_FAILURE, "Can't connect to the daemon.");
699 if (clear_user_cache_entries != 0) {
700 result = nscd_transform__(connection,
701 user_config_entry_name, TT_USER);
704 "user cache transformation failed");
707 "user cache_transformation "
711 if (clear_all_cache_entries != 0) {
713 errx(EXIT_FAILURE, "Only root can initiate "
714 "global cache transformation.");
716 result = nscd_transform__(connection,
717 global_config_entry_name, TT_ALL);
720 "global cache transformation "
724 "global cache transformation "
728 close_nscd_connection__(connection);
730 free(user_config_entry_name);
731 free(global_config_entry_name);
732 return (EXIT_SUCCESS);
735 pidfile = pidfile_open(DEFAULT_PIDFILE_PATH, 0644, &pid);
736 if (pidfile == NULL) {
738 errx(EXIT_FAILURE, "Daemon already running, pid: %d.",
740 warn("Cannot open or create pidfile");
743 if (trace_mode_enabled == 1)
746 /* blocking the main thread from receiving SIGPIPE signal */
747 sigblock(sigmask(SIGPIPE));
750 if (do_not_daemonize == 0) {
751 res = daemon(0, trace_mode_enabled == 0 ? 0 : 1);
753 LOG_ERR_1("main", "can't daemonize myself: %s",
755 pidfile_remove(pidfile);
758 LOG_MSG_1("main", "successfully daemonized");
761 pidfile_write(pidfile);
763 s_agent_table = init_agent_table();
764 register_agent(s_agent_table, init_passwd_agent());
765 register_agent(s_agent_table, init_passwd_mp_agent());
766 register_agent(s_agent_table, init_group_agent());
767 register_agent(s_agent_table, init_group_mp_agent());
768 register_agent(s_agent_table, init_services_agent());
769 register_agent(s_agent_table, init_services_mp_agent());
770 LOG_MSG_1("main", "request agents registered successfully");
773 * Hosts agent can't work properly until we have access to the
774 * appropriate dtab structures, which are used in nsdispatch
777 register_agent(s_agent_table, init_hosts_agent());
780 /* configuration initialization */
781 s_configuration = init_configuration();
782 fill_configuration_defaults(s_configuration);
786 config_file = CONFIG_PATH;
788 res = parse_config_file(s_configuration, config_file, &error_str,
790 if ((res != 0) && (error_str == NULL)) {
791 config_file = DEFAULT_CONFIG_PATH;
792 res = parse_config_file(s_configuration, config_file,
793 &error_str, &error_line);
797 if (error_str != NULL) {
798 LOG_ERR_1("main", "error in configuration file(%s, %d): %s\n",
799 config_file, error_line, error_str);
801 LOG_ERR_1("main", "no configuration file found "
802 "- was looking for %s and %s",
803 CONFIG_PATH, DEFAULT_CONFIG_PATH);
805 destroy_configuration(s_configuration);
809 if (force_single_threaded == 1)
810 s_configuration->threads_num = 1;
812 /* cache initialization */
813 s_cache = init_cache_(s_configuration);
814 if (s_cache == NULL) {
815 LOG_ERR_1("main", "can't initialize the cache");
816 destroy_configuration(s_configuration);
820 /* runtime environment initialization */
821 s_runtime_env = init_runtime_env(s_configuration);
822 if (s_runtime_env == NULL) {
823 LOG_ERR_1("main", "can't initialize the runtime environment");
824 destroy_configuration(s_configuration);
825 destroy_cache_(s_cache);
829 if (s_configuration->threads_num > 1) {
830 threads = (pthread_t *)calloc(1, sizeof(pthread_t) *
831 s_configuration->threads_num);
832 for (i = 0; i < s_configuration->threads_num; ++i) {
833 thread_args = (struct processing_thread_args *)malloc(
834 sizeof(struct processing_thread_args));
835 thread_args->the_cache = s_cache;
836 thread_args->the_runtime_env = s_runtime_env;
837 thread_args->the_configuration = s_configuration;
839 LOG_MSG_1("main", "thread #%d was successfully created",
841 pthread_create(&threads[i], NULL, processing_thread,
847 for (i = 0; i < s_configuration->threads_num; ++i)
848 pthread_join(threads[i], NULL);
850 LOG_MSG_1("main", "working in single-threaded mode");
851 processing_loop(s_cache, s_runtime_env, s_configuration);
855 /* runtime environment destruction */
856 destroy_runtime_env(s_runtime_env);
858 /* cache destruction */
859 destroy_cache_(s_cache);
861 /* configuration destruction */
862 destroy_configuration(s_configuration);
864 /* agents table destruction */
865 destroy_agent_table(s_agent_table);
867 pidfile_remove(pidfile);
868 return (EXIT_SUCCESS);