cache.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. #include <assert.h>
  14. #include <atomic.h>
  15. #include <errno.h>
  16. #include <error.h>
  17. #include <inttypes.h>
  18. #include <limits.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <libintl.h>
  22. #include <arpa/inet.h>
  23. #include <sys/mman.h>
  24. #include <sys/param.h>
  25. #include <sys/stat.h>
  26. #include <sys/uio.h>
  27. #include <nss.h>
  28. #include "nscd.h"
  29. #include "dbg_log.h"
  30. /* Wrapper functions with error checking for standard functions. */
  31. extern void *xcalloc (size_t n, size_t s);
  32. /* Number of times a value is reloaded without being used. UINT_MAX
  33. means unlimited. */
  34. unsigned int reload_count = DEFAULT_RELOAD_LIMIT;
  35. static time_t (*const readdfcts[LASTREQ]) (struct database_dyn *,
  36. struct hashentry *,
  37. struct datahead *) =
  38. {
  39. [GETPWBYNAME] = readdpwbyname,
  40. [GETPWBYUID] = readdpwbyuid,
  41. [GETGRBYNAME] = readdgrbyname,
  42. [GETGRBYGID] = readdgrbygid,
  43. [GETHOSTBYNAME] = readdhstbyname,
  44. [GETHOSTBYNAMEv6] = readdhstbynamev6,
  45. [GETHOSTBYADDR] = readdhstbyaddr,
  46. [GETHOSTBYADDRv6] = readdhstbyaddrv6,
  47. [GETAI] = readdhstai,
  48. [INITGROUPS] = readdinitgroups,
  49. [GETSERVBYNAME] = readdservbyname,
  50. [GETSERVBYPORT] = readdservbyport,
  51. [GETNETGRENT] = readdgetnetgrent,
  52. [INNETGR] = readdinnetgr
  53. };
  54. /* Search the cache for a matching entry and return it when found. If
  55. this fails search the negative cache and return (void *) -1 if this
  56. search was successful. Otherwise return NULL.
  57. This function must be called with the read-lock held. */
  58. struct datahead *
  59. cache_search (request_type type, const void *key, size_t len,
  60. struct database_dyn *table, uid_t owner)
  61. {
  62. unsigned long int hash = __nss_hash (key, len) % table->head->module;
  63. unsigned long int nsearched = 0;
  64. struct datahead *result = NULL;
  65. ref_t work = table->head->array[hash];
  66. while (work != ENDREF)
  67. {
  68. ++nsearched;
  69. struct hashentry *here = (struct hashentry *) (table->data + work);
  70. if (type == here->type && len == here->len
  71. && memcmp (key, table->data + here->key, len) == 0
  72. && here->owner == owner)
  73. {
  74. /* We found the entry. Increment the appropriate counter. */
  75. struct datahead *dh
  76. = (struct datahead *) (table->data + here->packet);
  77. /* See whether we must ignore the entry. */
  78. if (dh->usable)
  79. {
  80. /* We do not synchronize the memory here. The statistics
  81. data is not crucial, we synchronize only once in a while
  82. in the cleanup threads. */
  83. if (dh->notfound)
  84. ++table->head->neghit;
  85. else
  86. {
  87. ++table->head->poshit;
  88. if (dh->nreloads != 0)
  89. dh->nreloads = 0;
  90. }
  91. result = dh;
  92. break;
  93. }
  94. }
  95. work = here->next;
  96. }
  97. if (nsearched > table->head->maxnsearched)
  98. table->head->maxnsearched = nsearched;
  99. return result;
  100. }
  101. /* Add a new entry to the cache. The return value is zero if the function
  102. call was successful.
  103. This function must be called with the read-lock held.
  104. We modify the table but we nevertheless only acquire a read-lock.
  105. This is ok since we use operations which would be safe even without
  106. locking, given that the `prune_cache' function never runs. Using
  107. the readlock reduces the chance of conflicts. */
  108. int
  109. cache_add (int type, const void *key, size_t len, struct datahead *packet,
  110. bool first, struct database_dyn *table,
  111. uid_t owner, bool prune_wakeup)
  112. {
  113. if (__glibc_unlikely (debug_level >= 2))
  114. {
  115. const char *str;
  116. char buf[INET6_ADDRSTRLEN + 1];
  117. if (type == GETHOSTBYADDR || type == GETHOSTBYADDRv6)
  118. str = inet_ntop (type == GETHOSTBYADDR ? AF_INET : AF_INET6,
  119. key, buf, sizeof (buf));
  120. else
  121. str = key;
  122. dbg_log (_("add new entry \"%s\" of type %s for %s to cache%s"),
  123. str, serv2str[type], dbnames[table - dbs],
  124. first ? _(" (first)") : "");
  125. }
  126. unsigned long int hash = __nss_hash (key, len) % table->head->module;
  127. struct hashentry *newp;
  128. newp = mempool_alloc (table, sizeof (struct hashentry), 0);
  129. /* If we cannot allocate memory, just do not do anything. */
  130. if (newp == NULL)
  131. {
  132. /* If necessary mark the entry as unusable so that lookups will
  133. not use it. */
  134. if (first)
  135. packet->usable = false;
  136. return -1;
  137. }
  138. newp->type = type;
  139. newp->first = first;
  140. newp->len = len;
  141. newp->key = (char *) key - table->data;
  142. assert (newp->key + newp->len <= table->head->first_free);
  143. newp->owner = owner;
  144. newp->packet = (char *) packet - table->data;
  145. assert ((newp->packet & BLOCK_ALIGN_M1) == 0);
  146. /* Put the new entry in the first position. */
  147. /* TODO Review concurrency. Use atomic_exchange_release. */
  148. newp->next = atomic_load_relaxed (&table->head->array[hash]);
  149. while (!atomic_compare_exchange_weak_release (&table->head->array[hash],
  150. (ref_t *) &newp->next,
  151. (ref_t) ((char *) newp
  152. - table->data)));
  153. /* Update the statistics. */
  154. if (packet->notfound)
  155. ++table->head->negmiss;
  156. else if (first)
  157. ++table->head->posmiss;
  158. /* We depend on this value being correct and at least as high as the
  159. real number of entries. */
  160. atomic_fetch_add_relaxed (&table->head->nentries, 1);
  161. /* It does not matter that we are not loading the just increment
  162. value, this is just for statistics. */
  163. unsigned long int nentries = table->head->nentries;
  164. if (nentries > table->head->maxnentries)
  165. table->head->maxnentries = nentries;
  166. if (table->persistent)
  167. // XXX async OK?
  168. msync ((void *) table->head,
  169. (char *) &table->head->array[hash] - (char *) table->head
  170. + sizeof (ref_t), MS_ASYNC);
  171. /* We do not have to worry about the pruning thread if we are
  172. re-adding the data since this is done by the pruning thread. We
  173. also do not have to do anything in case this is not the first
  174. time the data is entered since different data heads all have the
  175. same timeout. */
  176. if (first && prune_wakeup)
  177. {
  178. /* Perhaps the prune thread for the table is not running in a long
  179. time. Wake it if necessary. */
  180. pthread_mutex_lock (&table->prune_lock);
  181. time_t next_wakeup = table->wakeup_time;
  182. bool do_wakeup = false;
  183. if (next_wakeup > packet->timeout + CACHE_PRUNE_INTERVAL)
  184. {
  185. table->wakeup_time = packet->timeout;
  186. do_wakeup = true;
  187. }
  188. pthread_mutex_unlock (&table->prune_lock);
  189. if (do_wakeup)
  190. pthread_cond_signal (&table->prune_cond);
  191. }
  192. return 0;
  193. }
  194. /* Walk through the table and remove all entries which lifetime ended.
  195. We have a problem here. To actually remove the entries we must get
  196. the write-lock. But since we want to keep the time we have the
  197. lock as short as possible we cannot simply acquire the lock when we
  198. start looking for timedout entries.
  199. Therefore we do it in two stages: first we look for entries which
  200. must be invalidated and remember them. Then we get the lock and
  201. actually remove them. This is complicated by the way we have to
  202. free the data structures since some hash table entries share the same
  203. data. */
  204. time_t
  205. prune_cache (struct database_dyn *table, time_t now, int fd)
  206. {
  207. size_t cnt = table->head->module;
  208. /* If this table is not actually used don't do anything. */
  209. if (cnt == 0)
  210. {
  211. if (fd != -1)
  212. {
  213. /* Reply to the INVALIDATE initiator. */
  214. int32_t resp = 0;
  215. writeall (fd, &resp, sizeof (resp));
  216. }
  217. /* No need to do this again anytime soon. */
  218. return 24 * 60 * 60;
  219. }
  220. /* If we check for the modification of the underlying file we invalidate
  221. the entries also in this case. */
  222. if (table->check_file && now != LONG_MAX)
  223. {
  224. struct traced_file *runp = table->traced_files;
  225. while (runp != NULL)
  226. {
  227. #ifdef HAVE_INOTIFY
  228. if (runp->inotify_descr[TRACED_FILE] == -1)
  229. #endif
  230. {
  231. struct stat64 st;
  232. if (stat64 (runp->fname, &st) < 0)
  233. {
  234. /* Print a diagnostic that the traced file was missing.
  235. We must not disable tracing since the file might return
  236. shortly and we want to reload it at the next pruning.
  237. Disabling tracing here would go against the configuration
  238. as specified by the user via check-files. */
  239. char buf[128];
  240. dbg_log (_("checking for monitored file `%s': %s"),
  241. runp->fname, strerror_r (errno, buf, sizeof (buf)));
  242. }
  243. else
  244. {
  245. /* This must be `!=` to catch cases where users turn the
  246. clocks back and we still want to detect any time difference
  247. in mtime. */
  248. if (st.st_mtime != runp->mtime)
  249. {
  250. dbg_log (_("monitored file `%s` changed (mtime)"),
  251. runp->fname);
  252. /* The file changed. Invalidate all entries. */
  253. now = LONG_MAX;
  254. runp->mtime = st.st_mtime;
  255. #ifdef HAVE_INOTIFY
  256. /* Attempt to install a watch on the file. */
  257. install_watches (runp);
  258. #endif
  259. }
  260. }
  261. }
  262. runp = runp->next;
  263. }
  264. }
  265. /* We run through the table and find values which are not valid anymore.
  266. Note that for the initial step, finding the entries to be removed,
  267. we don't need to get any lock. It is at all timed assured that the
  268. linked lists are set up correctly and that no second thread prunes
  269. the cache. */
  270. bool *mark;
  271. size_t memory_needed = cnt * sizeof (bool);
  272. bool mark_use_alloca;
  273. if (__glibc_likely (memory_needed <= MAX_STACK_USE))
  274. {
  275. mark = alloca (cnt * sizeof (bool));
  276. memset (mark, '\0', memory_needed);
  277. mark_use_alloca = true;
  278. }
  279. else
  280. {
  281. mark = xcalloc (1, memory_needed);
  282. mark_use_alloca = false;
  283. }
  284. size_t first = cnt + 1;
  285. size_t last = 0;
  286. char *const data = table->data;
  287. bool any = false;
  288. if (__glibc_unlikely (debug_level > 2))
  289. dbg_log (_("pruning %s cache; time %ld"),
  290. dbnames[table - dbs], (long int) now);
  291. #define NO_TIMEOUT LONG_MAX
  292. time_t next_timeout = NO_TIMEOUT;
  293. do
  294. {
  295. ref_t run = table->head->array[--cnt];
  296. while (run != ENDREF)
  297. {
  298. struct hashentry *runp = (struct hashentry *) (data + run);
  299. struct datahead *dh = (struct datahead *) (data + runp->packet);
  300. /* Some debug support. */
  301. if (__glibc_unlikely (debug_level > 2))
  302. {
  303. char buf[INET6_ADDRSTRLEN];
  304. const char *str;
  305. if (runp->type == GETHOSTBYADDR || runp->type == GETHOSTBYADDRv6)
  306. {
  307. inet_ntop (runp->type == GETHOSTBYADDR ? AF_INET : AF_INET6,
  308. data + runp->key, buf, sizeof (buf));
  309. str = buf;
  310. }
  311. else
  312. str = data + runp->key;
  313. dbg_log (_("considering %s entry \"%s\", timeout %" PRIu64),
  314. serv2str[runp->type], str, dh->timeout);
  315. }
  316. /* Check whether the entry timed out. Timed out entries
  317. will be revalidated. For unusable records, it is still
  318. necessary to record that the bucket needs to be scanned
  319. again below. */
  320. if (dh->timeout < now || !dh->usable)
  321. {
  322. /* This hash bucket could contain entries which need to
  323. be looked at. */
  324. mark[cnt] = true;
  325. first = MIN (first, cnt);
  326. last = MAX (last, cnt);
  327. /* We only have to look at the data of the first entries
  328. since the count information is kept in the data part
  329. which is shared. */
  330. if (runp->first && dh->usable)
  331. {
  332. /* At this point there are two choices: we reload the
  333. value or we discard it. Do not change NRELOADS if
  334. we never not reload the record. */
  335. if ((reload_count != UINT_MAX
  336. && __builtin_expect (dh->nreloads >= reload_count, 0))
  337. /* We always remove negative entries. */
  338. || dh->notfound
  339. /* Discard everything if the user explicitly
  340. requests it. */
  341. || now == LONG_MAX)
  342. {
  343. /* Remove the value. */
  344. dh->usable = false;
  345. }
  346. else
  347. {
  348. /* Reload the value. We do this only for the
  349. initially used key, not the additionally
  350. added derived value. */
  351. assert (runp->type < LASTREQ
  352. && readdfcts[runp->type] != NULL);
  353. time_t timeout = readdfcts[runp->type] (table, runp, dh);
  354. next_timeout = MIN (next_timeout, timeout);
  355. }
  356. }
  357. /* If the entry has been replaced, we might need cleanup. */
  358. any |= !dh->usable;
  359. }
  360. else
  361. /* Entry has not timed out and is usable. */
  362. next_timeout = MIN (next_timeout, dh->timeout);
  363. run = runp->next;
  364. }
  365. }
  366. while (cnt > 0);
  367. if (__glibc_unlikely (fd != -1))
  368. {
  369. /* Reply to the INVALIDATE initiator that the cache has been
  370. invalidated. */
  371. int32_t resp = 0;
  372. writeall (fd, &resp, sizeof (resp));
  373. }
  374. if (first <= last)
  375. {
  376. struct hashentry *head = NULL;
  377. /* Now we have to get the write lock since we are about to modify
  378. the table. */
  379. if (__glibc_unlikely (pthread_rwlock_trywrlock (&table->lock) != 0))
  380. {
  381. ++table->head->wrlockdelayed;
  382. pthread_rwlock_wrlock (&table->lock);
  383. }
  384. /* Now we start modifying the data. Make sure all readers of the
  385. data are aware of this and temporarily don't use the data. */
  386. atomic_fetch_add_relaxed (&table->head->gc_cycle, 1);
  387. assert ((table->head->gc_cycle & 1) == 1);
  388. while (first <= last)
  389. {
  390. if (mark[first])
  391. {
  392. ref_t *old = &table->head->array[first];
  393. ref_t run = table->head->array[first];
  394. assert (run != ENDREF);
  395. do
  396. {
  397. struct hashentry *runp = (struct hashentry *) (data + run);
  398. struct datahead *dh
  399. = (struct datahead *) (data + runp->packet);
  400. if (! dh->usable)
  401. {
  402. /* We need the list only for debugging but it is
  403. more costly to avoid creating the list than
  404. doing it. */
  405. runp->dellist = head;
  406. head = runp;
  407. /* No need for an atomic operation, we have the
  408. write lock. */
  409. --table->head->nentries;
  410. run = *old = runp->next;
  411. }
  412. else
  413. {
  414. old = &runp->next;
  415. run = runp->next;
  416. }
  417. }
  418. while (run != ENDREF);
  419. }
  420. ++first;
  421. }
  422. /* Now we are done modifying the data. */
  423. atomic_fetch_add_relaxed (&table->head->gc_cycle, 1);
  424. assert ((table->head->gc_cycle & 1) == 0);
  425. /* It's all done. */
  426. pthread_rwlock_unlock (&table->lock);
  427. /* Make sure the data is saved to disk. */
  428. if (table->persistent)
  429. msync (table->head,
  430. data + table->head->first_free - (char *) table->head,
  431. MS_ASYNC);
  432. /* One extra pass if we do debugging. */
  433. if (__glibc_unlikely (debug_level > 0))
  434. {
  435. struct hashentry *runp = head;
  436. while (runp != NULL)
  437. {
  438. char buf[INET6_ADDRSTRLEN];
  439. const char *str;
  440. if (runp->type == GETHOSTBYADDR || runp->type == GETHOSTBYADDRv6)
  441. {
  442. inet_ntop (runp->type == GETHOSTBYADDR ? AF_INET : AF_INET6,
  443. data + runp->key, buf, sizeof (buf));
  444. str = buf;
  445. }
  446. else
  447. str = data + runp->key;
  448. dbg_log ("remove %s entry \"%s\"", serv2str[runp->type], str);
  449. runp = runp->dellist;
  450. }
  451. }
  452. }
  453. if (__glibc_unlikely (! mark_use_alloca))
  454. free (mark);
  455. /* Run garbage collection if any entry has been removed or replaced. */
  456. if (any)
  457. gc (table);
  458. /* If there is no entry in the database and we therefore have no new
  459. timeout value, tell the caller to wake up in 24 hours. */
  460. return next_timeout == NO_TIMEOUT ? 24 * 60 * 60 : next_timeout - now;
  461. }