Update ChangeLog.old/ChangeLog.23.
[glibc.git] / nscd / hstcache.c
blob253c1a16640cc4db8693cf4b6bb46015bb33df64
1 /* Cache handling for host lookup.
2 Copyright (C) 1998-2021 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published
8 by the Free Software Foundation; version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, see <https://www.gnu.org/licenses/>. */
19 #include <alloca.h>
20 #include <assert.h>
21 #include <errno.h>
22 #include <error.h>
23 #include <libintl.h>
24 #include <netdb.h>
25 #include <stdbool.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <time.h>
31 #include <unistd.h>
32 #include <stdint.h>
33 #include <arpa/inet.h>
34 #include <arpa/nameser.h>
35 #include <sys/mman.h>
36 #include <stackinfo.h>
37 #include <scratch_buffer.h>
39 #include "nscd.h"
40 #include "dbg_log.h"
43 /* This is the standard reply in case the service is disabled. */
44 static const hst_response_header disabled =
46 .version = NSCD_VERSION,
47 .found = -1,
48 .h_name_len = 0,
49 .h_aliases_cnt = 0,
50 .h_addrtype = -1,
51 .h_length = -1,
52 .h_addr_list_cnt = 0,
53 .error = NETDB_INTERNAL
56 /* This is the struct describing how to write this record. */
57 const struct iovec hst_iov_disabled =
59 .iov_base = (void *) &disabled,
60 .iov_len = sizeof (disabled)
64 /* This is the standard reply in case we haven't found the dataset. */
65 static const hst_response_header notfound =
67 .version = NSCD_VERSION,
68 .found = 0,
69 .h_name_len = 0,
70 .h_aliases_cnt = 0,
71 .h_addrtype = -1,
72 .h_length = -1,
73 .h_addr_list_cnt = 0,
74 .error = HOST_NOT_FOUND
78 /* This is the standard reply in case there are temporary problems. */
79 static const hst_response_header tryagain =
81 .version = NSCD_VERSION,
82 .found = 0,
83 .h_name_len = 0,
84 .h_aliases_cnt = 0,
85 .h_addrtype = -1,
86 .h_length = -1,
87 .h_addr_list_cnt = 0,
88 .error = TRY_AGAIN
92 static time_t
93 cache_addhst (struct database_dyn *db, int fd, request_header *req,
94 const void *key, struct hostent *hst, uid_t owner,
95 struct hashentry *const he, struct datahead *dh, int errval,
96 int32_t ttl)
98 bool all_written = true;
99 time_t t = time (NULL);
101 /* We allocate all data in one memory block: the iov vector,
102 the response header and the dataset itself. */
103 struct dataset
105 struct datahead head;
106 hst_response_header resp;
107 char strdata[0];
108 } *dataset;
110 assert (offsetof (struct dataset, resp) == offsetof (struct datahead, data));
112 time_t timeout = MAX_TIMEOUT_VALUE;
113 if (hst == NULL)
115 if (he != NULL && errval == EAGAIN)
117 /* If we have an old record available but cannot find one
118 now because the service is not available we keep the old
119 record and make sure it does not get removed. */
120 if (reload_count != UINT_MAX)
121 /* Do not reset the value if we never not reload the record. */
122 dh->nreloads = reload_count - 1;
124 /* Reload with the same time-to-live value. */
125 timeout = dh->timeout = t + dh->ttl;
127 else
129 /* We have no data. This means we send the standard reply for this
130 case. Possibly this is only temporary. */
131 ssize_t total = sizeof (notfound);
132 assert (sizeof (notfound) == sizeof (tryagain));
134 const hst_response_header *resp = (errval == EAGAIN
135 ? &tryagain : &notfound);
137 if (fd != -1
138 && TEMP_FAILURE_RETRY (send (fd, resp, total,
139 MSG_NOSIGNAL)) != total)
140 all_written = false;
142 /* If we have a transient error or cannot permanently store
143 the result, so be it. */
144 if (errval == EAGAIN || __builtin_expect (db->negtimeout == 0, 0))
146 /* Mark the old entry as obsolete. */
147 if (dh != NULL)
148 dh->usable = false;
150 else if ((dataset = mempool_alloc (db, (sizeof (struct dataset)
151 + req->key_len), 1)) != NULL)
153 timeout = datahead_init_neg (&dataset->head,
154 (sizeof (struct dataset)
155 + req->key_len), total,
156 (ttl == INT32_MAX
157 ? db->negtimeout : ttl));
159 /* This is the reply. */
160 memcpy (&dataset->resp, resp, total);
162 /* Copy the key data. */
163 memcpy (dataset->strdata, key, req->key_len);
165 /* If necessary, we also propagate the data to disk. */
166 if (db->persistent)
168 // XXX async OK?
169 uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
170 msync ((void *) pval,
171 ((uintptr_t) dataset & pagesize_m1)
172 + sizeof (struct dataset) + req->key_len, MS_ASYNC);
175 (void) cache_add (req->type, &dataset->strdata, req->key_len,
176 &dataset->head, true, db, owner, he == NULL);
178 pthread_rwlock_unlock (&db->lock);
180 /* Mark the old entry as obsolete. */
181 if (dh != NULL)
182 dh->usable = false;
186 else
188 /* Determine the I/O structure. */
189 size_t h_name_len = strlen (hst->h_name) + 1;
190 size_t h_aliases_cnt;
191 uint32_t *h_aliases_len;
192 size_t h_addr_list_cnt;
193 char *addresses;
194 char *aliases;
195 char *key_copy = NULL;
196 char *cp;
197 size_t cnt;
198 ssize_t total;
200 /* Determine the number of aliases. */
201 h_aliases_cnt = 0;
202 for (cnt = 0; hst->h_aliases[cnt] != NULL; ++cnt)
203 ++h_aliases_cnt;
204 /* Determine the length of all aliases. */
205 h_aliases_len = (uint32_t *) alloca (h_aliases_cnt * sizeof (uint32_t));
206 total = 0;
207 for (cnt = 0; cnt < h_aliases_cnt; ++cnt)
209 h_aliases_len[cnt] = strlen (hst->h_aliases[cnt]) + 1;
210 total += h_aliases_len[cnt];
213 /* Determine the number of addresses. */
214 h_addr_list_cnt = 0;
215 while (hst->h_addr_list[h_addr_list_cnt] != NULL)
216 ++h_addr_list_cnt;
218 if (h_addr_list_cnt == 0)
219 /* Invalid entry. */
220 return MAX_TIMEOUT_VALUE;
222 total += (sizeof (struct dataset)
223 + h_name_len
224 + h_aliases_cnt * sizeof (uint32_t)
225 + h_addr_list_cnt * hst->h_length);
227 /* If we refill the cache, first assume the reconrd did not
228 change. Allocate memory on the cache since it is likely
229 discarded anyway. If it turns out to be necessary to have a
230 new record we can still allocate real memory. */
231 bool alloca_used = false;
232 dataset = NULL;
234 /* If the record contains more than one IP address (used for
235 load balancing etc) don't cache the entry. This is something
236 the current cache handling cannot handle and it is more than
237 questionable whether it is worthwhile complicating the cache
238 handling just for handling such a special case. */
239 if (he == NULL && h_addr_list_cnt == 1)
240 dataset = (struct dataset *) mempool_alloc (db, total + req->key_len,
243 if (dataset == NULL)
245 /* We cannot permanently add the result in the moment. But
246 we can provide the result as is. Store the data in some
247 temporary memory. */
248 dataset = (struct dataset *) alloca (total + req->key_len);
250 /* We cannot add this record to the permanent database. */
251 alloca_used = true;
254 timeout = datahead_init_pos (&dataset->head, total + req->key_len,
255 total - offsetof (struct dataset, resp),
256 he == NULL ? 0 : dh->nreloads + 1,
257 ttl == INT32_MAX ? db->postimeout : ttl);
259 dataset->resp.version = NSCD_VERSION;
260 dataset->resp.found = 1;
261 dataset->resp.h_name_len = h_name_len;
262 dataset->resp.h_aliases_cnt = h_aliases_cnt;
263 dataset->resp.h_addrtype = hst->h_addrtype;
264 dataset->resp.h_length = hst->h_length;
265 dataset->resp.h_addr_list_cnt = h_addr_list_cnt;
266 dataset->resp.error = NETDB_SUCCESS;
268 /* Make sure there is no gap. */
269 assert ((char *) (&dataset->resp.error + 1) == dataset->strdata);
271 cp = dataset->strdata;
273 cp = mempcpy (cp, hst->h_name, h_name_len);
274 cp = mempcpy (cp, h_aliases_len, h_aliases_cnt * sizeof (uint32_t));
276 /* The normal addresses first. */
277 addresses = cp;
278 for (cnt = 0; cnt < h_addr_list_cnt; ++cnt)
279 cp = mempcpy (cp, hst->h_addr_list[cnt], hst->h_length);
281 /* Then the aliases. */
282 aliases = cp;
283 for (cnt = 0; cnt < h_aliases_cnt; ++cnt)
284 cp = mempcpy (cp, hst->h_aliases[cnt], h_aliases_len[cnt]);
286 assert (cp
287 == dataset->strdata + total - offsetof (struct dataset,
288 strdata));
290 /* If we are adding a GETHOSTBYNAME{,v6} entry we must be prepared
291 that the answer we get from the NSS does not contain the key
292 itself. This is the case if the resolver is used and the name
293 is extended by the domainnames from /etc/resolv.conf. Therefore
294 we explicitly add the name here. */
295 key_copy = memcpy (cp, key, req->key_len);
297 assert ((char *) &dataset->resp + dataset->head.recsize == cp);
299 /* Now we can determine whether on refill we have to create a new
300 record or not. */
301 if (he != NULL)
303 assert (fd == -1);
305 if (total + req->key_len == dh->allocsize
306 && total - offsetof (struct dataset, resp) == dh->recsize
307 && memcmp (&dataset->resp, dh->data,
308 dh->allocsize - offsetof (struct dataset, resp)) == 0)
310 /* The data has not changed. We will just bump the
311 timeout value. Note that the new record has been
312 allocated on the stack and need not be freed. */
313 assert (h_addr_list_cnt == 1);
314 dh->ttl = dataset->head.ttl;
315 dh->timeout = dataset->head.timeout;
316 ++dh->nreloads;
318 else
320 if (h_addr_list_cnt == 1)
322 /* We have to create a new record. Just allocate
323 appropriate memory and copy it. */
324 struct dataset *newp
325 = (struct dataset *) mempool_alloc (db,
326 total + req->key_len,
328 if (newp != NULL)
330 /* Adjust pointers into the memory block. */
331 addresses = (char *) newp + (addresses
332 - (char *) dataset);
333 aliases = (char *) newp + (aliases - (char *) dataset);
334 assert (key_copy != NULL);
335 key_copy = (char *) newp + (key_copy - (char *) dataset);
337 dataset = memcpy (newp, dataset, total + req->key_len);
338 alloca_used = false;
342 /* Mark the old record as obsolete. */
343 dh->usable = false;
346 else
348 /* We write the dataset before inserting it to the database
349 since while inserting this thread might block and so would
350 unnecessarily keep the receiver waiting. */
351 assert (fd != -1);
353 if (writeall (fd, &dataset->resp, dataset->head.recsize)
354 != dataset->head.recsize)
355 all_written = false;
358 /* Add the record to the database. But only if it has not been
359 stored on the stack.
361 If the record contains more than one IP address (used for
362 load balancing etc) don't cache the entry. This is something
363 the current cache handling cannot handle and it is more than
364 questionable whether it is worthwhile complicating the cache
365 handling just for handling such a special case. */
366 if (! alloca_used)
368 /* If necessary, we also propagate the data to disk. */
369 if (db->persistent)
371 // XXX async OK?
372 uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
373 msync ((void *) pval,
374 ((uintptr_t) dataset & pagesize_m1)
375 + total + req->key_len, MS_ASYNC);
378 /* NB: the following code is really complicated. It has
379 seemlingly duplicated code paths which do the same. The
380 problem is that we always must add the hash table entry
381 with the FIRST flag set first. Otherwise we get dangling
382 pointers in case memory allocation fails. */
383 assert (hst->h_addr_list[1] == NULL);
385 /* Avoid adding names if more than one address is available. See
386 above for more info. */
387 assert (req->type == GETHOSTBYNAME
388 || req->type == GETHOSTBYNAMEv6
389 || req->type == GETHOSTBYADDR
390 || req->type == GETHOSTBYADDRv6);
392 (void) cache_add (req->type, key_copy, req->key_len,
393 &dataset->head, true, db, owner, he == NULL);
395 pthread_rwlock_unlock (&db->lock);
399 if (__builtin_expect (!all_written, 0) && debug_level > 0)
401 char buf[256];
402 dbg_log (_("short write in %s: %s"), __FUNCTION__,
403 strerror_r (errno, buf, sizeof (buf)));
406 return timeout;
410 static int
411 lookup (int type, void *key, struct hostent *resultbufp, char *buffer,
412 size_t buflen, struct hostent **hst, int32_t *ttlp)
414 if (type == GETHOSTBYNAME)
415 return __gethostbyname3_r (key, AF_INET, resultbufp, buffer, buflen, hst,
416 &h_errno, ttlp, NULL);
417 if (type == GETHOSTBYNAMEv6)
418 return __gethostbyname3_r (key, AF_INET6, resultbufp, buffer, buflen, hst,
419 &h_errno, ttlp, NULL);
420 if (type == GETHOSTBYADDR)
421 return __gethostbyaddr2_r (key, NS_INADDRSZ, AF_INET, resultbufp, buffer,
422 buflen, hst, &h_errno, ttlp);
423 return __gethostbyaddr2_r (key, NS_IN6ADDRSZ, AF_INET6, resultbufp, buffer,
424 buflen, hst, &h_errno, ttlp);
428 static time_t
429 addhstbyX (struct database_dyn *db, int fd, request_header *req,
430 void *key, uid_t uid, struct hashentry *he, struct datahead *dh)
432 /* Search for the entry matching the key. Please note that we don't
433 look again in the table whether the dataset is now available. We
434 simply insert it. It does not matter if it is in there twice. The
435 pruning function only will look at the timestamp. */
436 struct hostent resultbuf;
437 struct hostent *hst;
438 int errval = 0;
439 int32_t ttl = INT32_MAX;
441 if (__glibc_unlikely (debug_level > 0))
443 const char *str;
444 char buf[INET6_ADDRSTRLEN + 1];
445 if (req->type == GETHOSTBYNAME || req->type == GETHOSTBYNAMEv6)
446 str = key;
447 else
448 str = inet_ntop (req->type == GETHOSTBYADDR ? AF_INET : AF_INET6,
449 key, buf, sizeof (buf));
451 if (he == NULL)
452 dbg_log (_("Haven't found \"%s\" in hosts cache!"), (char *) str);
453 else
454 dbg_log (_("Reloading \"%s\" in hosts cache!"), (char *) str);
457 struct scratch_buffer tmpbuf;
458 scratch_buffer_init (&tmpbuf);
460 while (lookup (req->type, key, &resultbuf,
461 tmpbuf.data, tmpbuf.length, &hst, &ttl) != 0
462 && h_errno == NETDB_INTERNAL
463 && (errval = errno) == ERANGE)
464 if (!scratch_buffer_grow (&tmpbuf))
466 /* We ran out of memory. We cannot do anything but sending a
467 negative response. In reality this should never
468 happen. */
469 hst = NULL;
470 /* We set the error to indicate this is (possibly) a temporary
471 error and that it does not mean the entry is not
472 available at all. */
473 h_errno = TRY_AGAIN;
474 errval = EAGAIN;
475 break;
478 time_t timeout = cache_addhst (db, fd, req, key, hst, uid, he, dh,
479 h_errno == TRY_AGAIN ? errval : 0, ttl);
480 scratch_buffer_free (&tmpbuf);
481 return timeout;
485 void
486 addhstbyname (struct database_dyn *db, int fd, request_header *req,
487 void *key, uid_t uid)
489 addhstbyX (db, fd, req, key, uid, NULL, NULL);
493 time_t
494 readdhstbyname (struct database_dyn *db, struct hashentry *he,
495 struct datahead *dh)
497 request_header req =
499 .type = GETHOSTBYNAME,
500 .key_len = he->len
503 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
507 void
508 addhstbyaddr (struct database_dyn *db, int fd, request_header *req,
509 void *key, uid_t uid)
511 addhstbyX (db, fd, req, key, uid, NULL, NULL);
515 time_t
516 readdhstbyaddr (struct database_dyn *db, struct hashentry *he,
517 struct datahead *dh)
519 request_header req =
521 .type = GETHOSTBYADDR,
522 .key_len = he->len
525 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
529 void
530 addhstbynamev6 (struct database_dyn *db, int fd, request_header *req,
531 void *key, uid_t uid)
533 addhstbyX (db, fd, req, key, uid, NULL, NULL);
537 time_t
538 readdhstbynamev6 (struct database_dyn *db, struct hashentry *he,
539 struct datahead *dh)
541 request_header req =
543 .type = GETHOSTBYNAMEv6,
544 .key_len = he->len
547 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
551 void
552 addhstbyaddrv6 (struct database_dyn *db, int fd, request_header *req,
553 void *key, uid_t uid)
555 addhstbyX (db, fd, req, key, uid, NULL, NULL);
559 time_t
560 readdhstbyaddrv6 (struct database_dyn *db, struct hashentry *he,
561 struct datahead *dh)
563 request_header req =
565 .type = GETHOSTBYADDRv6,
566 .key_len = he->len
569 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);