fgetspent.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright (C) 1996-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 <shadow.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <set-freeres.h>
  20. /* A reasonable size for a buffer to start with. */
  21. #define BUFLEN_SPWD 1024
  22. /* We need to protect the dynamic buffer handling. */
  23. __libc_lock_define_initialized (static, lock);
  24. static char *buffer;
  25. /* Read one shadow entry from the given stream. */
  26. struct spwd *
  27. fgetspent (FILE *stream)
  28. {
  29. static size_t buffer_size;
  30. static struct spwd resbuf;
  31. fpos_t pos;
  32. struct spwd *result;
  33. int save;
  34. if (fgetpos (stream, &pos) != 0)
  35. return NULL;
  36. /* Get lock. */
  37. __libc_lock_lock (lock);
  38. /* Allocate buffer if not yet available. */
  39. if (buffer == NULL)
  40. {
  41. buffer_size = BUFLEN_SPWD;
  42. buffer = malloc (buffer_size);
  43. }
  44. while (buffer != NULL
  45. && (__fgetspent_r (stream, &resbuf, buffer, buffer_size, &result)
  46. == ERANGE))
  47. {
  48. char *new_buf;
  49. buffer_size += BUFLEN_SPWD;
  50. new_buf = realloc (buffer, buffer_size);
  51. if (new_buf == NULL)
  52. {
  53. /* We are out of memory. Free the current buffer so that the
  54. process gets a chance for a normal termination. */
  55. save = errno;
  56. free (buffer);
  57. __set_errno (save);
  58. }
  59. buffer = new_buf;
  60. /* Reset the stream. */
  61. if (fsetpos (stream, &pos) != 0)
  62. buffer = NULL;
  63. }
  64. if (buffer == NULL)
  65. result = NULL;
  66. /* Release lock. Preserve error value. */
  67. save = errno;
  68. __libc_lock_unlock (lock);
  69. __set_errno (save);
  70. return result;
  71. }
  72. weak_alias (buffer, __libc_fgetspent_freemem_ptr);