math: Reverse include order in <math-type-macros-*.h>
[glibc.git] / nscd / pwdcache.c
blob997d7c08fc54f6b16bd17b975e0601a203a0b451
1 /* Cache handling for passwd lookup.
2 Copyright (C) 1998-2018 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 <http://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 <pwd.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 <sys/mman.h>
33 #include <sys/socket.h>
34 #include <stackinfo.h>
36 #include "nscd.h"
37 #include "dbg_log.h"
39 /* This is the standard reply in case the service is disabled. */
40 static const pw_response_header disabled =
42 .version = NSCD_VERSION,
43 .found = -1,
44 .pw_name_len = 0,
45 .pw_passwd_len = 0,
46 .pw_uid = -1,
47 .pw_gid = -1,
48 .pw_gecos_len = 0,
49 .pw_dir_len = 0,
50 .pw_shell_len = 0
53 /* This is the struct describing how to write this record. */
54 const struct iovec pwd_iov_disabled =
56 .iov_base = (void *) &disabled,
57 .iov_len = sizeof (disabled)
61 /* This is the standard reply in case we haven't found the dataset. */
62 static const pw_response_header notfound =
64 .version = NSCD_VERSION,
65 .found = 0,
66 .pw_name_len = 0,
67 .pw_passwd_len = 0,
68 .pw_uid = -1,
69 .pw_gid = -1,
70 .pw_gecos_len = 0,
71 .pw_dir_len = 0,
72 .pw_shell_len = 0
76 static time_t
77 cache_addpw (struct database_dyn *db, int fd, request_header *req,
78 const void *key, struct passwd *pwd, uid_t owner,
79 struct hashentry *const he, struct datahead *dh, int errval)
81 bool all_written = true;
82 ssize_t total;
83 time_t t = time (NULL);
85 /* We allocate all data in one memory block: the iov vector,
86 the response header and the dataset itself. */
87 struct dataset
89 struct datahead head;
90 pw_response_header resp;
91 char strdata[0];
92 } *dataset;
94 assert (offsetof (struct dataset, resp) == offsetof (struct datahead, data));
96 time_t timeout = MAX_TIMEOUT_VALUE;
97 if (pwd == NULL)
99 if (he != NULL && errval == EAGAIN)
101 /* If we have an old record available but cannot find one
102 now because the service is not available we keep the old
103 record and make sure it does not get removed. */
104 if (reload_count != UINT_MAX && dh->nreloads == reload_count)
105 /* Do not reset the value if we never not reload the record. */
106 dh->nreloads = reload_count - 1;
108 /* Reload with the same time-to-live value. */
109 timeout = dh->timeout = t + db->postimeout;
111 total = 0;
113 else
115 /* We have no data. This means we send the standard reply for this
116 case. */
117 total = sizeof (notfound);
119 if (fd != -1
120 && TEMP_FAILURE_RETRY (send (fd, &notfound, total,
121 MSG_NOSIGNAL)) != total)
122 all_written = false;
124 /* If we have a transient error or cannot permanently store
125 the result, so be it. */
126 if (errno == EAGAIN || __builtin_expect (db->negtimeout == 0, 0))
128 /* Mark the old entry as obsolete. */
129 if (dh != NULL)
130 dh->usable = false;
132 else if ((dataset = mempool_alloc (db, (sizeof (struct dataset)
133 + req->key_len), 1)) != NULL)
135 timeout = datahead_init_neg (&dataset->head,
136 (sizeof (struct dataset)
137 + req->key_len), total,
138 db->negtimeout);
140 /* This is the reply. */
141 memcpy (&dataset->resp, &notfound, total);
143 /* Copy the key data. */
144 char *key_copy = memcpy (dataset->strdata, key, req->key_len);
146 /* If necessary, we also propagate the data to disk. */
147 if (db->persistent)
149 // XXX async OK?
150 uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
151 msync ((void *) pval,
152 ((uintptr_t) dataset & pagesize_m1)
153 + sizeof (struct dataset) + req->key_len, MS_ASYNC);
156 (void) cache_add (req->type, key_copy, req->key_len,
157 &dataset->head, true, db, owner, he == NULL);
159 pthread_rwlock_unlock (&db->lock);
161 /* Mark the old entry as obsolete. */
162 if (dh != NULL)
163 dh->usable = false;
167 else
169 /* Determine the I/O structure. */
170 size_t pw_name_len = strlen (pwd->pw_name) + 1;
171 size_t pw_passwd_len = strlen (pwd->pw_passwd) + 1;
172 size_t pw_gecos_len = strlen (pwd->pw_gecos) + 1;
173 size_t pw_dir_len = strlen (pwd->pw_dir) + 1;
174 size_t pw_shell_len = strlen (pwd->pw_shell) + 1;
175 char *cp;
176 const size_t key_len = strlen (key);
177 const size_t buf_len = 3 * sizeof (pwd->pw_uid) + key_len + 1;
178 char *buf = alloca (buf_len);
179 ssize_t n;
181 /* We need this to insert the `byuid' entry. */
182 int key_offset;
183 n = snprintf (buf, buf_len, "%d%c%n%s", pwd->pw_uid, '\0',
184 &key_offset, (char *) key) + 1;
186 total = (offsetof (struct dataset, strdata)
187 + pw_name_len + pw_passwd_len
188 + pw_gecos_len + pw_dir_len + pw_shell_len);
190 /* If we refill the cache, first assume the reconrd did not
191 change. Allocate memory on the cache since it is likely
192 discarded anyway. If it turns out to be necessary to have a
193 new record we can still allocate real memory. */
194 bool alloca_used = false;
195 dataset = NULL;
197 if (he == NULL)
199 /* Prevent an INVALIDATE request from pruning the data between
200 the two calls to cache_add. */
201 if (db->propagate)
202 pthread_mutex_lock (&db->prune_run_lock);
203 dataset = (struct dataset *) mempool_alloc (db, total + n, 1);
206 if (dataset == NULL)
208 if (he == NULL && db->propagate)
209 pthread_mutex_unlock (&db->prune_run_lock);
211 /* We cannot permanently add the result in the moment. But
212 we can provide the result as is. Store the data in some
213 temporary memory. */
214 dataset = (struct dataset *) alloca (total + n);
216 /* We cannot add this record to the permanent database. */
217 alloca_used = true;
220 timeout = datahead_init_pos (&dataset->head, total + n,
221 total - offsetof (struct dataset, resp),
222 he == NULL ? 0 : dh->nreloads + 1,
223 db->postimeout);
225 dataset->resp.version = NSCD_VERSION;
226 dataset->resp.found = 1;
227 dataset->resp.pw_name_len = pw_name_len;
228 dataset->resp.pw_passwd_len = pw_passwd_len;
229 dataset->resp.pw_uid = pwd->pw_uid;
230 dataset->resp.pw_gid = pwd->pw_gid;
231 dataset->resp.pw_gecos_len = pw_gecos_len;
232 dataset->resp.pw_dir_len = pw_dir_len;
233 dataset->resp.pw_shell_len = pw_shell_len;
235 cp = dataset->strdata;
237 /* Copy the strings over into the buffer. */
238 cp = mempcpy (cp, pwd->pw_name, pw_name_len);
239 cp = mempcpy (cp, pwd->pw_passwd, pw_passwd_len);
240 cp = mempcpy (cp, pwd->pw_gecos, pw_gecos_len);
241 cp = mempcpy (cp, pwd->pw_dir, pw_dir_len);
242 cp = mempcpy (cp, pwd->pw_shell, pw_shell_len);
244 /* Finally the stringified UID value. */
245 memcpy (cp, buf, n);
246 char *key_copy = cp + key_offset;
247 assert (key_copy == (char *) rawmemchr (cp, '\0') + 1);
249 assert (cp == dataset->strdata + total - offsetof (struct dataset,
250 strdata));
252 /* Now we can determine whether on refill we have to create a new
253 record or not. */
254 if (he != NULL)
256 assert (fd == -1);
258 if (dataset->head.allocsize == dh->allocsize
259 && dataset->head.recsize == dh->recsize
260 && memcmp (&dataset->resp, dh->data,
261 dh->allocsize - offsetof (struct dataset, resp)) == 0)
263 /* The data has not changed. We will just bump the
264 timeout value. Note that the new record has been
265 allocated on the stack and need not be freed. */
266 dh->timeout = dataset->head.timeout;
267 ++dh->nreloads;
269 else
271 /* We have to create a new record. Just allocate
272 appropriate memory and copy it. */
273 struct dataset *newp
274 = (struct dataset *) mempool_alloc (db, total + n, 1);
275 if (newp != NULL)
277 /* Adjust pointer into the memory block. */
278 cp = (char *) newp + (cp - (char *) dataset);
279 key_copy = (char *) newp + (key_copy - (char *) dataset);
281 dataset = memcpy (newp, dataset, total + n);
282 alloca_used = false;
285 /* Mark the old record as obsolete. */
286 dh->usable = false;
289 else
291 /* We write the dataset before inserting it to the database
292 since while inserting this thread might block and so would
293 unnecessarily let the receiver wait. */
294 assert (fd != -1);
296 if (writeall (fd, &dataset->resp, dataset->head.recsize)
297 != dataset->head.recsize)
298 all_written = false;
302 /* Add the record to the database. But only if it has not been
303 stored on the stack. */
304 if (! alloca_used)
306 /* If necessary, we also propagate the data to disk. */
307 if (db->persistent)
309 // XXX async OK?
310 uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1;
311 msync ((void *) pval,
312 ((uintptr_t) dataset & pagesize_m1) + total + n,
313 MS_ASYNC);
316 /* NB: in the following code we always must add the entry
317 marked with FIRST first. Otherwise we end up with
318 dangling "pointers" in case a latter hash entry cannot be
319 added. */
320 bool first = true;
322 /* If the request was by UID, add that entry first. */
323 if (req->type == GETPWBYUID)
325 if (cache_add (GETPWBYUID, cp, key_offset, &dataset->head, true,
326 db, owner, he == NULL) < 0)
327 goto out;
329 first = false;
331 /* If the key is different from the name add a separate entry. */
332 else if (strcmp (key_copy, dataset->strdata) != 0)
334 if (cache_add (GETPWBYNAME, key_copy, key_len + 1,
335 &dataset->head, true, db, owner, he == NULL) < 0)
336 goto out;
338 first = false;
341 /* We have to add the value for both, byname and byuid. */
342 if ((req->type == GETPWBYNAME || db->propagate)
343 && __builtin_expect (cache_add (GETPWBYNAME, dataset->strdata,
344 pw_name_len, &dataset->head,
345 first, db, owner, he == NULL)
346 == 0, 1))
348 if (req->type == GETPWBYNAME && db->propagate)
349 (void) cache_add (GETPWBYUID, cp, key_offset, &dataset->head,
350 false, db, owner, false);
353 out:
354 pthread_rwlock_unlock (&db->lock);
355 if (he == NULL && db->propagate)
356 pthread_mutex_unlock (&db->prune_run_lock);
360 if (__builtin_expect (!all_written, 0) && debug_level > 0)
362 char buf[256];
363 dbg_log (_("short write in %s: %s"), __FUNCTION__,
364 strerror_r (errno, buf, sizeof (buf)));
367 return timeout;
371 union keytype
373 void *v;
374 uid_t u;
378 static int
379 lookup (int type, union keytype key, struct passwd *resultbufp, char *buffer,
380 size_t buflen, struct passwd **pwd)
382 if (type == GETPWBYNAME)
383 return __getpwnam_r (key.v, resultbufp, buffer, buflen, pwd);
384 else
385 return __getpwuid_r (key.u, resultbufp, buffer, buflen, pwd);
389 static time_t
390 addpwbyX (struct database_dyn *db, int fd, request_header *req,
391 union keytype key, const char *keystr, uid_t c_uid,
392 struct hashentry *he, struct datahead *dh)
394 /* Search for the entry matching the key. Please note that we don't
395 look again in the table whether the dataset is now available. We
396 simply insert it. It does not matter if it is in there twice. The
397 pruning function only will look at the timestamp. */
398 size_t buflen = 1024;
399 char *buffer = (char *) alloca (buflen);
400 struct passwd resultbuf;
401 struct passwd *pwd;
402 bool use_malloc = false;
403 int errval = 0;
405 if (__glibc_unlikely (debug_level > 0))
407 if (he == NULL)
408 dbg_log (_("Haven't found \"%s\" in password cache!"), keystr);
409 else
410 dbg_log (_("Reloading \"%s\" in password cache!"), keystr);
413 while (lookup (req->type, key, &resultbuf, buffer, buflen, &pwd) != 0
414 && (errval = errno) == ERANGE)
416 errno = 0;
418 if (__glibc_unlikely (buflen > 32768))
420 char *old_buffer = buffer;
421 buflen *= 2;
422 buffer = (char *) realloc (use_malloc ? buffer : NULL, buflen);
423 if (buffer == NULL)
425 /* We ran out of memory. We cannot do anything but
426 sending a negative response. In reality this should
427 never happen. */
428 pwd = NULL;
429 buffer = old_buffer;
431 /* We set the error to indicate this is (possibly) a
432 temporary error and that it does not mean the entry
433 is not available at all. */
434 errval = EAGAIN;
435 break;
437 use_malloc = true;
439 else
440 /* Allocate a new buffer on the stack. If possible combine it
441 with the previously allocated buffer. */
442 buffer = (char *) extend_alloca (buffer, buflen, 2 * buflen);
445 /* Add the entry to the cache. */
446 time_t timeout = cache_addpw (db, fd, req, keystr, pwd, c_uid, he, dh,
447 errval);
449 if (use_malloc)
450 free (buffer);
452 return timeout;
456 void
457 addpwbyname (struct database_dyn *db, int fd, request_header *req,
458 void *key, uid_t c_uid)
460 union keytype u = { .v = key };
462 addpwbyX (db, fd, req, u, key, c_uid, NULL, NULL);
466 time_t
467 readdpwbyname (struct database_dyn *db, struct hashentry *he,
468 struct datahead *dh)
470 request_header req =
472 .type = GETPWBYNAME,
473 .key_len = he->len
475 union keytype u = { .v = db->data + he->key };
477 return addpwbyX (db, -1, &req, u, db->data + he->key, he->owner, he, dh);
481 void
482 addpwbyuid (struct database_dyn *db, int fd, request_header *req,
483 void *key, uid_t c_uid)
485 char *ep;
486 uid_t uid = strtoul ((char *) key, &ep, 10);
488 if (*(char *) key == '\0' || *ep != '\0') /* invalid numeric uid */
490 if (debug_level > 0)
491 dbg_log (_("Invalid numeric uid \"%s\"!"), (char *) key);
493 errno = EINVAL;
494 return;
497 union keytype u = { .u = uid };
499 addpwbyX (db, fd, req, u, key, c_uid, NULL, NULL);
503 time_t
504 readdpwbyuid (struct database_dyn *db, struct hashentry *he,
505 struct datahead *dh)
507 char *ep;
508 uid_t uid = strtoul (db->data + he->key, &ep, 10);
510 /* Since the key has been added before it must be OK. */
511 assert (*(db->data + he->key) != '\0' && *ep == '\0');
513 request_header req =
515 .type = GETPWBYUID,
516 .key_len = he->len
518 union keytype u = { .u = uid };
520 return addpwbyX (db, -1, &req, u, db->data + he->key, he->owner, he, dh);