1/* Cache handling for host lookup.
2 Copyright (C) 1998-2020 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
5
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.
10
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.
15
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/>. */
18
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>
38
39#include "nscd.h"
40#include "dbg_log.h"
41
42
43/* This is the standard reply in case the service is disabled. */
44static const hst_response_header disabled =
45{
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
54};
55
56/* This is the struct describing how to write this record. */
57const struct iovec hst_iov_disabled =
58{
59 .iov_base = (void *) &disabled,
60 .iov_len = sizeof (disabled)
61};
62
63
64/* This is the standard reply in case we haven't found the dataset. */
65static const hst_response_header notfound =
66{
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
75};
76
77
78/* This is the standard reply in case there are temporary problems. */
79static const hst_response_header tryagain =
80{
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
89};
90
91
92static time_t
93cache_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)
97{
98 bool all_written = true;
99 time_t t = time (NULL);
100
101 /* We allocate all data in one memory block: the iov vector,
102 the response header and the dataset itself. */
103 struct dataset
104 {
105 struct datahead head;
106 hst_response_header resp;
107 char strdata[0];
108 } *dataset;
109
110 assert (offsetof (struct dataset, resp) == offsetof (struct datahead, data));
111
112 time_t timeout = MAX_TIMEOUT_VALUE;
113 if (hst == NULL)
114 {
115 if (he != NULL && errval == EAGAIN)
116 {
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;
123
124 /* Reload with the same time-to-live value. */
125 timeout = dh->timeout = t + dh->ttl;
126 }
127 else
128 {
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));
133
134 const hst_response_header *resp = (errval == EAGAIN
135 ? &tryagain : &notfound);
136
137 if (fd != -1
138 && TEMP_FAILURE_RETRY (send (fd, resp, total,
139 MSG_NOSIGNAL)) != total)
140 all_written = false;
141
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))
145 {
146 /* Mark the old entry as obsolete. */
147 if (dh != NULL)
148 dh->usable = false;
149 }
150 else if ((dataset = mempool_alloc (db, (sizeof (struct dataset)
151 + req->key_len), 1)) != NULL)
152 {
153 timeout = datahead_init_neg (&dataset->head,
154 (sizeof (struct dataset)
155 + req->key_len), total,
156 (ttl == INT32_MAX
157 ? db->negtimeout : ttl));
158
159 /* This is the reply. */
160 memcpy (&dataset->resp, resp, total);
161
162 /* Copy the key data. */
163 memcpy (dataset->strdata, key, req->key_len);
164
165 /* If necessary, we also propagate the data to disk. */
166 if (db->persistent)
167 {
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);
173 }
174
175 (void) cache_add (req->type, &dataset->strdata, req->key_len,
176 &dataset->head, true, db, owner, he == NULL);
177
178 pthread_rwlock_unlock (&db->lock);
179
180 /* Mark the old entry as obsolete. */
181 if (dh != NULL)
182 dh->usable = false;
183 }
184 }
185 }
186 else
187 {
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;
199
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)
208 {
209 h_aliases_len[cnt] = strlen (hst->h_aliases[cnt]) + 1;
210 total += h_aliases_len[cnt];
211 }
212
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;
217
218 if (h_addr_list_cnt == 0)
219 /* Invalid entry. */
220 return MAX_TIMEOUT_VALUE;
221
222 total += (sizeof (struct dataset)
223 + h_name_len
224 + h_aliases_cnt * sizeof (uint32_t)
225 + h_addr_list_cnt * hst->h_length);
226
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;
233
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,
241 1);
242
243 if (dataset == NULL)
244 {
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);
249
250 /* We cannot add this record to the permanent database. */
251 alloca_used = true;
252 }
253
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);
258
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;
267
268 /* Make sure there is no gap. */
269 assert ((char *) (&dataset->resp.error + 1) == dataset->strdata);
270
271 cp = dataset->strdata;
272
273 cp = mempcpy (cp, hst->h_name, h_name_len);
274 cp = mempcpy (cp, h_aliases_len, h_aliases_cnt * sizeof (uint32_t));
275
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);
280
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]);
285
286 assert (cp
287 == dataset->strdata + total - offsetof (struct dataset,
288 strdata));
289
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);
296
297 assert ((char *) &dataset->resp + dataset->head.recsize == cp);
298
299 /* Now we can determine whether on refill we have to create a new
300 record or not. */
301 if (he != NULL)
302 {
303 assert (fd == -1);
304
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)
309 {
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;
317 }
318 else
319 {
320 if (h_addr_list_cnt == 1)
321 {
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,
327 1);
328 if (newp != NULL)
329 {
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);
336
337 dataset = memcpy (newp, dataset, total + req->key_len);
338 alloca_used = false;
339 }
340 }
341
342 /* Mark the old record as obsolete. */
343 dh->usable = false;
344 }
345 }
346 else
347 {
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);
352
353 if (writeall (fd, &dataset->resp, dataset->head.recsize)
354 != dataset->head.recsize)
355 all_written = false;
356 }
357
358 /* Add the record to the database. But only if it has not been
359 stored on the stack.
360
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)
367 {
368 /* If necessary, we also propagate the data to disk. */
369 if (db->persistent)
370 {
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);
376 }
377
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);
384
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);
391
392 (void) cache_add (req->type, key_copy, req->key_len,
393 &dataset->head, true, db, owner, he == NULL);
394
395 pthread_rwlock_unlock (&db->lock);
396 }
397 }
398
399 if (__builtin_expect (!all_written, 0) && debug_level > 0)
400 {
401 char buf[256];
402 dbg_log (_("short write in %s: %s"), __FUNCTION__,
403 strerror_r (errno, buf, sizeof (buf)));
404 }
405
406 return timeout;
407}
408
409
410static int
411lookup (int type, void *key, struct hostent *resultbufp, char *buffer,
412 size_t buflen, struct hostent **hst, int32_t *ttlp)
413{
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);
425}
426
427
428static time_t
429addhstbyX (struct database_dyn *db, int fd, request_header *req,
430 void *key, uid_t uid, struct hashentry *he, struct datahead *dh)
431{
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;
440
441 if (__glibc_unlikely (debug_level > 0))
442 {
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));
450
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);
455 }
456
457 struct scratch_buffer tmpbuf;
458 scratch_buffer_init (&tmpbuf);
459
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))
465 {
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;
476 }
477
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;
482}
483
484
485void
486addhstbyname (struct database_dyn *db, int fd, request_header *req,
487 void *key, uid_t uid)
488{
489 addhstbyX (db, fd, req, key, uid, NULL, NULL);
490}
491
492
493time_t
494readdhstbyname (struct database_dyn *db, struct hashentry *he,
495 struct datahead *dh)
496{
497 request_header req =
498 {
499 .type = GETHOSTBYNAME,
500 .key_len = he->len
501 };
502
503 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
504}
505
506
507void
508addhstbyaddr (struct database_dyn *db, int fd, request_header *req,
509 void *key, uid_t uid)
510{
511 addhstbyX (db, fd, req, key, uid, NULL, NULL);
512}
513
514
515time_t
516readdhstbyaddr (struct database_dyn *db, struct hashentry *he,
517 struct datahead *dh)
518{
519 request_header req =
520 {
521 .type = GETHOSTBYADDR,
522 .key_len = he->len
523 };
524
525 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
526}
527
528
529void
530addhstbynamev6 (struct database_dyn *db, int fd, request_header *req,
531 void *key, uid_t uid)
532{
533 addhstbyX (db, fd, req, key, uid, NULL, NULL);
534}
535
536
537time_t
538readdhstbynamev6 (struct database_dyn *db, struct hashentry *he,
539 struct datahead *dh)
540{
541 request_header req =
542 {
543 .type = GETHOSTBYNAMEv6,
544 .key_len = he->len
545 };
546
547 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
548}
549
550
551void
552addhstbyaddrv6 (struct database_dyn *db, int fd, request_header *req,
553 void *key, uid_t uid)
554{
555 addhstbyX (db, fd, req, key, uid, NULL, NULL);
556}
557
558
559time_t
560readdhstbyaddrv6 (struct database_dyn *db, struct hashentry *he,
561 struct datahead *dh)
562{
563 request_header req =
564 {
565 .type = GETHOSTBYADDRv6,
566 .key_len = he->len
567 };
568
569 return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
570}
571