bb_pwd.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * password utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. * Copyright (C) 2008 by Tito Ragusa <farmatito@tiscali.it>
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. #include "libbb.h"
  11. /* TODO: maybe change API to return malloced data?
  12. * This will allow to stop using libc functions returning
  13. * pointers to static data (getpwuid)
  14. */
  15. struct passwd* FAST_FUNC xgetpwnam(const char *name)
  16. {
  17. struct passwd *pw = getpwnam(name);
  18. if (!pw)
  19. bb_error_msg_and_die("unknown user %s", name);
  20. return pw;
  21. }
  22. struct group* FAST_FUNC xgetgrnam(const char *name)
  23. {
  24. struct group *gr = getgrnam(name);
  25. if (!gr)
  26. bb_error_msg_and_die("unknown group %s", name);
  27. return gr;
  28. }
  29. struct passwd* FAST_FUNC xgetpwuid(uid_t uid)
  30. {
  31. struct passwd *pw = getpwuid(uid);
  32. if (!pw)
  33. bb_error_msg_and_die("unknown uid %u", (unsigned)uid);
  34. return pw;
  35. }
  36. struct group* FAST_FUNC xgetgrgid(gid_t gid)
  37. {
  38. struct group *gr = getgrgid(gid);
  39. if (!gr)
  40. bb_error_msg_and_die("unknown gid %u", (unsigned)gid);
  41. return gr;
  42. }
  43. char* FAST_FUNC xuid2uname(uid_t uid)
  44. {
  45. struct passwd *pw = xgetpwuid(uid);
  46. return pw->pw_name;
  47. }
  48. char* FAST_FUNC xgid2group(gid_t gid)
  49. {
  50. struct group *gr = xgetgrgid(gid);
  51. return gr->gr_name;
  52. }
  53. char* FAST_FUNC uid2uname(uid_t uid)
  54. {
  55. struct passwd *pw = getpwuid(uid);
  56. return (pw) ? pw->pw_name : NULL;
  57. }
  58. char* FAST_FUNC gid2group(gid_t gid)
  59. {
  60. struct group *gr = getgrgid(gid);
  61. return (gr) ? gr->gr_name : NULL;
  62. }
  63. char* FAST_FUNC uid2uname_utoa(long uid)
  64. {
  65. char *name = uid2uname(uid);
  66. return (name) ? name : utoa(uid);
  67. }
  68. char* FAST_FUNC gid2group_utoa(long gid)
  69. {
  70. char *name = gid2group(gid);
  71. return (name) ? name : utoa(gid);
  72. }
  73. long FAST_FUNC xuname2uid(const char *name)
  74. {
  75. struct passwd *myuser;
  76. myuser = xgetpwnam(name);
  77. return myuser->pw_uid;
  78. }
  79. long FAST_FUNC xgroup2gid(const char *name)
  80. {
  81. struct group *mygroup;
  82. mygroup = xgetgrnam(name);
  83. return mygroup->gr_gid;
  84. }
  85. unsigned long FAST_FUNC get_ug_id(const char *s,
  86. long FAST_FUNC (*xname2id)(const char *))
  87. {
  88. unsigned long r;
  89. r = bb_strtoul(s, NULL, 10);
  90. if (errno)
  91. return xname2id(s);
  92. return r;
  93. }