PageRenderTime 61ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/common/username.c

https://github.com/larkly/postgres-docker
C | 87 lines | 52 code | 14 blank | 21 comment | 3 complexity | 19118fc4b841831852626472e098bb99 MD5 | raw file
Possible License(s): AGPL-3.0
  1. /*-------------------------------------------------------------------------
  2. *
  3. * username.c
  4. * get user name
  5. *
  6. * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
  7. * Portions Copyright (c) 1994, Regents of the University of California
  8. *
  9. * IDENTIFICATION
  10. * src/common/username.c
  11. *
  12. *-------------------------------------------------------------------------
  13. */
  14. #ifndef FRONTEND
  15. #include "postgres.h"
  16. #else
  17. #include "postgres_fe.h"
  18. #endif
  19. #include <errno.h>
  20. #include <pwd.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>
  23. #include "common/username.h"
  24. /*
  25. * Returns the current user name in a static buffer, or NULL on error and
  26. * sets errstr
  27. */
  28. const char *
  29. get_user_name(char **errstr)
  30. {
  31. #ifndef WIN32
  32. struct passwd *pw;
  33. uid_t user_id = geteuid();
  34. *errstr = NULL;
  35. errno = 0; /* clear errno before call */
  36. pw = getpwuid(user_id);
  37. if (!pw)
  38. {
  39. *errstr = psprintf(_("failed to look up effective user id %ld: %s"),
  40. (long) user_id,
  41. errno ? strerror(errno) : _("user does not exist"));
  42. return NULL;
  43. }
  44. return pw->pw_name;
  45. #else
  46. /* UNLEN = 256, 'static' variable remains after function exit */
  47. static char username[256 + 1];
  48. DWORD len = sizeof(username) - 1;
  49. *errstr = NULL;
  50. if (!GetUserName(username, &len))
  51. {
  52. *errstr = psprintf(_("user name lookup failure: %s"), strerror(errno));
  53. return NULL;
  54. }
  55. return username;
  56. #endif
  57. }
  58. /*
  59. * Returns the current user name in a static buffer or exits
  60. */
  61. const char *
  62. get_user_name_or_exit(const char *progname)
  63. {
  64. const char *user_name;
  65. char *errstr;
  66. user_name = get_user_name(&errstr);
  67. if (!user_name)
  68. {
  69. fprintf(stderr, "%s: %s\n", progname, errstr);
  70. exit(1);
  71. }
  72. return user_name;
  73. }