Update.
[glibc.git] / nscd / nscd.c
bloba67da746d6a83eedee12e79c39eea2b01a680ad8
1 /* Copyright (c) 1998, 1999, 2000, 2001 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 Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If not,
17 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 /* nscd - Name Service Cache Daemon. Caches passwd, group, and hosts. */
22 #include <argp.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <error.h>
26 #include <grp.h>
27 #include <libintl.h>
28 #include <locale.h>
29 #include <pthread.h>
30 #include <pwd.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
36 #include <unistd.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
40 #include "dbg_log.h"
41 #include "nscd.h"
43 /* Get libc version number. */
44 #include <version.h>
46 #define PACKAGE _libc_intl_domainname
48 /* Structure used by main() thread to keep track of the number of
49 active threads. Used to limit how many threads it will create
50 and under a shutdown condition to wait till all in-progress
51 requests have finished before "turning off the lights". */
53 typedef struct
55 int num_active;
56 pthread_cond_t thread_exit_cv;
57 pthread_mutex_t mutex;
58 } thread_info_t;
60 thread_info_t thread_info;
62 int do_shutdown;
63 int disabled_passwd;
64 int disabled_group;
65 int go_background = 1;
66 const char *server_user;
68 int secure[lastdb];
69 int secure_in_use;
70 static const char *conffile = _PATH_NSCDCONF;
72 static int check_pid (const char *file);
73 static int write_pid (const char *file);
74 static void drop_privileges (void);
76 /* Name and version of program. */
77 static void print_version (FILE *stream, struct argp_state *state);
78 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
80 /* Definitions of arguments for argp functions. */
81 static const struct argp_option options[] =
83 { "config-file", 'f', N_("NAME"), 0,
84 N_("Read configuration data from NAME") },
85 { "debug", 'd', NULL, 0,
86 N_("Do not fork and display messages on the current tty") },
87 { "nthreads", 't', N_("NUMBER"), 0, N_("Start NUMBER threads") },
88 { "shutdown", 'K', NULL, 0, N_("Shut the server down") },
89 { "statistic", 'g', NULL, 0, N_("Print current configuration statistic") },
90 { "invalidate", 'i', N_("TABLE"), 0,
91 N_("Invalidate the specified cache") },
92 { "secure", 'S', N_("TABLE,yes"), 0, N_("Use separate cache for each user")},
93 { NULL, 0, NULL, 0, NULL }
96 /* Short description of program. */
97 static const char doc[] = N_("Name Service Cache Daemon.");
99 /* Prototype for option handler. */
100 static error_t parse_opt (int key, char *arg, struct argp_state *state);
102 /* Data structure to communicate with argp functions. */
103 static struct argp argp =
105 options, parse_opt, NULL, doc,
109 main (int argc, char **argv)
111 int remaining;
113 /* Set locale via LC_ALL. */
114 setlocale (LC_ALL, "");
115 /* Set the text message domain. */
116 textdomain (PACKAGE);
118 /* Parse and process arguments. */
119 argp_parse (&argp, argc, argv, 0, &remaining, NULL);
121 if (remaining != argc)
123 error (0, 0, gettext ("wrong number of arguments"));
124 argp_help (&argp, stdout, ARGP_HELP_SEE, program_invocation_short_name);
125 exit (EXIT_FAILURE);
128 /* Check if we are already running. */
129 if (check_pid (_PATH_NSCDPID))
130 error (EXIT_FAILURE, 0, _("already running"));
132 /* Behave like a daemon. */
133 if (go_background)
135 int i;
137 if (fork ())
138 exit (0);
140 for (i = 0; i < getdtablesize (); i++)
141 close (i);
143 if (fork ())
144 exit (0);
146 setsid ();
148 chdir ("/");
150 openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
152 if (write_pid (_PATH_NSCDPID) < 0)
153 dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
155 /* Ignore job control signals. */
156 signal (SIGTTOU, SIG_IGN);
157 signal (SIGTTIN, SIG_IGN);
158 signal (SIGTSTP, SIG_IGN);
161 signal (SIGINT, termination_handler);
162 signal (SIGQUIT, termination_handler);
163 signal (SIGTERM, termination_handler);
164 signal (SIGPIPE, SIG_IGN);
166 /* Cleanup files created by a previous `bind'. */
167 unlink (_PATH_NSCDSOCKET);
169 /* Init databases. */
170 nscd_init (conffile);
172 /* Change to unprivileged UID if specifed in config file */
173 if(server_user && !secure_in_use)
174 drop_privileges ();
176 /* Handle incoming requests */
177 start_threads ();
179 return 0;
183 /* Handle program arguments. */
184 static error_t
185 parse_opt (int key, char *arg, struct argp_state *state)
187 switch (key)
189 case 'd':
190 ++debug_level;
191 go_background = 0;
192 break;
194 case 'f':
195 conffile = arg;
196 break;
198 case 'K':
199 if (getuid () != 0)
200 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
202 int sock = nscd_open_socket ();
203 request_header req;
204 ssize_t nbytes;
206 if (sock == -1)
207 exit (EXIT_FAILURE);
209 req.version = NSCD_VERSION;
210 req.type = SHUTDOWN;
211 req.key_len = 0;
212 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
213 sizeof (request_header)));
214 close (sock);
215 exit (nbytes != sizeof (request_header) ? EXIT_FAILURE : EXIT_SUCCESS);
218 case 'g':
219 if (getuid () != 0)
220 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
221 receive_print_stats ();
222 /* Does not return. */
224 case 'i':
225 if (getuid () != 0)
226 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
227 else
229 int sock = nscd_open_socket ();
230 request_header req;
231 ssize_t nbytes;
233 if (sock == -1)
234 exit (EXIT_FAILURE);
236 if (strcmp (arg, "passwd") == 0)
237 req.key_len = sizeof "passwd";
238 else if (strcmp (arg, "group") == 0)
239 req.key_len = sizeof "group";
240 else if (strcmp (arg, "hosts") == 0)
241 req.key_len = sizeof "hosts";
242 else
243 return ARGP_ERR_UNKNOWN;
245 req.version = NSCD_VERSION;
246 req.type = INVALIDATE;
247 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
248 sizeof (request_header)));
249 if (nbytes != sizeof (request_header))
251 close (sock);
252 exit (EXIT_FAILURE);
255 nbytes = TEMP_FAILURE_RETRY (write (sock, (void *)arg, req.key_len));
257 close (sock);
259 exit (nbytes != req.key_len ? EXIT_FAILURE : EXIT_SUCCESS);
262 case 't':
263 nthreads = atol (arg);
264 break;
266 case 'S':
267 if (strcmp (arg, "passwd,yes") == 0)
268 secure_in_use = secure[pwddb] = 1;
269 else if (strcmp (arg, "group,yes") == 0)
270 secure_in_use = secure[grpdb] = 1;
271 else if (strcmp (arg, "hosts,yes") == 0)
272 secure_in_use = secure[hstdb] = 1;
273 break;
275 default:
276 return ARGP_ERR_UNKNOWN;
279 return 0;
282 /* Print the version information. */
283 static void
284 print_version (FILE *stream, struct argp_state *state)
286 fprintf (stream, "nscd (GNU %s) %s\n", PACKAGE, VERSION);
287 fprintf (stream, gettext ("\
288 Copyright (C) %s Free Software Foundation, Inc.\n\
289 This is free software; see the source for copying conditions. There is NO\n\
290 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
291 "), "2001");
292 fprintf (stream, gettext ("Written by %s.\n"),
293 "Thorsten Kukuk and Ulrich Drepper");
297 /* Create a socket connected to a name. */
299 nscd_open_socket (void)
301 struct sockaddr_un addr;
302 int sock;
304 sock = socket (PF_UNIX, SOCK_STREAM, 0);
305 if (sock < 0)
306 return -1;
308 addr.sun_family = AF_UNIX;
309 assert (sizeof (addr.sun_path) >= sizeof (_PATH_NSCDSOCKET));
310 strcpy (addr.sun_path, _PATH_NSCDSOCKET);
311 if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0)
313 close (sock);
314 return -1;
317 return sock;
320 /* Cleanup. */
321 void
322 termination_handler (int signum)
324 close_sockets ();
326 /* Clean up the file created by `bind'. */
327 unlink (_PATH_NSCDSOCKET);
329 /* Clean up pid file. */
330 unlink (_PATH_NSCDPID);
332 exit (EXIT_SUCCESS);
335 /* Returns 1 if the process in pid file FILE is running, 0 if not. */
336 static int
337 check_pid (const char *file)
339 FILE *fp;
341 fp = fopen (file, "r");
342 if (fp)
344 pid_t pid;
345 int n;
347 n = fscanf (fp, "%d", &pid);
348 fclose (fp);
350 if (n != 1 || kill (pid, 0) == 0)
351 return 1;
354 return 0;
357 /* Write the current process id to the file FILE.
358 Returns 0 if successful, -1 if not. */
359 static int
360 write_pid (const char *file)
362 FILE *fp;
364 fp = fopen (file, "w");
365 if (fp == NULL)
366 return -1;
368 fprintf (fp, "%d\n", getpid ());
369 if (fflush (fp) || ferror (fp))
370 return -1;
372 fclose (fp);
374 return 0;
377 /* Look up the uid and gid associated with the user we are supposed to run
378 the server as, and then call setgid(), setgroups(), and setuid().
379 Otherwise, abort- we should not run as root if the configuration file
380 specifically tells us not to. */
382 static void
383 drop_privileges (void)
385 int buflen = 256;
386 char *buffer = alloca (buflen);
387 struct passwd resultbuf;
388 struct passwd *pwd;
390 while (__getpwnam_r (server_user, &resultbuf, buffer, buflen, &pwd) != 0
391 && errno == ERANGE)
393 errno = 0;
394 buflen += 256;
395 buffer = alloca (buflen);
398 if(!pwd)
400 dbg_log (_("Failed to look up user '%s' to run server as"),
401 server_user);
402 exit(1);
405 setgroups (0, NULL);
406 setgid (pwd->pw_gid);
407 setuid (pwd->pw_uid);