netgroupcache.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. /* Cache handling for netgroup lookup.
  2. Copyright (C) 2011-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published
  6. by the Free Software Foundation; version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  14. #include <alloca.h>
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <libintl.h>
  18. #include <stdbool.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. #include <sys/mman.h>
  22. #include <scratch_buffer.h>
  23. #include "../nss/netgroup.h"
  24. #include "nscd.h"
  25. #include "dbg_log.h"
  26. #include <kernel-features.h>
  27. /* This is the standard reply in case the service is disabled. */
  28. static const netgroup_response_header disabled =
  29. {
  30. .version = NSCD_VERSION,
  31. .found = -1,
  32. .nresults = 0,
  33. .result_len = 0
  34. };
  35. /* This is the struct describing how to write this record. */
  36. const struct iovec netgroup_iov_disabled =
  37. {
  38. .iov_base = (void *) &disabled,
  39. .iov_len = sizeof (disabled)
  40. };
  41. /* This is the standard reply in case we haven't found the dataset. */
  42. static const netgroup_response_header notfound =
  43. {
  44. .version = NSCD_VERSION,
  45. .found = 0,
  46. .nresults = 0,
  47. .result_len = 0
  48. };
  49. struct dataset
  50. {
  51. struct datahead head;
  52. netgroup_response_header resp;
  53. char strdata[0];
  54. };
  55. /* Send a notfound response to FD. Always returns -1 to indicate an
  56. ephemeral error. */
  57. static time_t
  58. send_notfound (int fd)
  59. {
  60. if (fd != -1)
  61. TEMP_FAILURE_RETRY (send (fd, &notfound, sizeof (notfound), MSG_NOSIGNAL));
  62. return -1;
  63. }
  64. /* Sends a notfound message and prepares a notfound dataset to write to the
  65. cache. Returns true if there was enough memory to allocate the dataset and
  66. returns the dataset in DATASETP, total bytes to write in TOTALP and the
  67. timeout in TIMEOUTP. KEY_COPY is set to point to the copy of the key in the
  68. dataset. */
  69. static bool
  70. do_notfound (struct database_dyn *db, int fd, request_header *req,
  71. const char *key, struct dataset **datasetp, ssize_t *totalp,
  72. time_t *timeoutp, char **key_copy)
  73. {
  74. struct dataset *dataset;
  75. ssize_t total;
  76. time_t timeout;
  77. bool cacheable = false;
  78. total = sizeof (notfound);
  79. timeout = time (NULL) + db->negtimeout;
  80. send_notfound (fd);
  81. dataset = mempool_alloc (db, sizeof (struct dataset) + req->key_len, 1);
  82. /* If we cannot permanently store the result, so be it. */
  83. if (dataset != NULL)
  84. {
  85. timeout = datahead_init_neg (&dataset->head,
  86. sizeof (struct dataset) + req->key_len,
  87. total, db->negtimeout);
  88. /* This is the reply. */
  89. memcpy (&dataset->resp, &notfound, total);
  90. /* Copy the key data. */
  91. memcpy (dataset->strdata, key, req->key_len);
  92. *key_copy = dataset->strdata;
  93. cacheable = true;
  94. }
  95. *timeoutp = timeout;
  96. *totalp = total;
  97. *datasetp = dataset;
  98. return cacheable;
  99. }
  100. struct addgetnetgrentX_scratch
  101. {
  102. /* This is the result that the caller should use. It can be NULL,
  103. point into buffer, or it can be in the cache. */
  104. struct dataset *dataset;
  105. struct scratch_buffer buffer;
  106. /* Used internally in addgetnetgrentX as a staging area. */
  107. struct scratch_buffer tmp;
  108. /* Number of bytes in buffer that are actually used. */
  109. size_t buffer_used;
  110. };
  111. static void
  112. addgetnetgrentX_scratch_init (struct addgetnetgrentX_scratch *scratch)
  113. {
  114. scratch->dataset = NULL;
  115. scratch_buffer_init (&scratch->buffer);
  116. scratch_buffer_init (&scratch->tmp);
  117. /* Reserve space for the header. */
  118. scratch->buffer_used = sizeof (struct dataset);
  119. static_assert (sizeof (struct dataset) < sizeof (scratch->tmp.__space),
  120. "initial buffer space");
  121. memset (scratch->tmp.data, 0, sizeof (struct dataset));
  122. }
  123. static void
  124. addgetnetgrentX_scratch_free (struct addgetnetgrentX_scratch *scratch)
  125. {
  126. scratch_buffer_free (&scratch->buffer);
  127. scratch_buffer_free (&scratch->tmp);
  128. }
  129. /* Copy LENGTH bytes from S into SCRATCH. Returns NULL if SCRATCH
  130. could not be resized, otherwise a pointer to the copy. */
  131. static char *
  132. addgetnetgrentX_append_n (struct addgetnetgrentX_scratch *scratch,
  133. const char *s, size_t length)
  134. {
  135. while (true)
  136. {
  137. size_t remaining = scratch->buffer.length - scratch->buffer_used;
  138. if (remaining >= length)
  139. break;
  140. if (!scratch_buffer_grow_preserve (&scratch->buffer))
  141. return NULL;
  142. }
  143. char *copy = scratch->buffer.data + scratch->buffer_used;
  144. memcpy (copy, s, length);
  145. scratch->buffer_used += length;
  146. return copy;
  147. }
  148. /* Copy S into SCRATCH, including its null terminator. Returns false
  149. if SCRATCH could not be resized. */
  150. static bool
  151. addgetnetgrentX_append (struct addgetnetgrentX_scratch *scratch, const char *s)
  152. {
  153. if (s == NULL)
  154. s = "";
  155. return addgetnetgrentX_append_n (scratch, s, strlen (s) + 1) != NULL;
  156. }
  157. /* Caller must initialize and free *SCRATCH. If the return value is
  158. negative, this function has sent a notfound response. */
  159. static time_t
  160. addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
  161. const char *key, uid_t uid, struct hashentry *he,
  162. struct datahead *dh, struct addgetnetgrentX_scratch *scratch)
  163. {
  164. if (__glibc_unlikely (debug_level > 0))
  165. {
  166. if (he == NULL)
  167. dbg_log (_("Haven't found \"%s\" in netgroup cache!"), key);
  168. else
  169. dbg_log (_("Reloading \"%s\" in netgroup cache!"), key);
  170. }
  171. static nss_action_list netgroup_database;
  172. time_t timeout;
  173. struct dataset *dataset;
  174. bool cacheable = false;
  175. ssize_t total;
  176. bool found = false;
  177. char *key_copy = NULL;
  178. struct __netgrent data;
  179. size_t nentries = 0;
  180. size_t group_len = strlen (key) + 1;
  181. struct name_list *first_needed
  182. = alloca (sizeof (struct name_list) + group_len);
  183. if (netgroup_database == NULL
  184. && !__nss_database_get (nss_database_netgroup, &netgroup_database))
  185. {
  186. /* No such service. */
  187. cacheable = do_notfound (db, fd, req, key, &dataset, &total, &timeout,
  188. &key_copy);
  189. goto maybe_cache_add;
  190. }
  191. memset (&data, '\0', sizeof (data));
  192. first_needed->next = first_needed;
  193. memcpy (first_needed->name, key, group_len);
  194. data.needed_groups = first_needed;
  195. while (data.needed_groups != NULL)
  196. {
  197. /* Add the next group to the list of those which are known. */
  198. struct name_list *this_group = data.needed_groups->next;
  199. if (this_group == data.needed_groups)
  200. data.needed_groups = NULL;
  201. else
  202. data.needed_groups->next = this_group->next;
  203. this_group->next = data.known_groups;
  204. data.known_groups = this_group;
  205. union
  206. {
  207. enum nss_status (*f) (const char *, struct __netgrent *);
  208. void *ptr;
  209. } setfct;
  210. nss_action_list nip = netgroup_database;
  211. int no_more = __nss_lookup (&nip, "setnetgrent", NULL, &setfct.ptr);
  212. while (!no_more)
  213. {
  214. enum nss_status status
  215. = DL_CALL_FCT (*setfct.f, (data.known_groups->name, &data));
  216. if (status == NSS_STATUS_SUCCESS)
  217. {
  218. found = true;
  219. union
  220. {
  221. enum nss_status (*f) (struct __netgrent *, char *, size_t,
  222. int *);
  223. void *ptr;
  224. } getfct;
  225. getfct.ptr = __nss_lookup_function (nip, "getnetgrent_r");
  226. if (getfct.f != NULL)
  227. while (1)
  228. {
  229. int e;
  230. status = getfct.f (&data, scratch->tmp.data,
  231. scratch->tmp.length, &e);
  232. if (status == NSS_STATUS_SUCCESS)
  233. {
  234. if (data.type == triple_val)
  235. {
  236. const char *nhost = data.val.triple.host;
  237. const char *nuser = data.val.triple.user;
  238. const char *ndomain = data.val.triple.domain;
  239. if (!(addgetnetgrentX_append (scratch, nhost)
  240. && addgetnetgrentX_append (scratch, nuser)
  241. && addgetnetgrentX_append (scratch, ndomain)))
  242. return send_notfound (fd);
  243. ++nentries;
  244. }
  245. else
  246. {
  247. /* Check that the group has not been
  248. requested before. */
  249. struct name_list *runp = data.needed_groups;
  250. if (runp != NULL)
  251. while (1)
  252. {
  253. if (strcmp (runp->name, data.val.group) == 0)
  254. break;
  255. runp = runp->next;
  256. if (runp == data.needed_groups)
  257. {
  258. runp = NULL;
  259. break;
  260. }
  261. }
  262. if (runp == NULL)
  263. {
  264. runp = data.known_groups;
  265. while (runp != NULL)
  266. if (strcmp (runp->name, data.val.group) == 0)
  267. break;
  268. else
  269. runp = runp->next;
  270. }
  271. if (runp == NULL)
  272. {
  273. /* A new group is requested. */
  274. size_t namelen = strlen (data.val.group) + 1;
  275. struct name_list *newg = alloca (sizeof (*newg)
  276. + namelen);
  277. memcpy (newg->name, data.val.group, namelen);
  278. if (data.needed_groups == NULL)
  279. data.needed_groups = newg->next = newg;
  280. else
  281. {
  282. newg->next = data.needed_groups->next;
  283. data.needed_groups->next = newg;
  284. data.needed_groups = newg;
  285. }
  286. }
  287. }
  288. }
  289. else if (status == NSS_STATUS_TRYAGAIN && e == ERANGE)
  290. {
  291. if (!scratch_buffer_grow (&scratch->tmp))
  292. return send_notfound (fd);
  293. }
  294. else if (status == NSS_STATUS_RETURN
  295. || status == NSS_STATUS_NOTFOUND
  296. || status == NSS_STATUS_UNAVAIL)
  297. /* This was either the last one for this group or the
  298. group was empty or the NSS module had an internal
  299. failure. Look at next group if available. */
  300. break;
  301. }
  302. enum nss_status (*endfct) (struct __netgrent *);
  303. endfct = __nss_lookup_function (nip, "endnetgrent");
  304. if (endfct != NULL)
  305. (void) DL_CALL_FCT (*endfct, (&data));
  306. break;
  307. }
  308. no_more = __nss_next2 (&nip, "setnetgrent", NULL, &setfct.ptr,
  309. status, 0);
  310. }
  311. }
  312. /* No results. Return a failure and write out a notfound record in the
  313. cache. */
  314. if (!found)
  315. {
  316. cacheable = do_notfound (db, fd, req, key, &dataset, &total, &timeout,
  317. &key_copy);
  318. goto maybe_cache_add;
  319. }
  320. /* Capture the result size without the key appended. */
  321. total = scratch->buffer_used;
  322. /* Make a copy of the key. The scratch buffer must not move after
  323. this point. */
  324. key_copy = addgetnetgrentX_append_n (scratch, key, req->key_len);
  325. if (key_copy == NULL)
  326. return send_notfound (fd);
  327. /* Fill in the dataset. */
  328. dataset = scratch->buffer.data;
  329. timeout = datahead_init_pos (&dataset->head, total + req->key_len,
  330. total - offsetof (struct dataset, resp),
  331. he == NULL ? 0 : dh->nreloads + 1,
  332. db->postimeout);
  333. dataset->resp.version = NSCD_VERSION;
  334. dataset->resp.found = 1;
  335. dataset->resp.nresults = nentries;
  336. dataset->resp.result_len = total - sizeof (*dataset);
  337. /* Now we can determine whether on refill we have to create a new
  338. record or not. */
  339. if (he != NULL)
  340. {
  341. assert (fd == -1);
  342. if (dataset->head.allocsize == dh->allocsize
  343. && dataset->head.recsize == dh->recsize
  344. && memcmp (&dataset->resp, dh->data,
  345. dh->allocsize - offsetof (struct dataset, resp)) == 0)
  346. {
  347. /* The data has not changed. We will just bump the timeout
  348. value. Note that the new record has been allocated on
  349. the stack and need not be freed. */
  350. dh->timeout = dataset->head.timeout;
  351. dh->ttl = dataset->head.ttl;
  352. ++dh->nreloads;
  353. dataset = (struct dataset *) dh;
  354. goto out;
  355. }
  356. }
  357. {
  358. struct dataset *newp
  359. = (struct dataset *) mempool_alloc (db, total + req->key_len, 1);
  360. if (__glibc_likely (newp != NULL))
  361. {
  362. /* Adjust pointer into the memory block. */
  363. key_copy = (char *) newp + (key_copy - (char *) dataset);
  364. dataset = memcpy (newp, dataset, total + req->key_len);
  365. cacheable = true;
  366. if (he != NULL)
  367. /* Mark the old record as obsolete. */
  368. dh->usable = false;
  369. }
  370. }
  371. if (he == NULL && fd != -1)
  372. /* We write the dataset before inserting it to the database since
  373. while inserting this thread might block and so would
  374. unnecessarily let the receiver wait. */
  375. writeall (fd, &dataset->resp, dataset->head.recsize);
  376. maybe_cache_add:
  377. if (cacheable)
  378. {
  379. /* If necessary, we also propagate the data to disk. */
  380. if (db->persistent)
  381. {
  382. // XXX async OK?
  383. uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
  384. msync ((void *) pval,
  385. ((uintptr_t) dataset & pagesize_m1) + total + req->key_len,
  386. MS_ASYNC);
  387. }
  388. (void) cache_add (req->type, key_copy, req->key_len, &dataset->head,
  389. true, db, uid, he == NULL);
  390. pthread_rwlock_unlock (&db->lock);
  391. /* Mark the old entry as obsolete. */
  392. if (dh != NULL)
  393. dh->usable = false;
  394. }
  395. out:
  396. scratch->dataset = dataset;
  397. return timeout;
  398. }
  399. static time_t
  400. addinnetgrX (struct database_dyn *db, int fd, request_header *req,
  401. char *key, uid_t uid, struct hashentry *he,
  402. struct datahead *dh)
  403. {
  404. const char *group = key;
  405. key = strchr (key, '\0') + 1;
  406. size_t group_len = key - group;
  407. const char *host = *key++ ? key : NULL;
  408. if (host != NULL)
  409. key = strchr (key, '\0') + 1;
  410. const char *user = *key++ ? key : NULL;
  411. if (user != NULL)
  412. key = strchr (key, '\0') + 1;
  413. const char *domain = *key++ ? key : NULL;
  414. struct addgetnetgrentX_scratch scratch;
  415. addgetnetgrentX_scratch_init (&scratch);
  416. if (__glibc_unlikely (debug_level > 0))
  417. {
  418. if (he == NULL)
  419. dbg_log (_("Haven't found \"%s (%s,%s,%s)\" in netgroup cache!"),
  420. group, host ?: "", user ?: "", domain ?: "");
  421. else
  422. dbg_log (_("Reloading \"%s (%s,%s,%s)\" in netgroup cache!"),
  423. group, host ?: "", user ?: "", domain ?: "");
  424. }
  425. struct dataset *result = (struct dataset *) cache_search (GETNETGRENT,
  426. group, group_len,
  427. db, uid);
  428. time_t timeout;
  429. if (result != NULL)
  430. timeout = result->head.timeout;
  431. else
  432. {
  433. request_header req_get =
  434. {
  435. .type = GETNETGRENT,
  436. .key_len = group_len
  437. };
  438. timeout = addgetnetgrentX (db, -1, &req_get, group, uid, NULL, NULL,
  439. &scratch);
  440. result = scratch.dataset;
  441. if (timeout < 0)
  442. goto out;
  443. }
  444. struct indataset
  445. {
  446. struct datahead head;
  447. innetgroup_response_header resp;
  448. } *dataset
  449. = (struct indataset *) mempool_alloc (db,
  450. sizeof (*dataset) + req->key_len,
  451. 1);
  452. bool cacheable = true;
  453. if (__glibc_unlikely (dataset == NULL))
  454. {
  455. cacheable = false;
  456. /* The alloca is safe because nscd_run_worker verifies that
  457. key_len is not larger than MAXKEYLEN. */
  458. dataset = alloca (sizeof (*dataset) + req->key_len);
  459. }
  460. datahead_init_pos (&dataset->head, sizeof (*dataset) + req->key_len,
  461. sizeof (innetgroup_response_header),
  462. he == NULL ? 0 : dh->nreloads + 1,
  463. result == NULL ? db->negtimeout : result->head.ttl);
  464. /* Set the notfound status and timeout based on the result from
  465. getnetgrent. */
  466. dataset->head.notfound = result == NULL || result->head.notfound;
  467. dataset->head.timeout = timeout;
  468. dataset->resp.version = NSCD_VERSION;
  469. dataset->resp.found = result != NULL && result->resp.found;
  470. /* Until we find a matching entry the result is 0. */
  471. dataset->resp.result = 0;
  472. char *key_copy = memcpy ((char *) (dataset + 1), group, req->key_len);
  473. if (dataset->resp.found)
  474. {
  475. const char *triplets = (const char *) (&result->resp + 1);
  476. for (nscd_ssize_t i = result->resp.nresults; i > 0; --i)
  477. {
  478. bool success = true;
  479. /* For the host, user and domain in each triplet, we assume success
  480. if the value is blank because that is how the wildcard entry to
  481. match anything is stored in the netgroup cache. */
  482. if (host != NULL && *triplets != '\0')
  483. success = strcmp (host, triplets) == 0;
  484. triplets = strchr (triplets, '\0') + 1;
  485. if (success && user != NULL && *triplets != '\0')
  486. success = strcmp (user, triplets) == 0;
  487. triplets = strchr (triplets, '\0') + 1;
  488. if (success && (domain == NULL || *triplets == '\0'
  489. || strcmp (domain, triplets) == 0))
  490. {
  491. dataset->resp.result = 1;
  492. break;
  493. }
  494. triplets = strchr (triplets, '\0') + 1;
  495. }
  496. }
  497. if (he != NULL && dh->data[0].innetgroupdata.result == dataset->resp.result)
  498. {
  499. /* The data has not changed. We will just bump the timeout
  500. value. Note that the new record has been allocated on
  501. the stack and need not be freed. */
  502. dh->timeout = timeout;
  503. dh->ttl = dataset->head.ttl;
  504. ++dh->nreloads;
  505. if (cacheable)
  506. pthread_rwlock_unlock (&db->lock);
  507. goto out;
  508. }
  509. /* addgetnetgrentX may have already sent a notfound response. Do
  510. not send another one. */
  511. if (he == NULL && dataset->resp.found)
  512. {
  513. /* We write the dataset before inserting it to the database
  514. since while inserting this thread might block and so would
  515. unnecessarily let the receiver wait. */
  516. assert (fd != -1);
  517. writeall (fd, &dataset->resp, sizeof (innetgroup_response_header));
  518. }
  519. if (cacheable)
  520. {
  521. /* If necessary, we also propagate the data to disk. */
  522. if (db->persistent)
  523. {
  524. // XXX async OK?
  525. uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
  526. msync ((void *) pval,
  527. ((uintptr_t) dataset & pagesize_m1) + sizeof (*dataset)
  528. + req->key_len,
  529. MS_ASYNC);
  530. }
  531. (void) cache_add (req->type, key_copy, req->key_len, &dataset->head,
  532. true, db, uid, he == NULL);
  533. pthread_rwlock_unlock (&db->lock);
  534. /* Mark the old entry as obsolete. */
  535. if (dh != NULL)
  536. dh->usable = false;
  537. }
  538. out:
  539. addgetnetgrentX_scratch_free (&scratch);
  540. return timeout;
  541. }
  542. static time_t
  543. addgetnetgrentX_ignore (struct database_dyn *db, int fd, request_header *req,
  544. const char *key, uid_t uid, struct hashentry *he,
  545. struct datahead *dh)
  546. {
  547. struct addgetnetgrentX_scratch scratch;
  548. addgetnetgrentX_scratch_init (&scratch);
  549. time_t timeout = addgetnetgrentX (db, fd, req, key, uid, he, dh, &scratch);
  550. addgetnetgrentX_scratch_free (&scratch);
  551. if (timeout < 0)
  552. timeout = 0;
  553. return timeout;
  554. }
  555. void
  556. addgetnetgrent (struct database_dyn *db, int fd, request_header *req,
  557. void *key, uid_t uid)
  558. {
  559. addgetnetgrentX_ignore (db, fd, req, key, uid, NULL, NULL);
  560. }
  561. time_t
  562. readdgetnetgrent (struct database_dyn *db, struct hashentry *he,
  563. struct datahead *dh)
  564. {
  565. request_header req =
  566. {
  567. .type = GETNETGRENT,
  568. .key_len = he->len
  569. };
  570. return addgetnetgrentX_ignore
  571. (db, -1, &req, db->data + he->key, he->owner, he, dh);
  572. }
  573. void
  574. addinnetgr (struct database_dyn *db, int fd, request_header *req,
  575. void *key, uid_t uid)
  576. {
  577. addinnetgrX (db, fd, req, key, uid, NULL, NULL);
  578. }
  579. time_t
  580. readdinnetgr (struct database_dyn *db, struct hashentry *he,
  581. struct datahead *dh)
  582. {
  583. request_header req =
  584. {
  585. .type = INNETGR,
  586. .key_len = he->len
  587. };
  588. time_t timeout = addinnetgrX (db, -1, &req, db->data + he->key, he->owner,
  589. he, dh);
  590. if (timeout < 0)
  591. timeout = 0;
  592. return timeout;
  593. }