nscd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. /* Copyright (c) 1998-2026 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published
  5. by the Free Software Foundation; version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  13. /* nscd - Name Service Cache Daemon. Caches passwd, group, and hosts. */
  14. #include <argp.h>
  15. #include <assert.h>
  16. #include <dirent.h>
  17. #include <errno.h>
  18. #include <error.h>
  19. #include <fcntl.h>
  20. #include <libintl.h>
  21. #include <locale.h>
  22. #include <paths.h>
  23. #include <pthread.h>
  24. #include <signal.h>
  25. #include <stdbool.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <syslog.h>
  30. #include <unistd.h>
  31. #include <sys/mman.h>
  32. #include <sys/socket.h>
  33. #include <sys/stat.h>
  34. #include <sys/uio.h>
  35. #include <sys/un.h>
  36. #include <sys/wait.h>
  37. #include <stdarg.h>
  38. #include "dbg_log.h"
  39. #include "nscd.h"
  40. #include "selinux.h"
  41. #include "../nss/nsswitch.h"
  42. #include <device-nrs.h>
  43. #ifdef HAVE_INOTIFY
  44. # include <sys/inotify.h>
  45. #endif
  46. #include <kernel-features.h>
  47. /* Get libc version number. */
  48. #include <version.h>
  49. #define PACKAGE _libc_intl_domainname
  50. int do_shutdown;
  51. int disabled_passwd;
  52. int disabled_group;
  53. typedef enum
  54. {
  55. /* Running in background as daemon. */
  56. RUN_DAEMONIZE,
  57. /* Running in foreground but otherwise behave like a daemon,
  58. i.e., detach from terminal and use syslog. This allows
  59. better integration with services like systemd. */
  60. RUN_FOREGROUND,
  61. /* Run in foreground in debug mode. */
  62. RUN_DEBUG
  63. } run_modes;
  64. static run_modes run_mode = RUN_DAEMONIZE;
  65. static const char *conffile = _PATH_NSCDCONF;
  66. static const char *print_cache = NULL;
  67. time_t start_time;
  68. uintptr_t pagesize_m1;
  69. int paranoia;
  70. time_t restart_time;
  71. time_t restart_interval = RESTART_INTERVAL;
  72. const char *oldcwd;
  73. uid_t old_uid;
  74. gid_t old_gid;
  75. static int check_pid (const char *file);
  76. static int write_pid (const char *file);
  77. static int monitor_child (int fd);
  78. /* Name and version of program. */
  79. static void print_version (FILE *stream, struct argp_state *state);
  80. void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
  81. /* Function to print some extra text in the help message. */
  82. static char *more_help (int key, const char *text, void *input);
  83. /* Definitions of arguments for argp functions. */
  84. static const struct argp_option options[] =
  85. {
  86. { "config-file", 'f', N_("NAME"), 0,
  87. N_("Read configuration data from NAME") },
  88. { "debug", 'd', NULL, 0,
  89. N_("Do not fork and display messages on the current tty") },
  90. { "print", 'p', N_("NAME"), 0,
  91. N_("Print contents of the offline cache file NAME") },
  92. { "foreground", 'F', NULL, 0,
  93. N_("Do not fork, but otherwise behave like a daemon") },
  94. { "nthreads", 't', N_("NUMBER"), 0, N_("Start NUMBER threads") },
  95. { "shutdown", 'K', NULL, 0, N_("Shut the server down") },
  96. { "statistics", 'g', NULL, 0, N_("Print current configuration statistics") },
  97. { "invalidate", 'i', N_("TABLE"), 0,
  98. N_("Invalidate the specified cache") },
  99. { "secure", 'S', N_("TABLE,yes"), OPTION_HIDDEN,
  100. N_("Use separate cache for each user")},
  101. { NULL, 0, NULL, 0, NULL }
  102. };
  103. /* Short description of program. */
  104. 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);
  107. /* Data structure to communicate with argp functions. */
  108. static struct argp argp =
  109. {
  110. options, parse_opt, NULL, doc, NULL, more_help
  111. };
  112. /* True if only statistics are requested. */
  113. static bool get_stats;
  114. static int parent_fd = -1;
  115. int
  116. main (int argc, char **argv)
  117. {
  118. int remaining;
  119. /* Set locale via LC_ALL. */
  120. setlocale (LC_ALL, "");
  121. /* Set the text message domain. */
  122. textdomain (PACKAGE);
  123. /* Determine if the kernel has SELinux support. */
  124. nscd_selinux_enabled (&selinux_enabled);
  125. /* Parse and process arguments. */
  126. argp_parse (&argp, argc, argv, 0, &remaining, NULL);
  127. if (remaining != argc)
  128. {
  129. error (0, 0, gettext ("wrong number of arguments"));
  130. argp_help (&argp, stdout, ARGP_HELP_SEE, program_invocation_short_name);
  131. exit (1);
  132. }
  133. /* Print the contents of the indicated cache file. */
  134. if (print_cache != NULL)
  135. /* Does not return. */
  136. nscd_print_cache (print_cache);
  137. /* Read the configuration file. */
  138. if (nscd_parse_file (conffile, dbs) != 0)
  139. /* We couldn't read the configuration file. We don't start the
  140. server. */
  141. error (EXIT_FAILURE, 0,
  142. _("failure while reading configuration file; this is fatal"));
  143. /* Do we only get statistics? */
  144. if (get_stats)
  145. /* Does not return. */
  146. receive_print_stats ();
  147. /* Check if we are already running. */
  148. if (check_pid (_PATH_NSCDPID))
  149. error (EXIT_FAILURE, 0, _("already running"));
  150. /* Remember when we started. */
  151. start_time = time (NULL);
  152. /* Determine page size. */
  153. pagesize_m1 = getpagesize () - 1;
  154. if (run_mode == RUN_DAEMONIZE || run_mode == RUN_FOREGROUND)
  155. {
  156. int i;
  157. pid_t pid;
  158. /* Behave like a daemon. */
  159. if (run_mode == RUN_DAEMONIZE)
  160. {
  161. int fd[2];
  162. if (pipe (fd) != 0)
  163. error (EXIT_FAILURE, errno,
  164. _("cannot create a pipe to talk to the child"));
  165. pid = fork ();
  166. if (pid == -1)
  167. error (EXIT_FAILURE, errno, _("cannot fork"));
  168. if (pid != 0)
  169. {
  170. /* The parent only reads from the child. */
  171. close (fd[1]);
  172. exit (monitor_child (fd[0]));
  173. }
  174. else
  175. {
  176. /* The child only writes to the parent. */
  177. close (fd[0]);
  178. parent_fd = fd[1];
  179. }
  180. }
  181. int nullfd = open (_PATH_DEVNULL, O_RDWR);
  182. if (nullfd != -1)
  183. {
  184. struct stat64 st;
  185. if (fstat64 (nullfd, &st) == 0 && S_ISCHR (st.st_mode) != 0
  186. #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
  187. && st.st_rdev == makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
  188. #endif
  189. )
  190. {
  191. /* It is the /dev/null special device alright. */
  192. (void) dup2 (nullfd, STDIN_FILENO);
  193. (void) dup2 (nullfd, STDOUT_FILENO);
  194. (void) dup2 (nullfd, STDERR_FILENO);
  195. if (nullfd > 2)
  196. close (nullfd);
  197. }
  198. else
  199. {
  200. /* Ugh, somebody is trying to play a trick on us. */
  201. close (nullfd);
  202. nullfd = -1;
  203. }
  204. }
  205. int min_close_fd = nullfd == -1 ? 0 : STDERR_FILENO + 1;
  206. DIR *d = opendir ("/proc/self/fd");
  207. if (d != NULL)
  208. {
  209. struct dirent64 *dirent;
  210. int dfdn = dirfd (d);
  211. while ((dirent = readdir64 (d)) != NULL)
  212. {
  213. char *endp;
  214. long int fdn = strtol (dirent->d_name, &endp, 10);
  215. if (*endp == '\0' && fdn != dfdn && fdn >= min_close_fd
  216. && fdn != parent_fd)
  217. close ((int) fdn);
  218. }
  219. closedir (d);
  220. }
  221. else
  222. for (i = min_close_fd; i < getdtablesize (); i++)
  223. if (i != parent_fd)
  224. close (i);
  225. setsid ();
  226. if (chdir ("/") != 0)
  227. do_exit (EXIT_FAILURE, errno,
  228. _("cannot change current working directory to \"/\""));
  229. openlog ("nscd", LOG_CONS | LOG_ODELAY, LOG_DAEMON);
  230. if (write_pid (_PATH_NSCDPID) < 0)
  231. dbg_log ("%s: %s", _PATH_NSCDPID, strerror (errno));
  232. if (!init_logfile ())
  233. dbg_log (_("Could not create log file"));
  234. /* Ignore job control signals. */
  235. signal (SIGTTOU, SIG_IGN);
  236. signal (SIGTTIN, SIG_IGN);
  237. signal (SIGTSTP, SIG_IGN);
  238. }
  239. else
  240. /* In debug mode we are not paranoid. */
  241. paranoia = 0;
  242. signal (SIGINT, termination_handler);
  243. signal (SIGQUIT, termination_handler);
  244. signal (SIGTERM, termination_handler);
  245. signal (SIGPIPE, SIG_IGN);
  246. /* Cleanup files created by a previous 'bind'. */
  247. unlink (_PATH_NSCDSOCKET);
  248. #ifdef HAVE_INOTIFY
  249. /* Use inotify to recognize changed files. */
  250. inotify_fd = inotify_init1 (IN_NONBLOCK);
  251. # ifndef __ASSUME_IN_NONBLOCK
  252. if (inotify_fd == -1 && errno == ENOSYS)
  253. {
  254. inotify_fd = inotify_init ();
  255. if (inotify_fd != -1)
  256. fcntl (inotify_fd, F_SETFL, O_RDONLY | O_NONBLOCK);
  257. }
  258. # endif
  259. #endif
  260. #ifdef USE_NSCD
  261. /* Make sure we do not get recursive calls. */
  262. __nss_disable_nscd (register_traced_file);
  263. #endif
  264. /* Init databases. */
  265. nscd_init ();
  266. /* Start the SELinux AVC. */
  267. if (selinux_enabled)
  268. nscd_avc_init ();
  269. /* Handle incoming requests */
  270. start_threads ();
  271. return 0;
  272. }
  273. static void __attribute__ ((noreturn))
  274. invalidate_db (const char *dbname)
  275. {
  276. int sock = nscd_open_socket ();
  277. if (sock == -1)
  278. exit (EXIT_FAILURE);
  279. size_t dbname_len = strlen (dbname) + 1;
  280. size_t reqlen = sizeof (request_header) + dbname_len;
  281. struct
  282. {
  283. request_header req;
  284. char dbname[];
  285. } *reqdata = alloca (reqlen);
  286. reqdata->req.key_len = dbname_len;
  287. reqdata->req.version = NSCD_VERSION;
  288. reqdata->req.type = INVALIDATE;
  289. memcpy (reqdata->dbname, dbname, dbname_len);
  290. ssize_t nbytes = TEMP_FAILURE_RETRY (send (sock, reqdata, reqlen,
  291. MSG_NOSIGNAL));
  292. if (nbytes != reqlen)
  293. {
  294. int err = errno;
  295. close (sock);
  296. error (EXIT_FAILURE, err, _("write incomplete"));
  297. }
  298. /* Wait for ack. Older nscd just closed the socket when
  299. prune_cache finished, silently ignore that. */
  300. int32_t resp = 0;
  301. nbytes = TEMP_FAILURE_RETRY (read (sock, &resp, sizeof (resp)));
  302. if (nbytes != 0 && nbytes != sizeof (resp))
  303. {
  304. int err = errno;
  305. close (sock);
  306. error (EXIT_FAILURE, err, _("cannot read invalidate ACK"));
  307. }
  308. close (sock);
  309. if (resp != 0)
  310. error (EXIT_FAILURE, resp, _("invalidation failed"));
  311. exit (0);
  312. }
  313. static void __attribute__ ((noreturn))
  314. send_shutdown (void)
  315. {
  316. int sock = nscd_open_socket ();
  317. if (sock == -1)
  318. exit (EXIT_FAILURE);
  319. request_header req;
  320. req.version = NSCD_VERSION;
  321. req.type = SHUTDOWN;
  322. req.key_len = 0;
  323. ssize_t nbytes = TEMP_FAILURE_RETRY (send (sock, &req, sizeof req,
  324. MSG_NOSIGNAL));
  325. close (sock);
  326. exit (nbytes != sizeof (request_header) ? EXIT_FAILURE : EXIT_SUCCESS);
  327. }
  328. /* Handle program arguments. */
  329. static error_t
  330. parse_opt (int key, char *arg, struct argp_state *state)
  331. {
  332. switch (key)
  333. {
  334. case 'd':
  335. ++debug_level;
  336. run_mode = RUN_DEBUG;
  337. break;
  338. case 'p':
  339. print_cache = arg;
  340. break;
  341. case 'F':
  342. run_mode = RUN_FOREGROUND;
  343. break;
  344. case 'f':
  345. conffile = arg;
  346. break;
  347. case 'K':
  348. if (getuid () != 0)
  349. error (4, 0, _("Only root is allowed to use this option!"));
  350. else
  351. send_shutdown ();
  352. break;
  353. case 'g':
  354. get_stats = true;
  355. break;
  356. case 'i':
  357. {
  358. /* Validate the database name. */
  359. dbtype cnt;
  360. for (cnt = pwddb; cnt < lastdb; ++cnt)
  361. if (strcmp (arg, dbnames[cnt]) == 0)
  362. break;
  363. if (cnt == lastdb)
  364. {
  365. argp_error (state, _("'%s' is not a known database"), arg);
  366. return EINVAL;
  367. }
  368. }
  369. if (getuid () != 0)
  370. error (4, 0, _("Only root is allowed to use this option!"));
  371. else
  372. invalidate_db (arg);
  373. break;
  374. case 't':
  375. nthreads = atol (arg);
  376. break;
  377. case 'S':
  378. error (0, 0, _("secure services not implemented anymore"));
  379. break;
  380. default:
  381. return ARGP_ERR_UNKNOWN;
  382. }
  383. return 0;
  384. }
  385. /* Print bug-reporting information in the help message. */
  386. static char *
  387. more_help (int key, const char *text, void *input)
  388. {
  389. switch (key)
  390. {
  391. case ARGP_KEY_HELP_EXTRA:
  392. {
  393. /* We print some extra information. */
  394. char *tables = xstrdup (dbnames[0]);
  395. for (dbtype i = 1; i < lastdb; ++i)
  396. {
  397. char *more_tables;
  398. if (asprintf (&more_tables, "%s %s", tables, dbnames[i]) < 0)
  399. more_tables = NULL;
  400. free (tables);
  401. if (more_tables == NULL)
  402. return NULL;
  403. tables = more_tables;
  404. }
  405. char *tp;
  406. if (asprintf (&tp, gettext ("\
  407. Supported tables:\n\
  408. %s\n\
  409. \n\
  410. For bug reporting instructions, please see:\n\
  411. %s.\n\
  412. "), tables, REPORT_BUGS_TO) < 0)
  413. tp = NULL;
  414. free (tables);
  415. return tp;
  416. }
  417. default:
  418. break;
  419. }
  420. return (char *) text;
  421. }
  422. /* Print the version information. */
  423. static void
  424. print_version (FILE *stream, struct argp_state *state)
  425. {
  426. fprintf (stream, "nscd %s%s\n", PKGVERSION, VERSION);
  427. fprintf (stream, gettext ("\
  428. Copyright (C) %s Free Software Foundation, Inc.\n\
  429. This is free software; see the source for copying conditions. There is NO\n\
  430. warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
  431. "), "2024");
  432. fprintf (stream, gettext ("Written by %s.\n"),
  433. "Thorsten Kukuk and Ulrich Drepper");
  434. }
  435. /* Create a socket connected to a name. */
  436. int
  437. nscd_open_socket (void)
  438. {
  439. struct sockaddr_un addr;
  440. int sock;
  441. sock = socket (PF_UNIX, SOCK_STREAM, 0);
  442. if (sock < 0)
  443. return -1;
  444. addr.sun_family = AF_UNIX;
  445. assert (sizeof (addr.sun_path) >= sizeof (_PATH_NSCDSOCKET));
  446. strcpy (addr.sun_path, _PATH_NSCDSOCKET);
  447. if (connect (sock, (struct sockaddr *) &addr, sizeof (addr)) < 0)
  448. {
  449. close (sock);
  450. return -1;
  451. }
  452. return sock;
  453. }
  454. /* Cleanup. */
  455. void
  456. termination_handler (int signum)
  457. {
  458. close_sockets ();
  459. /* Clean up the file created by 'bind'. */
  460. unlink (_PATH_NSCDSOCKET);
  461. /* Clean up pid file. */
  462. unlink (_PATH_NSCDPID);
  463. // XXX Terminate threads.
  464. /* Synchronize memory. */
  465. for (int cnt = 0; cnt < lastdb; ++cnt)
  466. {
  467. if (!dbs[cnt].enabled || dbs[cnt].head == NULL)
  468. continue;
  469. /* Make sure nobody keeps using the database. */
  470. dbs[cnt].head->timestamp = 0;
  471. if (dbs[cnt].persistent)
  472. // XXX async OK?
  473. msync (dbs[cnt].head, dbs[cnt].memsize, MS_ASYNC);
  474. }
  475. _exit (EXIT_SUCCESS);
  476. }
  477. /* Returns 1 if the process in pid file FILE is running, 0 if not. */
  478. static int
  479. check_pid (const char *file)
  480. {
  481. FILE *fp;
  482. fp = fopen (file, "r");
  483. if (fp)
  484. {
  485. pid_t pid;
  486. int n;
  487. n = fscanf (fp, "%d", &pid);
  488. fclose (fp);
  489. /* If we cannot parse the file default to assuming nscd runs.
  490. If the PID is alive, assume it is running. That all unless
  491. the PID is the same as the current process' since the latter
  492. can mean we re-exec. */
  493. if ((n != 1 || kill (pid, 0) == 0) && pid != getpid ())
  494. return 1;
  495. }
  496. return 0;
  497. }
  498. /* Write the current process id to the file FILE.
  499. Returns 0 if successful, -1 if not. */
  500. static int
  501. write_pid (const char *file)
  502. {
  503. FILE *fp;
  504. fp = fopen (file, "w");
  505. if (fp == NULL)
  506. return -1;
  507. fprintf (fp, "%d\n", getpid ());
  508. int result = fflush (fp) || ferror (fp) ? -1 : 0;
  509. fclose (fp);
  510. return result;
  511. }
  512. static int
  513. monitor_child (int fd)
  514. {
  515. int child_ret = 0;
  516. int ret = read (fd, &child_ret, sizeof (child_ret));
  517. /* The child terminated with an error, either via exit or some other abnormal
  518. method, like a segfault. */
  519. if (ret <= 0 || child_ret != 0)
  520. {
  521. int status;
  522. int err = wait (&status);
  523. if (err < 0)
  524. {
  525. fprintf (stderr, _("'wait' failed\n"));
  526. return 1;
  527. }
  528. if (WIFEXITED (status))
  529. {
  530. child_ret = WEXITSTATUS (status);
  531. fprintf (stderr, _("child exited with status %d\n"), child_ret);
  532. }
  533. if (WIFSIGNALED (status))
  534. {
  535. child_ret = WTERMSIG (status);
  536. fprintf (stderr, _("child terminated by signal %d\n"), child_ret);
  537. }
  538. }
  539. /* We have the child status, so exit with that code. */
  540. close (fd);
  541. return child_ret;
  542. }
  543. void
  544. do_exit (int child_ret, int errnum, const char *format, ...)
  545. {
  546. if (parent_fd != -1)
  547. {
  548. int ret __attribute__ ((unused));
  549. ret = write (parent_fd, &child_ret, sizeof (child_ret));
  550. assert (ret == sizeof (child_ret));
  551. close (parent_fd);
  552. }
  553. if (format != NULL)
  554. {
  555. /* Emulate error() since we don't have a va_list variant for it. */
  556. va_list argp;
  557. fflush (stdout);
  558. fprintf (stderr, "%s: ", program_invocation_name);
  559. va_start (argp, format);
  560. vfprintf (stderr, format, argp);
  561. va_end (argp);
  562. fprintf (stderr, ": %s\n", strerror (errnum));
  563. fflush (stderr);
  564. }
  565. /* Finally, exit. */
  566. exit (child_ret);
  567. }
  568. void
  569. notify_parent (int child_ret)
  570. {
  571. if (parent_fd == -1)
  572. return;
  573. int ret __attribute__ ((unused));
  574. ret = write (parent_fd, &child_ret, sizeof (child_ret));
  575. assert (ret == sizeof (child_ret));
  576. close (parent_fd);
  577. parent_fd = -1;
  578. }