This is not really associated with [bug #209], but is a test.
[glibc.git] / nscd / nscd.c
blobe3040bb20f66e7c5440ccbb7b8971590203c4dc3
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/socket.h>
40 #include <sys/stat.h>
41 #include <sys/un.h>
43 #include "dbg_log.h"
44 #include "nscd.h"
45 #include "../nss/nsswitch.h"
46 #include <device-nrs.h>
48 /* Get libc version number. */
49 #include <version.h>
51 #define PACKAGE _libc_intl_domainname
53 /* Structure used by main() thread to keep track of the number of
54 active threads. Used to limit how many threads it will create
55 and under a shutdown condition to wait till all in-progress
56 requests have finished before "turning off the lights". */
58 typedef struct
60 int num_active;
61 pthread_cond_t thread_exit_cv;
62 pthread_mutex_t mutex;
63 } thread_info_t;
65 thread_info_t thread_info;
67 int do_shutdown;
68 int disabled_passwd;
69 int disabled_group;
70 int go_background = 1;
72 int secure[lastdb];
73 int secure_in_use;
74 static const char *conffile = _PATH_NSCDCONF;
76 time_t start_time;
78 static int check_pid (const char *file);
79 static int write_pid (const char *file);
81 /* Name and version of program. */
82 static void print_version (FILE *stream, struct argp_state *state);
83 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
85 /* Definitions of arguments for argp functions. */
86 static const struct argp_option options[] =
88 { "config-file", 'f', N_("NAME"), 0,
89 N_("Read configuration data from NAME") },
90 { "debug", 'd', NULL, 0,
91 N_("Do not fork and display messages on the current tty") },
92 { "nthreads", 't', N_("NUMBER"), 0, N_("Start NUMBER threads") },
93 { "shutdown", 'K', NULL, 0, N_("Shut the server down") },
94 { "statistic", 'g', NULL, 0, N_("Print current configuration statistic") },
95 { "invalidate", 'i', N_("TABLE"), 0,
96 N_("Invalidate the specified cache") },
97 { "secure", 'S', N_("TABLE,yes"), 0, N_("Use separate cache for each user")},
98 { NULL, 0, NULL, 0, NULL }
101 /* Short description of program. */
102 static const char doc[] = N_("Name Service Cache Daemon.");
104 /* Prototype for option handler. */
105 static error_t parse_opt (int key, char *arg, struct argp_state *state);
107 /* Data structure to communicate with argp functions. */
108 static struct argp argp =
110 options, parse_opt, NULL, doc,
113 /* True if only statistics are requested. */
114 static bool get_stats;
117 main (int argc, char **argv)
119 int remaining;
121 /* Set locale via LC_ALL. */
122 setlocale (LC_ALL, "");
123 /* Set the text message domain. */
124 textdomain (PACKAGE);
126 /* Parse and process arguments. */
127 argp_parse (&argp, argc, argv, 0, &remaining, NULL);
129 if (remaining != argc)
131 error (0, 0, gettext ("wrong number of arguments"));
132 argp_help (&argp, stdout, ARGP_HELP_SEE, program_invocation_short_name);
133 exit (EXIT_FAILURE);
136 /* Read the configuration file. */
137 if (nscd_parse_file (conffile, dbs) != 0)
139 /* We couldn't read the configuration file. We don't start the
140 server. */
141 dbg_log (_("cannot read configuration file; this is fatal"));
142 exit (1);
145 /* Do we only get statistics? */
146 if (get_stats)
147 /* Does not return. */
148 receive_print_stats ();
150 /* Check if we are already running. */
151 if (check_pid (_PATH_NSCDPID))
152 error (EXIT_FAILURE, 0, _("already running"));
154 /* Remember when we started. */
155 start_time = time (NULL);
157 /* Behave like a daemon. */
158 if (go_background)
160 int i;
162 pid_t pid = fork ();
163 if (pid == -1)
164 error (EXIT_FAILURE, errno, _("cannot fork"));
165 if (pid != 0)
166 exit (0);
168 int nullfd = open (_PATH_DEVNULL, O_RDWR);
169 if (nullfd != -1)
171 struct stat64 st;
173 if (fstat64 (nullfd, &st) == 0 && S_ISCHR (st.st_mode) != 0
174 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
175 && st.st_rdev == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
176 #endif
179 /* It is the /dev/null special device alright. */
180 (void) dup2 (nullfd, STDIN_FILENO);
181 (void) dup2 (nullfd, STDOUT_FILENO);
182 (void) dup2 (nullfd, STDERR_FILENO);
184 if (nullfd > 2)
185 close (nullfd);
187 else
189 /* Ugh, somebody is trying to play a trick on us. */
190 close (nullfd);
191 nullfd = -1;
194 int min_close_fd = nullfd == -1 ? 0 : STDERR_FILENO + 1;
196 DIR *d = opendir ("/proc/self/fd");
197 if (d != NULL)
199 struct dirent64 *dirent;
200 int dfdn = dirfd (d);
202 while ((dirent = readdir64 (d)) != NULL)
204 char *endp;
205 long int fdn = strtol (dirent->d_name, &endp, 10);
207 if (*endp == '\0' && fdn != dfdn && fdn >= min_close_fd)
208 close ((int) fdn);
211 closedir (d);
213 else
214 for (i = min_close_fd; i < getdtablesize (); i++)
215 close (i);
217 pid = fork ();
218 if (pid == -1)
219 error (EXIT_FAILURE, errno, _("cannot fork"));
220 if (pid != 0)
221 exit (0);
223 setsid ();
225 chdir ("/");
227 openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
229 if (write_pid (_PATH_NSCDPID) < 0)
230 dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
232 if (!init_logfile ())
233 dbg_log (_("Could not create log file"));
235 /* Ignore job control signals. */
236 signal (SIGTTOU, SIG_IGN);
237 signal (SIGTTIN, SIG_IGN);
238 signal (SIGTSTP, SIG_IGN);
241 signal (SIGINT, termination_handler);
242 signal (SIGQUIT, termination_handler);
243 signal (SIGTERM, termination_handler);
244 signal (SIGPIPE, SIG_IGN);
246 /* Cleanup files created by a previous 'bind'. */
247 unlink (_PATH_NSCDSOCKET);
249 /* Make sure we do not get recursive calls. */
250 __nss_disable_nscd ();
252 /* Init databases. */
253 nscd_init ();
255 /* Handle incoming requests */
256 start_threads ();
258 return 0;
262 /* Handle program arguments. */
263 static error_t
264 parse_opt (int key, char *arg, struct argp_state *state)
266 switch (key)
268 case 'd':
269 ++debug_level;
270 go_background = 0;
271 break;
273 case 'f':
274 conffile = arg;
275 break;
277 case 'K':
278 if (getuid () != 0)
279 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
281 int sock = nscd_open_socket ();
282 request_header req;
283 ssize_t nbytes;
285 if (sock == -1)
286 exit (EXIT_FAILURE);
288 req.version = NSCD_VERSION;
289 req.type = SHUTDOWN;
290 req.key_len = 0;
291 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
292 sizeof (request_header)));
293 close (sock);
294 exit (nbytes != sizeof (request_header) ? EXIT_FAILURE : EXIT_SUCCESS);
297 case 'g':
298 get_stats = true;
299 break;
301 case 'i':
302 if (getuid () != 0)
303 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
304 else
306 int sock = nscd_open_socket ();
307 request_header req;
308 ssize_t nbytes;
310 if (sock == -1)
311 exit (EXIT_FAILURE);
313 if (strcmp (arg, "passwd") == 0)
314 req.key_len = sizeof "passwd";
315 else if (strcmp (arg, "group") == 0)
316 req.key_len = sizeof "group";
317 else if (strcmp (arg, "hosts") == 0)
318 req.key_len = sizeof "hosts";
319 else
320 return ARGP_ERR_UNKNOWN;
322 req.version = NSCD_VERSION;
323 req.type = INVALIDATE;
324 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
325 sizeof (request_header)));
326 if (nbytes != sizeof (request_header))
328 close (sock);
329 exit (EXIT_FAILURE);
332 nbytes = TEMP_FAILURE_RETRY (write (sock, (void *)arg, req.key_len));
334 close (sock);
336 exit (nbytes != req.key_len ? EXIT_FAILURE : EXIT_SUCCESS);
339 case 't':
340 nthreads = atol (arg);
341 break;
343 case 'S':
344 if (strcmp (arg, "passwd,yes") == 0)
345 secure_in_use = secure[pwddb] = 1;
346 else if (strcmp (arg, "group,yes") == 0)
347 secure_in_use = secure[grpdb] = 1;
348 else if (strcmp (arg, "hosts,yes") == 0)
349 secure_in_use = secure[hstdb] = 1;
350 break;
352 default:
353 return ARGP_ERR_UNKNOWN;
356 return 0;
359 /* Print the version information. */
360 static void
361 print_version (FILE *stream, struct argp_state *state)
363 fprintf (stream, "nscd (GNU %s) %s\n", PACKAGE, VERSION);
364 fprintf (stream, gettext ("\
365 Copyright (C) %s Free Software Foundation, Inc.\n\
366 This is free software; see the source for copying conditions. There is NO\n\
367 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
368 "), "2004");
369 fprintf (stream, gettext ("Written by %s.\n"),
370 "Thorsten Kukuk and Ulrich Drepper");
374 /* Create a socket connected to a name. */
376 nscd_open_socket (void)
378 struct sockaddr_un addr;
379 int sock;
381 sock = socket (PF_UNIX, SOCK_STREAM, 0);
382 if (sock < 0)
383 return -1;
385 addr.sun_family = AF_UNIX;
386 assert (sizeof (addr.sun_path) >= sizeof (_PATH_NSCDSOCKET));
387 strcpy (addr.sun_path, _PATH_NSCDSOCKET);
388 if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0)
390 close (sock);
391 return -1;
394 return sock;
397 /* Cleanup. */
398 void
399 termination_handler (int signum)
401 close_sockets ();
403 /* Clean up the file created by 'bind'. */
404 unlink (_PATH_NSCDSOCKET);
406 /* Clean up pid file. */
407 unlink (_PATH_NSCDPID);
409 _exit (EXIT_SUCCESS);
412 /* Returns 1 if the process in pid file FILE is running, 0 if not. */
413 static int
414 check_pid (const char *file)
416 FILE *fp;
418 fp = fopen (file, "r");
419 if (fp)
421 pid_t pid;
422 int n;
424 n = fscanf (fp, "%d", &pid);
425 fclose (fp);
427 if (n != 1 || kill (pid, 0) == 0)
428 return 1;
431 return 0;
434 /* Write the current process id to the file FILE.
435 Returns 0 if successful, -1 if not. */
436 static int
437 write_pid (const char *file)
439 FILE *fp;
441 fp = fopen (file, "w");
442 if (fp == NULL)
443 return -1;
445 fprintf (fp, "%d\n", getpid ());
446 if (fflush (fp) || ferror (fp))
447 return -1;
449 fclose (fp);
451 return 0;