putgrent.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Copyright (C) 1991-2019 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. <http://www.gnu.org/licenses/>. */
  14. #include <errno.h>
  15. #include <nss.h>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <grp.h>
  19. #define flockfile(s) _IO_flockfile (s)
  20. #define funlockfile(s) _IO_funlockfile (s)
  21. #define _S(x) x ? x : ""
  22. /* Write an entry to the given stream.
  23. This must know the format of the group file. */
  24. int
  25. putgrent (const struct group *gr, FILE *stream)
  26. {
  27. int retval;
  28. if (__glibc_unlikely (gr == NULL) || __glibc_unlikely (stream == NULL)
  29. || gr->gr_name == NULL || !__nss_valid_field (gr->gr_name)
  30. || !__nss_valid_field (gr->gr_passwd)
  31. || !__nss_valid_list_field (gr->gr_mem))
  32. {
  33. __set_errno (EINVAL);
  34. return -1;
  35. }
  36. flockfile (stream);
  37. if (gr->gr_name[0] == '+' || gr->gr_name[0] == '-')
  38. retval = fprintf (stream, "%s:%s::",
  39. gr->gr_name, _S (gr->gr_passwd));
  40. else
  41. retval = fprintf (stream, "%s:%s:%lu:",
  42. gr->gr_name, _S (gr->gr_passwd),
  43. (unsigned long int) gr->gr_gid);
  44. if (__builtin_expect (retval, 0) < 0)
  45. {
  46. funlockfile (stream);
  47. return -1;
  48. }
  49. if (gr->gr_mem != NULL)
  50. {
  51. for (size_t i = 0; gr->gr_mem[i] != NULL; i++)
  52. if (fprintf (stream, i == 0 ? "%s" : ",%s", gr->gr_mem[i]) < 0)
  53. {
  54. /* What else can we do? */
  55. funlockfile (stream);
  56. return -1;
  57. }
  58. }
  59. retval = fputc_unlocked ('\n', stream);
  60. funlockfile (stream);
  61. return retval < 0 ? -1 : 0;
  62. }