Handle nscd negtimeout==0
[platform/upstream/glibc.git] / nscd / hstcache.c
1 /* Cache handling for host lookup.
2    Copyright (C) 1998-2008, 2009, 2011 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, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #include <alloca.h>
21 #include <assert.h>
22 #include <errno.h>
23 #include <error.h>
24 #include <libintl.h>
25 #include <netdb.h>
26 #include <stdbool.h>
27 #include <stddef.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32 #include <unistd.h>
33 #include <arpa/inet.h>
34 #include <arpa/nameser.h>
35 #include <sys/mman.h>
36 #include <stackinfo.h>
37
38 #include "nscd.h"
39 #include "dbg_log.h"
40 #ifdef HAVE_SENDFILE
41 # include <kernel-features.h>
42 #endif
43
44
45 /* This is the standard reply in case the service is disabled.  */
46 static const hst_response_header disabled =
47 {
48   .version = NSCD_VERSION,
49   .found = -1,
50   .h_name_len = 0,
51   .h_aliases_cnt = 0,
52   .h_addrtype = -1,
53   .h_length = -1,
54   .h_addr_list_cnt = 0,
55   .error = NETDB_INTERNAL
56 };
57
58 /* This is the struct describing how to write this record.  */
59 const struct iovec hst_iov_disabled =
60 {
61   .iov_base = (void *) &disabled,
62   .iov_len = sizeof (disabled)
63 };
64
65
66 /* This is the standard reply in case we haven't found the dataset.  */
67 static const hst_response_header notfound =
68 {
69   .version = NSCD_VERSION,
70   .found = 0,
71   .h_name_len = 0,
72   .h_aliases_cnt = 0,
73   .h_addrtype = -1,
74   .h_length = -1,
75   .h_addr_list_cnt = 0,
76   .error = HOST_NOT_FOUND
77 };
78
79
80 /* This is the standard reply in case there are temporary problems.  */
81 static const hst_response_header tryagain =
82 {
83   .version = NSCD_VERSION,
84   .found = 0,
85   .h_name_len = 0,
86   .h_aliases_cnt = 0,
87   .h_addrtype = -1,
88   .h_length = -1,
89   .h_addr_list_cnt = 0,
90   .error = TRY_AGAIN
91 };
92
93
94 static time_t
95 cache_addhst (struct database_dyn *db, int fd, request_header *req,
96               const void *key, struct hostent *hst, uid_t owner,
97               struct hashentry *const he, struct datahead *dh, int errval,
98               int32_t ttl)
99 {
100   bool all_written = true;
101   time_t t = time (NULL);
102
103   /* We allocate all data in one memory block: the iov vector,
104      the response header and the dataset itself.  */
105   struct dataset
106   {
107     struct datahead head;
108     hst_response_header resp;
109     char strdata[0];
110   } *dataset;
111
112   assert (offsetof (struct dataset, resp) == offsetof (struct datahead, data));
113
114   time_t timeout = MAX_TIMEOUT_VALUE;
115   if (hst == NULL)
116     {
117       if (he != NULL && errval == EAGAIN)
118         {
119           /* If we have an old record available but cannot find one
120              now because the service is not available we keep the old
121              record and make sure it does not get removed.  */
122           if (reload_count != UINT_MAX)
123             /* Do not reset the value if we never not reload the record.  */
124             dh->nreloads = reload_count - 1;
125
126           /* Reload with the same time-to-live value.  */
127           timeout = dh->timeout = t + dh->ttl;
128         }
129       else
130         {
131           /* We have no data.  This means we send the standard reply for this
132              case.  Possibly this is only temporary.  */
133           ssize_t total = sizeof (notfound);
134           assert (sizeof (notfound) == sizeof (tryagain));
135
136           const hst_response_header *resp = (errval == EAGAIN
137                                              ? &tryagain : &notfound);
138
139           if (fd != -1 &&
140               TEMP_FAILURE_RETRY (send (fd, resp, total,
141                                         MSG_NOSIGNAL)) != total)
142             all_written = false;
143
144           /* If we cannot permanently store the result, so be it.  */
145           if (db->negtimeout == 0)
146             {
147               /* Mark the old entry as obsolete.  */
148               if (dh != NULL)
149                 dh->usable = false;
150             }
151           else if ((dataset = mempool_alloc (db, sizeof (struct dataset) + req->key_len, 1)) != NULL)
152             {
153               dataset->head.allocsize = sizeof (struct dataset) + req->key_len;
154               dataset->head.recsize = total;
155               dataset->head.notfound = true;
156               dataset->head.nreloads = 0;
157               dataset->head.usable = true;
158
159               /* Compute the timeout time.  */
160               dataset->head.ttl = ttl == INT32_MAX ? db->negtimeout : ttl;
161               timeout = dataset->head.timeout = t + dataset->head.ttl;
162
163               /* This is the reply.  */
164               memcpy (&dataset->resp, resp, total);
165
166               /* Copy the key data.  */
167               memcpy (dataset->strdata, key, req->key_len);
168
169               /* If necessary, we also propagate the data to disk.  */
170               if (db->persistent)
171                 {
172                   // XXX async OK?
173                   uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
174                   msync ((void *) pval,
175                          ((uintptr_t) dataset & pagesize_m1)
176                          + sizeof (struct dataset) + req->key_len, MS_ASYNC);
177                 }
178
179               (void) cache_add (req->type, &dataset->strdata, req->key_len,
180                                 &dataset->head, true, db, owner, he == NULL);
181
182               pthread_rwlock_unlock (&db->lock);
183
184               /* Mark the old entry as obsolete.  */
185               if (dh != NULL)
186                 dh->usable = false;
187             }
188         }
189     }
190   else
191     {
192       /* Determine the I/O structure.  */
193       size_t h_name_len = strlen (hst->h_name) + 1;
194       size_t h_aliases_cnt;
195       uint32_t *h_aliases_len;
196       size_t h_addr_list_cnt;
197       char *addresses;
198       char *aliases;
199       char *key_copy = NULL;
200       char *cp;
201       size_t cnt;
202       ssize_t total;
203
204       /* Determine the number of aliases.  */
205       h_aliases_cnt = 0;
206       for (cnt = 0; hst->h_aliases[cnt] != NULL; ++cnt)
207         ++h_aliases_cnt;
208       /* Determine the length of all aliases.  */
209       h_aliases_len = (uint32_t *) alloca (h_aliases_cnt * sizeof (uint32_t));
210       total = 0;
211       for (cnt = 0; cnt < h_aliases_cnt; ++cnt)
212         {
213           h_aliases_len[cnt] = strlen (hst->h_aliases[cnt]) + 1;
214           total += h_aliases_len[cnt];
215         }
216
217       /* Determine the number of addresses.  */
218       h_addr_list_cnt = 0;
219       while (hst->h_addr_list[h_addr_list_cnt] != NULL)
220         ++h_addr_list_cnt;
221
222       if (h_addr_list_cnt == 0)
223         /* Invalid entry.  */
224         return MAX_TIMEOUT_VALUE;
225
226       total += (sizeof (struct dataset)
227                 + h_name_len
228                 + h_aliases_cnt * sizeof (uint32_t)
229                 + h_addr_list_cnt * hst->h_length);
230
231       /* If we refill the cache, first assume the reconrd did not
232          change.  Allocate memory on the cache since it is likely
233          discarded anyway.  If it turns out to be necessary to have a
234          new record we can still allocate real memory.  */
235       bool alloca_used = false;
236       dataset = NULL;
237
238       /* If the record contains more than one IP address (used for
239          load balancing etc) don't cache the entry.  This is something
240          the current cache handling cannot handle and it is more than
241          questionable whether it is worthwhile complicating the cache
242          handling just for handling such a special case. */
243       if (he == NULL && h_addr_list_cnt == 1)
244         dataset = (struct dataset *) mempool_alloc (db, total + req->key_len,
245                                                     1);
246
247       if (dataset == NULL)
248         {
249           /* We cannot permanently add the result in the moment.  But
250              we can provide the result as is.  Store the data in some
251              temporary memory.  */
252           dataset = (struct dataset *) alloca (total + req->key_len);
253
254           /* We cannot add this record to the permanent database.  */
255           alloca_used = true;
256         }
257
258       dataset->head.allocsize = total + req->key_len;
259       dataset->head.recsize = total - offsetof (struct dataset, resp);
260       dataset->head.notfound = false;
261       dataset->head.nreloads = he == NULL ? 0 : (dh->nreloads + 1);
262       dataset->head.usable = true;
263
264       /* Compute the timeout time.  */
265       dataset->head.ttl = ttl == INT32_MAX ? db->postimeout : ttl;
266       timeout = dataset->head.timeout = t + dataset->head.ttl;
267
268       dataset->resp.version = NSCD_VERSION;
269       dataset->resp.found = 1;
270       dataset->resp.h_name_len = h_name_len;
271       dataset->resp.h_aliases_cnt = h_aliases_cnt;
272       dataset->resp.h_addrtype = hst->h_addrtype;
273       dataset->resp.h_length = hst->h_length;
274       dataset->resp.h_addr_list_cnt = h_addr_list_cnt;
275       dataset->resp.error = NETDB_SUCCESS;
276
277       /* Make sure there is no gap.  */
278       assert ((char *) (&dataset->resp.error + 1) == dataset->strdata);
279
280       cp = dataset->strdata;
281
282       cp = mempcpy (cp, hst->h_name, h_name_len);
283       cp = mempcpy (cp, h_aliases_len, h_aliases_cnt * sizeof (uint32_t));
284
285       /* The normal addresses first.  */
286       addresses = cp;
287       for (cnt = 0; cnt < h_addr_list_cnt; ++cnt)
288         cp = mempcpy (cp, hst->h_addr_list[cnt], hst->h_length);
289
290       /* Then the aliases.  */
291       aliases = cp;
292       for (cnt = 0; cnt < h_aliases_cnt; ++cnt)
293         cp = mempcpy (cp, hst->h_aliases[cnt], h_aliases_len[cnt]);
294
295       assert (cp
296               == dataset->strdata + total - offsetof (struct dataset,
297                                                       strdata));
298
299       /* If we are adding a GETHOSTBYNAME{,v6} entry we must be prepared
300          that the answer we get from the NSS does not contain the key
301          itself.  This is the case if the resolver is used and the name
302          is extended by the domainnames from /etc/resolv.conf.  Therefore
303          we explicitly add the name here.  */
304       key_copy = memcpy (cp, key, req->key_len);
305
306       assert ((char *) &dataset->resp + dataset->head.recsize == cp);
307
308       /* Now we can determine whether on refill we have to create a new
309          record or not.  */
310       if (he != NULL)
311         {
312           assert (fd == -1);
313
314           if (total + req->key_len == dh->allocsize
315               && total - offsetof (struct dataset, resp) == dh->recsize
316               && memcmp (&dataset->resp, dh->data,
317                          dh->allocsize - offsetof (struct dataset, resp)) == 0)
318             {
319               /* The data has not changed.  We will just bump the
320                  timeout value.  Note that the new record has been
321                  allocated on the stack and need not be freed.  */
322               assert (h_addr_list_cnt == 1);
323               dh->ttl = dataset->head.ttl;
324               dh->timeout = dataset->head.timeout;
325               ++dh->nreloads;
326             }
327           else
328             {
329               if (h_addr_list_cnt == 1)
330                 {
331                   /* We have to create a new record.  Just allocate
332                      appropriate memory and copy it.  */
333                   struct dataset *newp
334                     = (struct dataset *) mempool_alloc (db,
335                                                         total + req->key_len,
336                                                         1);
337                   if (newp != NULL)
338                     {
339                       /* Adjust pointers into the memory block.  */
340                       addresses = (char *) newp + (addresses
341                                                    - (char *) dataset);
342                       aliases = (char *) newp + (aliases - (char *) dataset);
343                       assert (key_copy != NULL);
344                       key_copy = (char *) newp + (key_copy - (char *) dataset);
345
346                       dataset = memcpy (newp, dataset, total + req->key_len);
347                       alloca_used = false;
348                     }
349                 }
350
351               /* Mark the old record as obsolete.  */
352               dh->usable = false;
353             }
354         }
355       else
356         {
357           /* We write the dataset before inserting it to the database
358              since while inserting this thread might block and so would
359              unnecessarily keep the receiver waiting.  */
360           assert (fd != -1);
361
362 #ifdef HAVE_SENDFILE
363           if (__builtin_expect (db->mmap_used, 1) && !alloca_used)
364             {
365               assert (db->wr_fd != -1);
366               assert ((char *) &dataset->resp > (char *) db->data);
367               assert ((char *) dataset - (char *) db->head
368                       + total
369                       <= (sizeof (struct database_pers_head)
370                           + db->head->module * sizeof (ref_t)
371                           + db->head->data_size));
372               ssize_t written = sendfileall (fd, db->wr_fd,
373                                              (char *) &dataset->resp
374                                              - (char *) db->head,
375                                              dataset->head.recsize);
376               if (written != dataset->head.recsize)
377                 {
378 # ifndef __ASSUME_SENDFILE
379                   if (written == -1 && errno == ENOSYS)
380                     goto use_write;
381 # endif
382                   all_written = false;
383                 }
384             }
385           else
386 # ifndef __ASSUME_SENDFILE
387           use_write:
388 # endif
389 #endif
390             if (writeall (fd, &dataset->resp, dataset->head.recsize)
391                 != dataset->head.recsize)
392               all_written = false;
393         }
394
395       /* Add the record to the database.  But only if it has not been
396          stored on the stack.
397
398          If the record contains more than one IP address (used for
399          load balancing etc) don't cache the entry.  This is something
400          the current cache handling cannot handle and it is more than
401          questionable whether it is worthwhile complicating the cache
402          handling just for handling such a special case. */
403       if (! alloca_used)
404         {
405           /* If necessary, we also propagate the data to disk.  */
406           if (db->persistent)
407             {
408               // XXX async OK?
409               uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
410               msync ((void *) pval,
411                      ((uintptr_t) dataset & pagesize_m1)
412                      + total + req->key_len, MS_ASYNC);
413             }
414
415           /* NB: the following code is really complicated.  It has
416              seemlingly duplicated code paths which do the same.  The
417              problem is that we always must add the hash table entry
418              with the FIRST flag set first.  Otherwise we get dangling
419              pointers in case memory allocation fails.  */
420           assert (hst->h_addr_list[1] == NULL);
421
422           /* Avoid adding names if more than one address is available.  See
423              above for more info.  */
424           assert (req->type == GETHOSTBYNAME
425                   || req->type == GETHOSTBYNAMEv6
426                   || req->type == GETHOSTBYADDR
427                   || req->type == GETHOSTBYADDRv6);
428
429           (void) cache_add (req->type, key_copy, req->key_len,
430                             &dataset->head, true, db, owner, he == NULL);
431
432           pthread_rwlock_unlock (&db->lock);
433         }
434     }
435
436   if (__builtin_expect (!all_written, 0) && debug_level > 0)
437     {
438       char buf[256];
439       dbg_log (_("short write in %s: %s"),  __FUNCTION__,
440                strerror_r (errno, buf, sizeof (buf)));
441     }
442
443   return timeout;
444 }
445
446
447 static int
448 lookup (int type, void *key, struct hostent *resultbufp, char *buffer,
449         size_t buflen, struct hostent **hst, int32_t *ttlp)
450 {
451   if (type == GETHOSTBYNAME)
452     return __gethostbyname3_r (key, AF_INET, resultbufp, buffer, buflen, hst,
453                                &h_errno, ttlp, NULL);
454   if (type == GETHOSTBYNAMEv6)
455     return __gethostbyname3_r (key, AF_INET6, resultbufp, buffer, buflen, hst,
456                                &h_errno, ttlp, NULL);
457   if (type == GETHOSTBYADDR)
458     return __gethostbyaddr2_r (key, NS_INADDRSZ, AF_INET, resultbufp, buffer,
459                                buflen, hst, &h_errno, ttlp);
460   return __gethostbyaddr2_r (key, NS_IN6ADDRSZ, AF_INET6, resultbufp, buffer,
461                              buflen, hst, &h_errno, ttlp);
462 }
463
464
465 static time_t
466 addhstbyX (struct database_dyn *db, int fd, request_header *req,
467            void *key, uid_t uid, struct hashentry *he, struct datahead *dh)
468 {
469   /* Search for the entry matching the key.  Please note that we don't
470      look again in the table whether the dataset is now available.  We
471      simply insert it.  It does not matter if it is in there twice.  The
472      pruning function only will look at the timestamp.  */
473   int buflen = 1024;
474   char *buffer = (char *) alloca (buflen);
475   struct hostent resultbuf;
476   struct hostent *hst;
477   bool use_malloc = false;
478   int errval = 0;
479   int32_t ttl = INT32_MAX;
480
481   if (__builtin_expect (debug_level > 0, 0))
482     {
483       const char *str;
484       char buf[INET6_ADDRSTRLEN + 1];
485       if (req->type == GETHOSTBYNAME || req->type == GETHOSTBYNAMEv6)
486         str = key;
487       else
488         str = inet_ntop (req->type == GETHOSTBYADDR ? AF_INET : AF_INET6,
489                          key, buf, sizeof (buf));
490
491       if (he == NULL)
492         dbg_log (_("Haven't found \"%s\" in hosts cache!"), (char *) str);
493       else
494         dbg_log (_("Reloading \"%s\" in hosts cache!"), (char *) str);
495     }
496
497   while (lookup (req->type, key, &resultbuf, buffer, buflen, &hst, &ttl) != 0
498          && h_errno == NETDB_INTERNAL
499          && (errval = errno) == ERANGE)
500     {
501       errno = 0;
502
503       if (__builtin_expect (buflen > 32768, 0))
504         {
505           char *old_buffer = buffer;
506           buflen *= 2;
507           buffer = (char *) realloc (use_malloc ? buffer : NULL, buflen);
508           if (buffer == NULL)
509             {
510               /* We ran out of memory.  We cannot do anything but
511                  sending a negative response.  In reality this should
512                  never happen.  */
513               hst = NULL;
514               buffer = old_buffer;
515
516               /* We set the error to indicate this is (possibly) a
517                  temporary error and that it does not mean the entry
518                  is not available at all.  */
519               h_errno = TRY_AGAIN;
520               errval = EAGAIN;
521               break;
522             }
523           use_malloc = true;
524         }
525       else
526         /* Allocate a new buffer on the stack.  If possible combine it
527            with the previously allocated buffer.  */
528         buffer = (char *) extend_alloca (buffer, buflen, 2 * buflen);
529     }
530
531   time_t timeout = cache_addhst (db, fd, req, key, hst, uid, he, dh,
532                                  h_errno == TRY_AGAIN ? errval : 0, ttl);
533
534   if (use_malloc)
535     free (buffer);
536
537   return timeout;
538 }
539
540
541 void
542 addhstbyname (struct database_dyn *db, int fd, request_header *req,
543               void *key, uid_t uid)
544 {
545   addhstbyX (db, fd, req, key, uid, NULL, NULL);
546 }
547
548
549 time_t
550 readdhstbyname (struct database_dyn *db, struct hashentry *he,
551                 struct datahead *dh)
552 {
553   request_header req =
554     {
555       .type = GETHOSTBYNAME,
556       .key_len = he->len
557     };
558
559   return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
560 }
561
562
563 void
564 addhstbyaddr (struct database_dyn *db, int fd, request_header *req,
565               void *key, uid_t uid)
566 {
567   addhstbyX (db, fd, req, key, uid, NULL, NULL);
568 }
569
570
571 time_t
572 readdhstbyaddr (struct database_dyn *db, struct hashentry *he,
573                 struct datahead *dh)
574 {
575   request_header req =
576     {
577       .type = GETHOSTBYADDR,
578       .key_len = he->len
579     };
580
581   return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
582 }
583
584
585 void
586 addhstbynamev6 (struct database_dyn *db, int fd, request_header *req,
587                 void *key, uid_t uid)
588 {
589   addhstbyX (db, fd, req, key, uid, NULL, NULL);
590 }
591
592
593 time_t
594 readdhstbynamev6 (struct database_dyn *db, struct hashentry *he,
595                   struct datahead *dh)
596 {
597   request_header req =
598     {
599       .type = GETHOSTBYNAMEv6,
600       .key_len = he->len
601     };
602
603   return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
604 }
605
606
607 void
608 addhstbyaddrv6 (struct database_dyn *db, int fd, request_header *req,
609                 void *key, uid_t uid)
610 {
611   addhstbyX (db, fd, req, key, uid, NULL, NULL);
612 }
613
614
615 time_t
616 readdhstbyaddrv6 (struct database_dyn *db, struct hashentry *he,
617                   struct datahead *dh)
618 {
619   request_header req =
620     {
621       .type = GETHOSTBYADDRv6,
622       .key_len = he->len
623     };
624
625   return addhstbyX (db, -1, &req, db->data + he->key, he->owner, he, dh);
626 }