winget-cli

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

Utils.cpp (1591B)


      1 // Copyright (c) Microsoft Corporation.
      2 // Licensed under the MIT License.
      3 #include "Utils.h"
      4 #pragma warning( push )
      5 #pragma warning ( disable : 6001 6388 6553)
      6 #include <wil/resource.h>
      7 #pragma warning( pop )
      8 #include <processthreadsapi.h>
      9 #include <sddl.h>
     10 #include <vector>
     11 
     12 unsigned char* GetUCharString(const std::string& str)
     13 {
     14     return reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
     15 }
     16 
     17 std::string GetUserSID()
     18 {
     19     HANDLE hToken = NULL;
     20     THROW_LAST_ERROR_IF(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken));
     21 
     22     DWORD dwBufferSize = 0;
     23     THROW_LAST_ERROR_IF(!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwBufferSize) && GetLastError() != ERROR_INSUFFICIENT_BUFFER);
     24 
     25     std::vector<BYTE> buffer;
     26     buffer.resize(dwBufferSize);
     27     PTOKEN_USER pTokenUser = reinterpret_cast<PTOKEN_USER>(&buffer[0]);
     28 
     29     THROW_LAST_ERROR_IF(!GetTokenInformation(hToken, TokenUser, pTokenUser, dwBufferSize, &dwBufferSize));
     30     THROW_HR_IF(CO_E_INVALIDSID, !IsValidSid(pTokenUser->User.Sid));
     31 
     32     LPSTR pszSID = NULL;
     33     THROW_LAST_ERROR_IF(!ConvertSidToStringSidA(pTokenUser->User.Sid, &pszSID));
     34     return std::string{ pszSID };
     35 }
     36 
     37 wil::unique_event CreateOrOpenServerStartEvent()
     38 {
     39     wil::unique_event result;
     40 
     41     for (int i = 0; !result && i < 2; ++i)
     42     {
     43         if (!result.try_create(wil::EventOptions::ManualReset, L"WinGetServerStartEvent"))
     44         {
     45             result.try_open(L"WinGetServerStartEvent");
     46         }
     47     }
     48 
     49     THROW_LAST_ERROR_IF(!result);
     50 
     51     return result;
     52 }