Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.2 KiB

  1. // Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved
  2. // CImpersonate class implementation
  3. // Created: 6/3/2000
  4. // Author: khughes
  5. #include <precomp.h>
  6. #include <chstring.h>
  7. #include "AutoImpRevert.h"
  8. CAutoImpRevert::CAutoImpRevert(
  9. BOOL fOpenAsSelf)
  10. : m_hOriginalUser(INVALID_HANDLE_VALUE),
  11. m_dwLastError(ERROR_SUCCESS)
  12. {
  13. GetCurrentImpersonation(fOpenAsSelf);
  14. }
  15. CAutoImpRevert::~CAutoImpRevert()
  16. {
  17. if(m_hOriginalUser != INVALID_HANDLE_VALUE)
  18. {
  19. Revert();
  20. }
  21. }
  22. bool CAutoImpRevert::GetCurrentImpersonation(
  23. BOOL fOpenAsSelf)
  24. {
  25. bool fRet = false;
  26. ::SetLastError(ERROR_SUCCESS);
  27. m_dwLastError = ERROR_SUCCESS;
  28. // Store the current user's handle...
  29. if(::OpenThreadToken(
  30. ::GetCurrentThread(),
  31. TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE,
  32. fOpenAsSelf,
  33. &m_hOriginalUser))
  34. {
  35. fRet = true;
  36. }
  37. else
  38. {
  39. m_dwLastError = ::GetLastError();
  40. if(m_dwLastError == ERROR_NO_TOKEN)
  41. {
  42. ::SetLastError(ERROR_SUCCESS);
  43. if(::ImpersonateSelf(SecurityImpersonation))
  44. {
  45. if(::OpenThreadToken(
  46. ::GetCurrentThread(),
  47. TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE,
  48. fOpenAsSelf,
  49. &m_hOriginalUser))
  50. {
  51. fRet = true;
  52. m_dwLastError = ERROR_SUCCESS;
  53. }
  54. else
  55. {
  56. m_dwLastError = ::GetLastError();
  57. }
  58. }
  59. else
  60. {
  61. m_dwLastError = ::GetLastError();
  62. }
  63. }
  64. }
  65. return fRet;
  66. }
  67. bool CAutoImpRevert::Revert()
  68. {
  69. bool fRet = false;
  70. if(m_hOriginalUser != INVALID_HANDLE_VALUE)
  71. {
  72. if(::ImpersonateLoggedOnUser(m_hOriginalUser))
  73. {
  74. CloseHandle(m_hOriginalUser);
  75. m_hOriginalUser = INVALID_HANDLE_VALUE;
  76. fRet = true;
  77. }
  78. else
  79. {
  80. m_dwLastError = ::GetLastError();
  81. }
  82. }
  83. return fRet;
  84. }
  85. DWORD CAutoImpRevert::LastError() const
  86. {
  87. return m_dwLastError;
  88. }