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