PageRenderTime 115ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/common/username.c

http://github.com/postgres/postgres
C | 87 lines | 51 code | 14 blank | 22 comment | 3 complexity | 7819ff66916951742159ea8461a4fbc3 MD5 | raw file
Possible License(s): AGPL-3.0
  1. /*-------------------------------------------------------------------------
  2. *
  3. * username.c
  4. * get user name
  5. *
  6. * Portions Copyright (c) 1996-2020, 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 <pwd.h>
  20. #include <unistd.h>
  21. #include "common/username.h"
  22. /*
  23. * Returns the current user name in a static buffer
  24. * On error, returns NULL and sets *errstr to point to a palloc'd message
  25. */
  26. const char *
  27. get_user_name(char **errstr)
  28. {
  29. #ifndef WIN32
  30. struct passwd *pw;
  31. uid_t user_id = geteuid();
  32. *errstr = NULL;
  33. errno = 0; /* clear errno before call */
  34. pw = getpwuid(user_id);
  35. if (!pw)
  36. {
  37. *errstr = psprintf(_("could not look up effective user ID %ld: %s"),
  38. (long) user_id,
  39. errno ? strerror(errno) : _("user does not exist"));
  40. return NULL;
  41. }
  42. return pw->pw_name;
  43. #else
  44. /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
  45. /* "static" variable remains after function exit */
  46. static char username[256 + 1];
  47. DWORD len = sizeof(username);
  48. *errstr = NULL;
  49. if (!GetUserName(username, &len))
  50. {
  51. *errstr = psprintf(_("user name lookup failure: error code %lu"),
  52. GetLastError());
  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. }