nscd_helper.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /* Copyright (C) 1998-2026 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library 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 GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <https://www.gnu.org/licenses/>. */
  14. #include <assert.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <stdbool.h>
  18. #include <stddef.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #include <stdint.h>
  24. #include <sys/mman.h>
  25. #include <sys/param.h>
  26. #include <sys/poll.h>
  27. #include <sys/socket.h>
  28. #include <sys/stat.h>
  29. #include <sys/time.h>
  30. #include <sys/uio.h>
  31. #include <sys/un.h>
  32. #include <not-cancel.h>
  33. #include <kernel-features.h>
  34. #include <nss.h>
  35. #include <struct___timespec64.h>
  36. #include "nscd-client.h"
  37. /* Extra time we wait if the socket is still receiving data. This
  38. value is in milliseconds. Note that the other side is nscd on the
  39. local machine and it is already transmitting data. So the wait
  40. time need not be long. */
  41. #define EXTRA_RECEIVE_TIME 200
  42. static int
  43. wait_on_socket (int sock, long int usectmo)
  44. {
  45. struct pollfd fds[1];
  46. fds[0].fd = sock;
  47. fds[0].events = POLLIN | POLLERR | POLLHUP;
  48. int n = __poll (fds, 1, usectmo);
  49. if (n == -1 && __builtin_expect (errno == EINTR, 0))
  50. {
  51. /* Handle the case where the poll() call is interrupted by a
  52. signal. We cannot just use TEMP_FAILURE_RETRY since it might
  53. lead to infinite loops. */
  54. struct __timespec64 now;
  55. __clock_gettime64 (CLOCK_REALTIME, &now);
  56. int64_t end = (now.tv_sec * 1000 + usectmo
  57. + (now.tv_nsec + 500000) / 1000000);
  58. long int timeout = usectmo;
  59. while (1)
  60. {
  61. n = __poll (fds, 1, timeout);
  62. if (n != -1 || errno != EINTR)
  63. break;
  64. /* Recompute the timeout time. */
  65. __clock_gettime64 (CLOCK_REALTIME, &now);
  66. timeout = end - ((now.tv_sec * 1000
  67. + (now.tv_nsec + 500000) / 1000000));
  68. }
  69. }
  70. return n;
  71. }
  72. ssize_t
  73. __readall (int fd, void *buf, size_t len)
  74. {
  75. size_t n = len;
  76. ssize_t ret;
  77. do
  78. {
  79. again:
  80. ret = TEMP_FAILURE_RETRY (__read (fd, buf, n));
  81. if (ret <= 0)
  82. {
  83. if (__builtin_expect (ret < 0 && errno == EAGAIN, 0)
  84. /* The socket is still receiving data. Wait a bit more. */
  85. && wait_on_socket (fd, EXTRA_RECEIVE_TIME) > 0)
  86. goto again;
  87. break;
  88. }
  89. buf = (char *) buf + ret;
  90. n -= ret;
  91. }
  92. while (n > 0);
  93. return ret < 0 ? ret : len - n;
  94. }
  95. ssize_t
  96. __readvall (int fd, const struct iovec *iov, int iovcnt)
  97. {
  98. ssize_t ret = TEMP_FAILURE_RETRY (__readv (fd, iov, iovcnt));
  99. if (ret <= 0)
  100. {
  101. if (__glibc_likely (ret == 0 || errno != EAGAIN))
  102. /* A genuine error or no data to read. */
  103. return ret;
  104. /* The data has not all yet been received. Do as if we have not
  105. read anything yet. */
  106. ret = 0;
  107. }
  108. size_t total = 0;
  109. for (int i = 0; i < iovcnt; ++i)
  110. total += iov[i].iov_len;
  111. if (ret < total)
  112. {
  113. struct iovec iov_buf[iovcnt];
  114. ssize_t r = ret;
  115. struct iovec *iovp = memcpy (iov_buf, iov, iovcnt * sizeof (*iov));
  116. do
  117. {
  118. while (iovp->iov_len <= r)
  119. {
  120. r -= iovp->iov_len;
  121. --iovcnt;
  122. ++iovp;
  123. }
  124. iovp->iov_base = (char *) iovp->iov_base + r;
  125. iovp->iov_len -= r;
  126. again:
  127. r = TEMP_FAILURE_RETRY (__readv (fd, iovp, iovcnt));
  128. if (r <= 0)
  129. {
  130. if (__builtin_expect (r < 0 && errno == EAGAIN, 0)
  131. /* The socket is still receiving data. Wait a bit more. */
  132. && wait_on_socket (fd, EXTRA_RECEIVE_TIME) > 0)
  133. goto again;
  134. break;
  135. }
  136. ret += r;
  137. }
  138. while (ret < total);
  139. if (r < 0)
  140. ret = r;
  141. }
  142. return ret;
  143. }
  144. static int
  145. open_socket (request_type type, const char *key, size_t keylen)
  146. {
  147. int sock;
  148. sock = __socket (PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
  149. if (sock < 0)
  150. return -1;
  151. size_t real_sizeof_reqdata = sizeof (request_header) + keylen;
  152. struct
  153. {
  154. request_header req;
  155. char key[];
  156. } *reqdata = alloca (real_sizeof_reqdata);
  157. struct sockaddr_un sun;
  158. sun.sun_family = AF_UNIX;
  159. strcpy (sun.sun_path, _PATH_NSCDSOCKET);
  160. if (__connect (sock, (struct sockaddr *) &sun, sizeof (sun)) < 0
  161. && errno != EINPROGRESS)
  162. goto out;
  163. reqdata->req.version = NSCD_VERSION;
  164. reqdata->req.type = type;
  165. reqdata->req.key_len = keylen;
  166. memcpy (reqdata->key, key, keylen);
  167. bool first_try = true;
  168. struct __timespec64 tvend = { 0, 0 };
  169. while (1)
  170. {
  171. #ifndef MSG_NOSIGNAL
  172. # define MSG_NOSIGNAL 0
  173. #endif
  174. ssize_t wres = TEMP_FAILURE_RETRY (__send (sock, reqdata,
  175. real_sizeof_reqdata,
  176. MSG_NOSIGNAL));
  177. if (__glibc_likely (wres == (ssize_t) real_sizeof_reqdata))
  178. /* We managed to send the request. */
  179. return sock;
  180. if (wres != -1 || errno != EAGAIN)
  181. /* Something is really wrong, no chance to continue. */
  182. break;
  183. /* The daemon is busy wait for it. */
  184. int to;
  185. struct __timespec64 now;
  186. __clock_gettime64 (CLOCK_REALTIME, &now);
  187. if (first_try)
  188. {
  189. tvend.tv_nsec = now.tv_nsec;
  190. tvend.tv_sec = now.tv_sec + 5;
  191. to = 5 * 1000;
  192. first_try = false;
  193. }
  194. else
  195. to = ((tvend.tv_sec - now.tv_sec) * 1000
  196. + (tvend.tv_nsec - now.tv_nsec) / 1000000);
  197. struct pollfd fds[1];
  198. fds[0].fd = sock;
  199. fds[0].events = POLLOUT | POLLERR | POLLHUP;
  200. if (__poll (fds, 1, to) <= 0)
  201. /* The connection timed out or broke down. */
  202. break;
  203. /* We try to write again. */
  204. }
  205. out:
  206. __close_nocancel_nostatus (sock);
  207. return -1;
  208. }
  209. void
  210. __nscd_unmap (struct mapped_database *mapped)
  211. {
  212. assert (mapped->counter == 0);
  213. __munmap ((void *) mapped->head, mapped->mapsize);
  214. free (mapped);
  215. }
  216. /* Try to get a file descriptor for the shared memory segment
  217. containing the database. */
  218. struct mapped_database *
  219. __nscd_get_mapping (request_type type, const char *key,
  220. struct mapped_database **mappedp)
  221. {
  222. struct mapped_database *result = NO_MAPPING;
  223. #ifdef SCM_RIGHTS
  224. const size_t keylen = strlen (key) + 1;
  225. int saved_errno = errno;
  226. int mapfd = -1;
  227. char resdata[keylen];
  228. /* Open a socket and send the request. */
  229. int sock = open_socket (type, key, keylen);
  230. if (sock < 0)
  231. goto out;
  232. /* Room for the data sent along with the file descriptor. We expect
  233. the key name back. */
  234. uint64_t mapsize;
  235. struct iovec iov[2];
  236. iov[0].iov_base = resdata;
  237. iov[0].iov_len = keylen;
  238. iov[1].iov_base = &mapsize;
  239. iov[1].iov_len = sizeof (mapsize);
  240. union
  241. {
  242. struct cmsghdr hdr;
  243. char bytes[CMSG_SPACE (sizeof (int))];
  244. } buf;
  245. struct msghdr msg = { .msg_iov = iov, .msg_iovlen = 2,
  246. .msg_control = buf.bytes,
  247. .msg_controllen = sizeof (buf) };
  248. struct cmsghdr *cmsg = CMSG_FIRSTHDR (&msg);
  249. cmsg->cmsg_level = SOL_SOCKET;
  250. cmsg->cmsg_type = SCM_RIGHTS;
  251. cmsg->cmsg_len = CMSG_LEN (sizeof (int));
  252. /* This access is well-aligned since BUF is correctly aligned for an
  253. int and CMSG_DATA preserves this alignment. */
  254. memset (CMSG_DATA (cmsg), '\xff', sizeof (int));
  255. msg.msg_controllen = cmsg->cmsg_len;
  256. if (wait_on_socket (sock, 5 * 1000) <= 0)
  257. goto out_close2;
  258. # ifndef MSG_CMSG_CLOEXEC
  259. # define MSG_CMSG_CLOEXEC 0
  260. # endif
  261. ssize_t n = TEMP_FAILURE_RETRY (__recvmsg (sock, &msg, MSG_CMSG_CLOEXEC));
  262. if (__builtin_expect (CMSG_FIRSTHDR (&msg) == NULL
  263. || (CMSG_FIRSTHDR (&msg)->cmsg_len
  264. != CMSG_LEN (sizeof (int))), 0))
  265. goto out_close2;
  266. int *ip = (void *) CMSG_DATA (cmsg);
  267. mapfd = *ip;
  268. if (__glibc_unlikely (n != keylen && n != keylen + sizeof (mapsize)))
  269. goto out_close;
  270. if (__glibc_unlikely (strcmp (resdata, key) != 0))
  271. goto out_close;
  272. if (__glibc_unlikely (n == keylen))
  273. {
  274. struct __stat64_t64 st;
  275. if (__glibc_unlikely (__fstat64_time64 (mapfd, &st) != 0)
  276. || __builtin_expect (st.st_size < sizeof (struct database_pers_head),
  277. 0))
  278. goto out_close;
  279. mapsize = st.st_size;
  280. }
  281. /* The file is large enough, map it now. */
  282. void *mapping = __mmap (NULL, mapsize, PROT_READ, MAP_SHARED, mapfd, 0);
  283. if (__glibc_likely (mapping != MAP_FAILED))
  284. {
  285. /* Check whether the database is correct and up-to-date. */
  286. struct database_pers_head *head = mapping;
  287. if (__builtin_expect (head->version != DB_VERSION, 0)
  288. || __builtin_expect (head->header_size != sizeof (*head), 0)
  289. /* Catch some misconfiguration. The server should catch
  290. them now but some older versions did not. */
  291. || __builtin_expect (head->module == 0, 0)
  292. /* This really should not happen but who knows, maybe the update
  293. thread got stuck. */
  294. || __builtin_expect (! head->nscd_certainly_running
  295. && (head->timestamp + MAPPING_TIMEOUT
  296. < time_now ()), 0))
  297. {
  298. out_unmap:
  299. __munmap (mapping, mapsize);
  300. goto out_close;
  301. }
  302. size_t size = (sizeof (*head) + roundup (head->module * sizeof (ref_t),
  303. ALIGN)
  304. + head->data_size);
  305. if (__glibc_unlikely (mapsize < size))
  306. goto out_unmap;
  307. /* Allocate a record for the mapping. */
  308. struct mapped_database *newp = malloc (sizeof (*newp));
  309. if (newp == NULL)
  310. /* Ugh, after all we went through the memory allocation failed. */
  311. goto out_unmap;
  312. newp->head = mapping;
  313. newp->data = ((char *) mapping + head->header_size
  314. + roundup (head->module * sizeof (ref_t), ALIGN));
  315. newp->mapsize = size;
  316. newp->datasize = head->data_size;
  317. /* Set counter to 1 to show it is usable. */
  318. newp->counter = 1;
  319. result = newp;
  320. }
  321. out_close:
  322. __close (mapfd);
  323. out_close2:
  324. __close (sock);
  325. out:
  326. __set_errno (saved_errno);
  327. #endif /* SCM_RIGHTS */
  328. struct mapped_database *oldval = *mappedp;
  329. *mappedp = result;
  330. if (oldval != NULL && atomic_fetch_add_relaxed (&oldval->counter, -1) == 1)
  331. __nscd_unmap (oldval);
  332. return result;
  333. }
  334. struct mapped_database *
  335. __nscd_get_map_ref (request_type type, const char *name,
  336. volatile struct locked_map_ptr *mapptr, int *gc_cyclep)
  337. {
  338. struct mapped_database *cur = mapptr->mapped;
  339. if (cur == NO_MAPPING)
  340. return cur;
  341. if (!__nscd_acquire_maplock (mapptr))
  342. return NO_MAPPING;
  343. cur = mapptr->mapped;
  344. if (__glibc_likely (cur != NO_MAPPING))
  345. {
  346. /* If not mapped or timestamp not updated, request new map. */
  347. if (cur == NULL
  348. || (cur->head->nscd_certainly_running == 0
  349. && cur->head->timestamp + MAPPING_TIMEOUT < time_now ())
  350. || cur->head->data_size > cur->datasize)
  351. cur = __nscd_get_mapping (type, name,
  352. (struct mapped_database **) &mapptr->mapped);
  353. if (__glibc_likely (cur != NO_MAPPING))
  354. {
  355. if (__builtin_expect (((*gc_cyclep = cur->head->gc_cycle) & 1) != 0,
  356. 0))
  357. cur = NO_MAPPING;
  358. else
  359. atomic_fetch_add_relaxed (&cur->counter, 1);
  360. }
  361. }
  362. mapptr->lock = 0;
  363. return cur;
  364. }
  365. /* Using sizeof (hashentry) is not always correct to determine the size of
  366. the data structure as found in the nscd cache. The program could be
  367. a 64-bit process and nscd could be a 32-bit process. In this case
  368. sizeof (hashentry) would overestimate the size. The following is
  369. the minimum size of such an entry, good enough for our tests here. */
  370. #define MINIMUM_HASHENTRY_SIZE \
  371. (offsetof (struct hashentry, dellist) + sizeof (int32_t))
  372. /* Don't return const struct datahead *, as even though the record
  373. is normally constant, it can change arbitrarily during nscd
  374. garbage collection. */
  375. struct datahead *
  376. __nscd_cache_search (request_type type, const char *key, size_t keylen,
  377. const struct mapped_database *mapped, size_t datalen)
  378. {
  379. unsigned long int hash = __nss_hash (key, keylen) % mapped->head->module;
  380. size_t datasize = mapped->datasize;
  381. ref_t trail = mapped->head->array[hash];
  382. ref_t work = trail;
  383. size_t loop_cnt = datasize / (MINIMUM_HASHENTRY_SIZE
  384. + offsetof (struct datahead, data) / 2);
  385. int tick = 0;
  386. while (work != ENDREF && work + MINIMUM_HASHENTRY_SIZE <= datasize)
  387. {
  388. struct hashentry *here = (struct hashentry *) (mapped->data + work);
  389. ref_t here_key, here_packet;
  390. /* Although during garbage collection when moving struct hashentry
  391. records around we first copy from old to new location and then
  392. adjust pointer from previous hashentry to it, there is no barrier
  393. between those memory writes!!! This is extremely risky on any
  394. modern CPU which can reorder memory accesses very aggressively.
  395. Check alignment, both as a partial consistency check and to avoid
  396. crashes on targets which require atomic loads to be aligned. */
  397. if ((uintptr_t) here & (__alignof__ (*here) - 1))
  398. return NULL;
  399. if (type == here->type
  400. && keylen == here->len
  401. && (here_key = atomic_load_relaxed (&here->key)) + keylen <= datasize
  402. && memcmp (key, mapped->data + here_key, keylen) == 0
  403. && ((here_packet = atomic_load_relaxed (&here->packet))
  404. + sizeof (struct datahead) <= datasize))
  405. {
  406. /* We found the entry. Increment the appropriate counter. */
  407. struct datahead *dh
  408. = (struct datahead *) (mapped->data + here_packet);
  409. if ((uintptr_t) dh & (__alignof__ (*dh) - 1))
  410. return NULL;
  411. /* See whether we must ignore the entry or whether something
  412. is wrong because garbage collection is in progress. */
  413. if (dh->usable
  414. && here_packet + dh->allocsize <= datasize
  415. && (here_packet + offsetof (struct datahead, data) + datalen
  416. <= datasize))
  417. return dh;
  418. }
  419. work = atomic_load_relaxed (&here->next);
  420. /* Prevent endless loops. This should never happen but perhaps
  421. the database got corrupted, accidentally or deliberately. */
  422. if (work == trail || loop_cnt-- == 0)
  423. break;
  424. if (tick)
  425. {
  426. struct hashentry *trailelem;
  427. trailelem = (struct hashentry *) (mapped->data + trail);
  428. /* We have to redo the checks. Maybe the data changed. */
  429. if ((uintptr_t) trailelem & (__alignof__ (*trailelem) - 1))
  430. return NULL;
  431. if (trail + MINIMUM_HASHENTRY_SIZE > datasize)
  432. return NULL;
  433. trail = atomic_load_relaxed (&trailelem->next);
  434. }
  435. tick = 1 - tick;
  436. }
  437. return NULL;
  438. }
  439. /* Create a socket connected to a name. */
  440. int
  441. __nscd_open_socket (const char *key, size_t keylen, request_type type,
  442. void *response, size_t responselen)
  443. {
  444. /* This should never happen and it is something the nscd daemon
  445. enforces, too. He it helps to limit the amount of stack
  446. used. */
  447. if (keylen > MAXKEYLEN)
  448. return -1;
  449. int saved_errno = errno;
  450. int sock = open_socket (type, key, keylen);
  451. if (sock >= 0)
  452. {
  453. /* Wait for data. */
  454. if (wait_on_socket (sock, 5 * 1000) > 0)
  455. {
  456. ssize_t nbytes = TEMP_FAILURE_RETRY (__read (sock, response,
  457. responselen));
  458. if (nbytes == (ssize_t) responselen)
  459. return sock;
  460. }
  461. __close_nocancel_nostatus (sock);
  462. }
  463. __set_errno (saved_errno);
  464. return -1;
  465. }