]> git.ipfire.org Git - thirdparty/glibc.git/blob - nscd/nscd.c
[BZ #18]
[thirdparty/glibc.git] / nscd / nscd.c
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.
4
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.
9
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.
14
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. */
19
20 /* nscd - Name Service Cache Daemon. Caches passwd, group, and hosts. */
21
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>
42
43 #include "dbg_log.h"
44 #include "nscd.h"
45 #include "../nss/nsswitch.h"
46 #include <device-nrs.h>
47
48 /* Get libc version number. */
49 #include <version.h>
50
51 #define PACKAGE _libc_intl_domainname
52
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". */
57
58 typedef struct
59 {
60 int num_active;
61 pthread_cond_t thread_exit_cv;
62 pthread_mutex_t mutex;
63 } thread_info_t;
64
65 thread_info_t thread_info;
66
67 int do_shutdown;
68 int disabled_passwd;
69 int disabled_group;
70 int go_background = 1;
71
72 int secure[lastdb];
73 int secure_in_use;
74 static const char *conffile = _PATH_NSCDCONF;
75
76 time_t start_time;
77
78 static int check_pid (const char *file);
79 static int write_pid (const char *file);
80
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;
84
85 /* Definitions of arguments for argp functions. */
86 static const struct argp_option options[] =
87 {
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 }
99 };
100
101 /* Short description of program. */
102 static const char doc[] = N_("Name Service Cache Daemon.");
103
104 /* Prototype for option handler. */
105 static error_t parse_opt (int key, char *arg, struct argp_state *state);
106
107 /* Data structure to communicate with argp functions. */
108 static struct argp argp =
109 {
110 options, parse_opt, NULL, doc,
111 };
112
113 /* True if only statistics are requested. */
114 static bool get_stats;
115
116 int
117 main (int argc, char **argv)
118 {
119 int remaining;
120
121 /* Set locale via LC_ALL. */
122 setlocale (LC_ALL, "");
123 /* Set the text message domain. */
124 textdomain (PACKAGE);
125
126 /* Parse and process arguments. */
127 argp_parse (&argp, argc, argv, 0, &remaining, NULL);
128
129 if (remaining != argc)
130 {
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);
134 }
135
136 /* Read the configuration file. */
137 if (nscd_parse_file (conffile, dbs) != 0)
138 {
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);
143 }
144
145 /* Do we only get statistics? */
146 if (get_stats)
147 /* Does not return. */
148 receive_print_stats ();
149
150 /* Check if we are already running. */
151 if (check_pid (_PATH_NSCDPID))
152 error (EXIT_FAILURE, 0, _("already running"));
153
154 /* Remember when we started. */
155 start_time = time (NULL);
156
157 /* Behave like a daemon. */
158 if (go_background)
159 {
160 int i;
161
162 if (fork ())
163 exit (0);
164
165 int nullfd = open (_PATH_DEVNULL, O_RDWR);
166 if (nullfd != -1)
167 {
168 struct stat64 st;
169
170 if (fstat64 (nullfd, &st) == 0 && S_ISCHR (st.st_mode) != 0
171 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
172 && st.st_rdev == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
173 #endif
174 )
175 {
176 /* It is the /dev/null special device alright. */
177 (void) dup2 (nullfd, STDIN_FILENO);
178 (void) dup2 (nullfd, STDOUT_FILENO);
179 (void) dup2 (nullfd, STDERR_FILENO);
180
181 if (nullfd > 2)
182 close (nullfd);
183 }
184 else
185 {
186 /* Ugh, somebody is trying to play a trick on us. */
187 close (nullfd);
188 nullfd = -1;
189 }
190 }
191 int min_close_fd = nullfd == -1 ? 0 : STDERR_FILENO + 1;
192
193 DIR *d = opendir ("/proc/self/fd");
194 if (d != NULL)
195 {
196 struct dirent64 *dirent;
197 int dfdn = dirfd (d);
198
199 while ((dirent = readdir64 (d)) != NULL)
200 {
201 char *endp;
202 long int fdn = strtol (dirent->d_name, &endp, 10);
203
204 if (*endp == '\0' && fdn != dfdn && fdn >= min_close_fd)
205 close ((int) fdn);
206 }
207
208 closedir (d);
209 }
210 else
211 for (i = min_close_fd; i < getdtablesize (); i++)
212 close (i);
213
214 if (fork ())
215 exit (0);
216
217 setsid ();
218
219 chdir ("/");
220
221 openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
222
223 if (write_pid (_PATH_NSCDPID) < 0)
224 dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
225
226 if (!init_logfile ())
227 dbg_log (_("Could not create log file"));
228
229 /* Ignore job control signals. */
230 signal (SIGTTOU, SIG_IGN);
231 signal (SIGTTIN, SIG_IGN);
232 signal (SIGTSTP, SIG_IGN);
233 }
234
235 signal (SIGINT, termination_handler);
236 signal (SIGQUIT, termination_handler);
237 signal (SIGTERM, termination_handler);
238 signal (SIGPIPE, SIG_IGN);
239
240 /* Cleanup files created by a previous `bind'. */
241 unlink (_PATH_NSCDSOCKET);
242
243 /* Make sure we do not get recursive calls. */
244 __nss_disable_nscd ();
245
246 /* Init databases. */
247 nscd_init ();
248
249 /* Handle incoming requests */
250 start_threads ();
251
252 return 0;
253 }
254
255
256 /* Handle program arguments. */
257 static error_t
258 parse_opt (int key, char *arg, struct argp_state *state)
259 {
260 switch (key)
261 {
262 case 'd':
263 ++debug_level;
264 go_background = 0;
265 break;
266
267 case 'f':
268 conffile = arg;
269 break;
270
271 case 'K':
272 if (getuid () != 0)
273 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
274 {
275 int sock = nscd_open_socket ();
276 request_header req;
277 ssize_t nbytes;
278
279 if (sock == -1)
280 exit (EXIT_FAILURE);
281
282 req.version = NSCD_VERSION;
283 req.type = SHUTDOWN;
284 req.key_len = 0;
285 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
286 sizeof (request_header)));
287 close (sock);
288 exit (nbytes != sizeof (request_header) ? EXIT_FAILURE : EXIT_SUCCESS);
289 }
290
291 case 'g':
292 get_stats = true;
293 break;
294
295 case 'i':
296 if (getuid () != 0)
297 error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
298 else
299 {
300 int sock = nscd_open_socket ();
301 request_header req;
302 ssize_t nbytes;
303
304 if (sock == -1)
305 exit (EXIT_FAILURE);
306
307 if (strcmp (arg, "passwd") == 0)
308 req.key_len = sizeof "passwd";
309 else if (strcmp (arg, "group") == 0)
310 req.key_len = sizeof "group";
311 else if (strcmp (arg, "hosts") == 0)
312 req.key_len = sizeof "hosts";
313 else
314 return ARGP_ERR_UNKNOWN;
315
316 req.version = NSCD_VERSION;
317 req.type = INVALIDATE;
318 nbytes = TEMP_FAILURE_RETRY (write (sock, &req,
319 sizeof (request_header)));
320 if (nbytes != sizeof (request_header))
321 {
322 close (sock);
323 exit (EXIT_FAILURE);
324 }
325
326 nbytes = TEMP_FAILURE_RETRY (write (sock, (void *)arg, req.key_len));
327
328 close (sock);
329
330 exit (nbytes != req.key_len ? EXIT_FAILURE : EXIT_SUCCESS);
331 }
332
333 case 't':
334 nthreads = atol (arg);
335 break;
336
337 case 'S':
338 if (strcmp (arg, "passwd,yes") == 0)
339 secure_in_use = secure[pwddb] = 1;
340 else if (strcmp (arg, "group,yes") == 0)
341 secure_in_use = secure[grpdb] = 1;
342 else if (strcmp (arg, "hosts,yes") == 0)
343 secure_in_use = secure[hstdb] = 1;
344 break;
345
346 default:
347 return ARGP_ERR_UNKNOWN;
348 }
349
350 return 0;
351 }
352
353 /* Print the version information. */
354 static void
355 print_version (FILE *stream, struct argp_state *state)
356 {
357 fprintf (stream, "nscd (GNU %s) %s\n", PACKAGE, VERSION);
358 fprintf (stream, gettext ("\
359 Copyright (C) %s Free Software Foundation, Inc.\n\
360 This is free software; see the source for copying conditions. There is NO\n\
361 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
362 "), "2004");
363 fprintf (stream, gettext ("Written by %s.\n"),
364 "Thorsten Kukuk and Ulrich Drepper");
365 }
366
367
368 /* Create a socket connected to a name. */
369 int
370 nscd_open_socket (void)
371 {
372 struct sockaddr_un addr;
373 int sock;
374
375 sock = socket (PF_UNIX, SOCK_STREAM, 0);
376 if (sock < 0)
377 return -1;
378
379 addr.sun_family = AF_UNIX;
380 assert (sizeof (addr.sun_path) >= sizeof (_PATH_NSCDSOCKET));
381 strcpy (addr.sun_path, _PATH_NSCDSOCKET);
382 if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0)
383 {
384 close (sock);
385 return -1;
386 }
387
388 return sock;
389 }
390
391 /* Cleanup. */
392 void
393 termination_handler (int signum)
394 {
395 close_sockets ();
396
397 /* Clean up the file created by `bind'. */
398 unlink (_PATH_NSCDSOCKET);
399
400 /* Clean up pid file. */
401 unlink (_PATH_NSCDPID);
402
403 exit (EXIT_SUCCESS);
404 }
405
406 /* Returns 1 if the process in pid file FILE is running, 0 if not. */
407 static int
408 check_pid (const char *file)
409 {
410 FILE *fp;
411
412 fp = fopen (file, "r");
413 if (fp)
414 {
415 pid_t pid;
416 int n;
417
418 n = fscanf (fp, "%d", &pid);
419 fclose (fp);
420
421 if (n != 1 || kill (pid, 0) == 0)
422 return 1;
423 }
424
425 return 0;
426 }
427
428 /* Write the current process id to the file FILE.
429 Returns 0 if successful, -1 if not. */
430 static int
431 write_pid (const char *file)
432 {
433 FILE *fp;
434
435 fp = fopen (file, "w");
436 if (fp == NULL)
437 return -1;
438
439 fprintf (fp, "%d\n", getpid ());
440 if (fflush (fp) || ferror (fp))
441 return -1;
442
443 fclose (fp);
444
445 return 0;
446 }