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