Update.
[platform/upstream/linaro-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/mman.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/uio.h>
43 #include <sys/un.h>
44
45 #include "dbg_log.h"
46 #include "nscd.h"
47 #include "../nss/nsswitch.h"
48 #include <device-nrs.h>
49
50 /* Get libc version number.  */
51 #include <version.h>
52
53 #define PACKAGE _libc_intl_domainname
54
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".  */
59
60 typedef struct
61 {
62   int             num_active;
63   pthread_cond_t  thread_exit_cv;
64   pthread_mutex_t mutex;
65 } thread_info_t;
66
67 thread_info_t thread_info;
68
69 int do_shutdown;
70 int disabled_passwd;
71 int disabled_group;
72 int go_background = 1;
73
74 int secure_in_use;
75 static const char *conffile = _PATH_NSCDCONF;
76
77 time_t start_time;
78
79 static int check_pid (const char *file);
80 static int write_pid (const char *file);
81
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;
85
86 /* Definitions of arguments for argp functions.  */
87 static const struct argp_option options[] =
88 {
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 }
100 };
101
102 /* Short description of program.  */
103 static const char doc[] = N_("Name Service Cache Daemon.");
104
105 /* Prototype for option handler.  */
106 static error_t parse_opt (int key, char *arg, struct argp_state *state);
107
108 /* Data structure to communicate with argp functions.  */
109 static struct argp argp =
110 {
111   options, parse_opt, NULL, doc,
112 };
113
114 /* True if only statistics are requested.  */
115 static bool get_stats;
116
117 int
118 main (int argc, char **argv)
119 {
120   int remaining;
121
122   /* Set locale via LC_ALL.  */
123   setlocale (LC_ALL, "");
124   /* Set the text message domain.  */
125   textdomain (PACKAGE);
126
127   /* Parse and process arguments.  */
128   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
129
130   if (remaining != argc)
131     {
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);
135     }
136
137   /* Read the configuration file.  */
138   if (nscd_parse_file (conffile, dbs) != 0)
139     {
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);
144     }
145
146   /* Do we only get statistics?  */
147   if (get_stats)
148     /* Does not return.  */
149     receive_print_stats ();
150
151   /* Check if we are already running. */
152   if (check_pid (_PATH_NSCDPID))
153     error (EXIT_FAILURE, 0, _("already running"));
154
155   /* Remember when we started.  */
156   start_time = time (NULL);
157
158   /* Behave like a daemon.  */
159   if (go_background)
160     {
161       int i;
162
163       pid_t pid = fork ();
164       if (pid == -1)
165         error (EXIT_FAILURE, errno, _("cannot fork"));
166       if (pid != 0)
167         exit (0);
168
169       int nullfd = open (_PATH_DEVNULL, O_RDWR);
170       if (nullfd != -1)
171         {
172           struct stat64 st;
173
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
178               )
179             {
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);
184
185               if (nullfd > 2)
186                 close (nullfd);
187             }
188           else
189             {
190               /* Ugh, somebody is trying to play a trick on us.  */
191               close (nullfd);
192               nullfd = -1;
193             }
194         }
195       int min_close_fd = nullfd == -1 ? 0 : STDERR_FILENO + 1;
196
197       DIR *d = opendir ("/proc/self/fd");
198       if (d != NULL)
199         {
200           struct dirent64 *dirent;
201           int dfdn = dirfd (d);
202
203           while ((dirent = readdir64 (d)) != NULL)
204             {
205               char *endp;
206               long int fdn = strtol (dirent->d_name, &endp, 10);
207
208               if (*endp == '\0' && fdn != dfdn && fdn >= min_close_fd)
209                 close ((int) fdn);
210             }
211
212           closedir (d);
213         }
214       else
215         for (i = min_close_fd; i < getdtablesize (); i++)
216           close (i);
217
218       pid = fork ();
219       if (pid == -1)
220         error (EXIT_FAILURE, errno, _("cannot fork"));
221       if (pid != 0)
222         exit (0);
223
224       setsid ();
225
226       chdir ("/");
227
228       openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
229
230       if (write_pid (_PATH_NSCDPID) < 0)
231         dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
232
233       if (!init_logfile ())
234         dbg_log (_("Could not create log file"));
235
236       /* Ignore job control signals.  */
237       signal (SIGTTOU, SIG_IGN);
238       signal (SIGTTIN, SIG_IGN);
239       signal (SIGTSTP, SIG_IGN);
240     }
241
242   signal (SIGINT, termination_handler);
243   signal (SIGQUIT, termination_handler);
244   signal (SIGTERM, termination_handler);
245   signal (SIGPIPE, SIG_IGN);
246
247   /* Cleanup files created by a previous 'bind'.  */
248   unlink (_PATH_NSCDSOCKET);
249
250   /* Make sure we do not get recursive calls.  */
251   __nss_disable_nscd ();
252
253   /* Init databases.  */
254   nscd_init ();
255
256   /* Handle incoming requests */
257   start_threads ();
258
259   return 0;
260 }
261
262
263 /* Handle program arguments.  */
264 static error_t
265 parse_opt (int key, char *arg, struct argp_state *state)
266 {
267   switch (key)
268     {
269     case 'd':
270       ++debug_level;
271       go_background = 0;
272       break;
273
274     case 'f':
275       conffile = arg;
276       break;
277
278     case 'K':
279       if (getuid () != 0)
280         error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
281       {
282         int sock = nscd_open_socket ();
283         request_header req;
284         ssize_t nbytes;
285
286         if (sock == -1)
287           exit (EXIT_FAILURE);
288
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);
296       }
297
298     case 'g':
299       get_stats = true;
300       break;
301
302     case 'i':
303       if (getuid () != 0)
304         error (EXIT_FAILURE, 0, _("Only root is allowed to use this option!"));
305       else
306         {
307           int sock = nscd_open_socket ();
308
309           if (sock == -1)
310             exit (EXIT_FAILURE);
311
312           request_header req;
313           ssize_t nbytes;
314           struct iovec iov[2];
315
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;
324
325           req.version = NSCD_VERSION;
326           req.type = INVALIDATE;
327
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;
332
333           nbytes = TEMP_FAILURE_RETRY (writev (sock, iov, 2));
334
335           close (sock);
336
337           exit (nbytes != iov[0].iov_len + iov[1].iov_len
338                 ? EXIT_FAILURE : EXIT_SUCCESS);
339         }
340
341     case 't':
342       nthreads = atol (arg);
343       break;
344
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;
353
354     default:
355       return ARGP_ERR_UNKNOWN;
356     }
357
358   return 0;
359 }
360
361 /* Print the version information.  */
362 static void
363 print_version (FILE *stream, struct argp_state *state)
364 {
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");
373 }
374
375
376 /* Create a socket connected to a name.  */
377 int
378 nscd_open_socket (void)
379 {
380   struct sockaddr_un addr;
381   int sock;
382
383   sock = socket (PF_UNIX, SOCK_STREAM, 0);
384   if (sock < 0)
385     return -1;
386
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)
391     {
392       close (sock);
393       return -1;
394     }
395
396   return sock;
397 }
398
399 /* Cleanup.  */
400 void
401 termination_handler (int signum)
402 {
403   close_sockets ();
404
405   /* Clean up the file created by 'bind'.  */
406   unlink (_PATH_NSCDSOCKET);
407
408   /* Clean up pid file.  */
409   unlink (_PATH_NSCDPID);
410
411   // XXX Terminate threads.
412
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);
418
419   _exit (EXIT_SUCCESS);
420 }
421
422 /* Returns 1 if the process in pid file FILE is running, 0 if not.  */
423 static int
424 check_pid (const char *file)
425 {
426   FILE *fp;
427
428   fp = fopen (file, "r");
429   if (fp)
430     {
431       pid_t pid;
432       int n;
433
434       n = fscanf (fp, "%d", &pid);
435       fclose (fp);
436
437       if (n != 1 || kill (pid, 0) == 0)
438         return 1;
439     }
440
441   return 0;
442 }
443
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)
448 {
449   FILE *fp;
450
451   fp = fopen (file, "w");
452   if (fp == NULL)
453     return -1;
454
455   fprintf (fp, "%d\n", getpid ());
456   if (fflush (fp) || ferror (fp))
457     return -1;
458
459   fclose (fp);
460
461   return 0;
462 }