fgetpwent.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright (C) 1991-2026 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <https://www.gnu.org/licenses/>. */
  14. #include <errno.h>
  15. #include <libc-lock.h>
  16. #include <pwd.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <set-freeres.h>
  20. /* We need to protect the dynamic buffer handling. */
  21. __libc_lock_define_initialized (static, lock);
  22. static char *buffer;
  23. /* Read one entry from the given stream. */
  24. struct passwd *
  25. fgetpwent (FILE *stream)
  26. {
  27. static size_t buffer_size;
  28. static struct passwd resbuf;
  29. fpos_t pos;
  30. struct passwd *result;
  31. int save;
  32. if (fgetpos (stream, &pos) != 0)
  33. return NULL;
  34. /* Get lock. */
  35. __libc_lock_lock (lock);
  36. /* Allocate buffer if not yet available. */
  37. if (buffer == NULL)
  38. {
  39. buffer_size = NSS_BUFLEN_PASSWD;
  40. buffer = malloc (buffer_size);
  41. }
  42. while (buffer != NULL
  43. && (__fgetpwent_r (stream, &resbuf, buffer, buffer_size, &result)
  44. == ERANGE))
  45. {
  46. char *new_buf;
  47. buffer_size += NSS_BUFLEN_PASSWD;
  48. new_buf = realloc (buffer, buffer_size);
  49. if (new_buf == NULL)
  50. {
  51. /* We are out of memory. Free the current buffer so that the
  52. process gets a chance for a normal termination. */
  53. save = errno;
  54. free (buffer);
  55. __set_errno (save);
  56. }
  57. buffer = new_buf;
  58. /* Reset the stream. */
  59. if (fsetpos (stream, &pos) != 0)
  60. buffer = NULL;
  61. }
  62. if (buffer == NULL)
  63. result = NULL;
  64. /* Release lock. Preserve error value. */
  65. save = errno;
  66. __libc_lock_unlock (lock);
  67. __set_errno (save);
  68. return result;
  69. }
  70. weak_alias (buffer, __libc_fgetpwent_freemem_ptr)