user.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "user.h"
  2. #include "env.h"
  3. #include <util/generic/yexception.h>
  4. #ifdef _win_
  5. #include "winint.h"
  6. #else
  7. #include <cerrno>
  8. #include <pwd.h>
  9. #include <unistd.h>
  10. #endif
  11. TString GetUsername() {
  12. for (const auto& var : {"LOGNAME", "USER", "LNAME", "USERNAME"}) {
  13. TString val = GetEnv(var);
  14. if (val) {
  15. return val;
  16. }
  17. }
  18. TTempBuf nameBuf;
  19. for (;;) {
  20. #if defined(_win_)
  21. DWORD len = (DWORD)Min(nameBuf.Size(), size_t(32767));
  22. if (!GetUserNameA(nameBuf.Data(), &len)) {
  23. DWORD err = GetLastError();
  24. if ((err == ERROR_INSUFFICIENT_BUFFER) && (nameBuf.Size() <= 32767))
  25. nameBuf = TTempBuf((size_t)len);
  26. else
  27. ythrow TSystemError(err) << " GetUserName failed";
  28. } else {
  29. return TString(nameBuf.Data(), (size_t)(len - 1));
  30. }
  31. #elif defined(_bionic_)
  32. const passwd* pwd = getpwuid(geteuid());
  33. if (pwd) {
  34. return TString(pwd->pw_name);
  35. }
  36. ythrow TSystemError() << TStringBuf(" getpwuid failed");
  37. #else
  38. passwd pwd;
  39. passwd* tmpPwd;
  40. int err = getpwuid_r(geteuid(), &pwd, nameBuf.Data(), nameBuf.Size(), &tmpPwd);
  41. if (err == 0 && tmpPwd) {
  42. return TString(pwd.pw_name);
  43. } else if (err == ERANGE) {
  44. nameBuf = TTempBuf(nameBuf.Size() * 2);
  45. } else {
  46. ythrow TSystemError(err) << " getpwuid_r failed";
  47. }
  48. #endif
  49. }
  50. }