sgetspent.c 2.1 KB

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