get_username.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Implementation of get_username() for Unix.
  3. */
  4. #include <unistd.h>
  5. #include <pwd.h>
  6. #include "putty.h"
  7. char *get_username(void)
  8. {
  9. struct passwd *p;
  10. uid_t uid = getuid();
  11. char *user, *ret = NULL;
  12. /*
  13. * First, find who we think we are using getlogin. If this
  14. * agrees with our uid, we'll go along with it. This should
  15. * allow sharing of uids between several login names whilst
  16. * coping correctly with people who have su'ed.
  17. */
  18. user = getlogin();
  19. #if HAVE_SETPWENT
  20. setpwent();
  21. #endif
  22. if (user)
  23. p = getpwnam(user);
  24. else
  25. p = NULL;
  26. if (p && p->pw_uid == uid) {
  27. /*
  28. * The result of getlogin() really does correspond to
  29. * our uid. Fine.
  30. */
  31. ret = user;
  32. } else {
  33. /*
  34. * If that didn't work, for whatever reason, we'll do
  35. * the simpler version: look up our uid in the password
  36. * file and map it straight to a name.
  37. */
  38. p = getpwuid(uid);
  39. if (!p)
  40. return NULL;
  41. ret = p->pw_name;
  42. }
  43. #if HAVE_ENDPWENT
  44. endpwent();
  45. #endif
  46. return dupstr(ret);
  47. }