Update.
[glibc.git] / nscd / nscd.c
blobf6b22d41797b9cde87ad234c99b723a37870a063
1 /* Copyright (c) 1998-2003, 2004 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Thorsten Kukuk <kukuk@suse.de>, 1998.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 /* nscd - Name Service Cache Daemon. Caches passwd, group, and hosts. */
22 #include <argp.h>
23 #include <assert.h>
24 #include <dirent.h>
25 #include <errno.h>
26 #include <error.h>
27 #include <fcntl.h>
28 #include <libintl.h>
29 #include <locale.h>
30 #include <paths.h>
31 #include <pthread.h>
32 #include <signal.h>
33 #include <stdbool.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <syslog.h>
38 #include <unistd.h>
39 #include <sys/mman.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/uio.h>
43 #include <sys/un.h>
45 #include "dbg_log.h"
46 #include "nscd.h"
47 #include "../nss/nsswitch.h"
48 #include <device-nrs.h>
50 /* Get libc version number. */
51 #include <version.h>
53 #define PACKAGE _libc_intl_domainname
55 /* Structure used by main() thread to keep track of the number of
56 active threads. Used to limit how many threads it will create
57 and under a shutdown condition to wait till all in-progress
58 requests have finished before "turning off the lights". */
60 typedef struct
62 int num_active;
63 pthread_cond_t thread_exit_cv;
64 pthread_mutex_t mutex;
65 } thread_info_t;
67 thread_info_t thread_info;
69 int do_shutdown;
70 int disabled_passwd;
71 int disabled_group;
72 int go_background = 1;
74 int secure_in_use;
75 static const char *conffile = _PATH_NSCDCONF;
77 time_t start_time;
79 static int check_pid (const char *file);
80 static int write_pid (const char *file);
82 /* Name and version of program. */
83 static void print_version (FILE *stream, struct argp_state *state);
84 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
86 /* Definitions of arguments for argp functions. */
87 static const struct argp_option options[] =
89 { "config-file", 'f', N_("NAME"), 0,
90 N_("Read configuration data from NAME") },
91 { "debug", 'd', NULL, 0,
92 N_("Do not fork and display messages on the current tty") },
93 { "nthreads", 't', N_("NUMBER"), 0, N_("Start NUMBER threads") },
94 { "shutdown", 'K', NULL, 0, N_("Shut the server down") },
95 { "statistic", 'g', NULL, 0, N_("Print current configuration statistic") },
96 { "invalidate", 'i', N_("TABLE"), 0,
97 N_("Invalidate the specified cache") },
98 { "secure", 'S', N_("TABLE,yes"), 0, N_("Use separate cache for each user")},
99 { NULL, 0, NULL, 0, NULL }
102 /* Short description of program. */
103 static const char doc[] = N_("Name Service Cache Daemon.");
105 /* Prototype for option handler. */
106 static error_t parse_opt (int key, char *arg, struct argp_state *state);
108 /* Data structure to communicate with argp functions. */
109 static struct argp argp =
111 options, parse_opt, NULL, doc,
114 /* True if only statistics are requested. */
115 static bool get_stats;
118 main (int argc, char **argv)
120 int remaining;
122 /* Set locale via LC_ALL. */
123 setlocale (LC_ALL, "");
124 /* Set the text message domain. */
125 textdomain (PACKAGE);
127 /* Parse and process arguments. */
128 argp_parse (&argp, argc, argv, 0, &remaining, NULL);
130 if (remaining != argc)
132 error (0, 0, gettext ("wrong number of arguments"));
133 argp_help (&argp, stdout, ARGP_HELP_SEE, program_invocation_short_name);
134 exit (EXIT_FAILURE);
137 /* Read the configuration file. */
138 if (nscd_parse_file (conffile, dbs) != 0)
140 /* We couldn't read the configuration file. We don't start the
141 server. */
142 dbg_log (_("cannot read configuration file; this is fatal"));
143 exit (1);
146 /* Do we only get statistics? */
147 if (get_stats)
148 /* Does not return. */
149 receive_print_stats ();
151 /* Check if we are already running. */
152 if (check_pid (_PATH_NSCDPID))
153 error (EXIT_FAILURE, 0, _("already running"));
155 /* Remember when we started. */
156 start_time = time (NULL);
158 /* Behave like a daemon. */
159 if (go_background)
161 int i;
163 pid_t pid = fork ();
164 if (pid == -1)
165 error (EXIT_FAILURE, errno, _("cannot fork"));
166 if (pid != 0)
167 exit (0);
169 int nullfd = open (_PATH_DEVNULL, O_RDWR);
170 if (nullfd != -1)
172 struct stat64 st;
174 if (fstat64 (nullfd, &st) == 0 && S_ISCHR (st.st_mode) != 0
175 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
176 && st.st_rdev == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
177 #endif
180 /* It is the /dev/null special device alright. */
181 (void) dup2 (nullfd, STDIN_FILENO);
182 (void) dup2 (nullfd, STDOUT_FILENO);
183 (void) dup2 (nullfd, STDERR_FILENO);
185 if (nullfd > 2)
186 close (nullfd);
188 else
190 /* Ugh, somebody is trying to play a trick on us. */
191 close (nullfd);
192 nullfd = -1;
195 int min_close_fd = nullfd == -1 ? 0 : STDERR_FILENO + 1;
197 DIR *d = opendir ("/proc/self/fd");
198 if (d != NULL)
200 struct dirent64 *dirent;
201 int dfdn = dirfd (d);
203 while ((dirent = readdir64 (d)) != NULL)
205 char *endp;
206 long int fdn = strtol (dirent->d_name, &endp, 10);
208 if (*endp == '\0' && fdn != dfdn && fdn >= min_close_fd)
209 close ((int) fdn);
212 closedir (d);
214 else
215 for (i = min_close_fd; i < getdtablesize (); i++)
216 close (i);
218 pid = fork ();
219 if (pid == -1)
220 error (EXIT_FAILURE, errno, _("cannot fork"));
221 if (pid != 0)
222 exit (0);
224 setsid ();
226 chdir ("/");
228 openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
230 if (write_pid (_PATH_NSCDPID) < 0)
231 dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
233 if (!init_logfile ())
234 dbg_log (_("Could not create log file"));
236 /* Ignore job control signals. */
237 signal (SIGTTOU, SIG_IGN);
238 signal (SIGTTIN, SIG_IGN);
239 signal (SIGTSTP, SIG_IGN);
242 signal (SIGINT, termination_handler);
243 signal (SIGQUIT, termination_handler);
244 signal (SIGTERM, termination_handler);
245 signal (SIGPIPE, SIG_IGN);
247 /* Cleanup files created by a previous 'bind'. */
248 unlink (_PATH_NSCDSOCKET);
250 /* Make sure we do not get recursive calls. */
251 __nss_disable_nscd ();
253 /* Init databases. */
254 nscd_init ();
256 /* Handle incoming requests */
257 start_threads ();
259 return 0;
263 /* Handle program arguments. */
264 static error_t
265 parse_opt (int key, char *arg, struct argp_state *state)
267 switch (key)
269 case 'd':
270 ++debug_level;
271 go_background = 0;
272 break;
274 case 'f':
275 conffile = arg;
276 break;
278 case 'K':
279 if (getuid () != 0)
280 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
282 int sock = nscd_open_socket ();
283 request_header req;
284 ssize_t nbytes;
286 if (sock == -1)
287 exit (EXIT_FAILURE);
289 req.version = NSCD_VERSION;
290 req.type = SHUTDOWN;
291 req.key_len = 0;
292 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
293 sizeof (request_header)));
294 close (sock);
295 exit (nbytes != sizeof (request_header) ? EXIT_FAILURE : EXIT_SUCCESS);
298 case 'g':
299 get_stats = true;
300 break;
302 case 'i':
303 if (getuid () != 0)
304 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
305 else
307 int sock = nscd_open_socket ();
309 if (sock == -1)
310 exit (EXIT_FAILURE);
312 request_header req;
313 ssize_t nbytes;
314 struct iovec iov[2];
316 if (strcmp (arg, "passwd") == 0)
317 req.key_len = sizeof "passwd";
318 else if (strcmp (arg, "group") == 0)
319 req.key_len = sizeof "group";
320 else if (strcmp (arg, "hosts") == 0)
321 req.key_len = sizeof "hosts";
322 else
323 return ARGP_ERR_UNKNOWN;
325 req.version = NSCD_VERSION;
326 req.type = INVALIDATE;
328 iov[0].iov_base = &req;
329 iov[0].iov_len = sizeof (req);
330 iov[1].iov_base = (void *) key;
331 iov[1].iov_len = req.key_len;
333 nbytes = TEMP_FAILURE_RETRY (writev (sock, iov, 2));
335 close (sock);
337 exit (nbytes != iov[0].iov_len + iov[1].iov_len
338 ? EXIT_FAILURE : EXIT_SUCCESS);
341 case 't':
342 nthreads = atol (arg);
343 break;
345 case 'S':
346 if (strcmp (arg, "passwd,yes") == 0)
347 secure_in_use = dbs[pwddb].secure = 1;
348 else if (strcmp (arg, "group,yes") == 0)
349 secure_in_use = dbs[grpdb].secure = 1;
350 else if (strcmp (arg, "hosts,yes") == 0)
351 secure_in_use = dbs[hstdb].secure = 1;
352 break;
354 default:
355 return ARGP_ERR_UNKNOWN;
358 return 0;
361 /* Print the version information. */
362 static void
363 print_version (FILE *stream, struct argp_state *state)
365 fprintf (stream, "nscd (GNU %s) %s\n", PACKAGE, VERSION);
366 fprintf (stream, gettext ("\
367 Copyright (C) %s Free Software Foundation, Inc.\n\
368 This is free software; see the source for copying conditions. There is NO\n\
369 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
370 "), "2004");
371 fprintf (stream, gettext ("Written by %s.\n"),
372 "Thorsten Kukuk and Ulrich Drepper");
376 /* Create a socket connected to a name. */
378 nscd_open_socket (void)
380 struct sockaddr_un addr;
381 int sock;
383 sock = socket (PF_UNIX, SOCK_STREAM, 0);
384 if (sock < 0)
385 return -1;
387 addr.sun_family = AF_UNIX;
388 assert (sizeof (addr.sun_path) >= sizeof (_PATH_NSCDSOCKET));
389 strcpy (addr.sun_path, _PATH_NSCDSOCKET);
390 if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0)
392 close (sock);
393 return -1;
396 return sock;
399 /* Cleanup. */
400 void
401 termination_handler (int signum)
403 close_sockets ();
405 /* Clean up the file created by 'bind'. */
406 unlink (_PATH_NSCDSOCKET);
408 /* Clean up pid file. */
409 unlink (_PATH_NSCDPID);
411 // XXX Terminate threads.
413 /* Synchronize memory. */
414 for (int cnt = 0; cnt < lastdb; ++cnt)
415 if (dbs[cnt].persistent)
416 // XXX async OK?
417 msync (dbs[cnt].head, dbs[cnt].memsize, MS_ASYNC);
419 _exit (EXIT_SUCCESS);
422 /* Returns 1 if the process in pid file FILE is running, 0 if not. */
423 static int
424 check_pid (const char *file)
426 FILE *fp;
428 fp = fopen (file, "r");
429 if (fp)
431 pid_t pid;
432 int n;
434 n = fscanf (fp, "%d", &pid);
435 fclose (fp);
437 if (n != 1 || kill (pid, 0) == 0)
438 return 1;
441 return 0;
444 /* Write the current process id to the file FILE.
445 Returns 0 if successful, -1 if not. */
446 static int
447 write_pid (const char *file)
449 FILE *fp;
451 fp = fopen (file, "w");
452 if (fp == NULL)
453 return -1;
455 fprintf (fp, "%d\n", getpid ());
456 if (fflush (fp) || ferror (fp))
457 return -1;
459 fclose (fp);
461 return 0;