winapi_common
sid.cpp
1 // Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
2 // This file is part of the "winapi-common" project.
3 // For details, see https://github.com/egor-tensin/winapi-common.
4 // Distributed under the MIT License.
5 
6 #include <winapi/buffer.hpp>
7 #include <winapi/error.hpp>
8 #include <winapi/sid.hpp>
9 #include <winapi/utf8.hpp>
10 #include <winapi/utils.hpp>
11 
12 // clang-format off
13 #include <windows.h>
14 #include <sddl.h>
15 // clang-format on
16 
17 #include <memory>
18 #include <string>
19 
20 namespace winapi {
21 
22 Sid Sid::well_known(WELL_KNOWN_SID_TYPE type) {
23  Buffer buffer;
24  buffer.resize(MAX_SID_SIZE);
25 
26  auto cb = static_cast<DWORD>(buffer.size());
27 
28  if (!::CreateWellKnownSid(type, NULL, buffer.data(), &cb))
29  throw error::windows(GetLastError(), "CreateWellKnownSid");
30 
31  buffer.resize(cb);
32  return Sid{buffer};
33 }
34 
35 Sid Sid::builtin_administrators() {
36  return well_known(WinBuiltinAdministratorsSid);
37 }
38 
39 std::string Sid::to_string() const {
40  wchar_t* s = nullptr;
41 
42  if (!::ConvertSidToStringSidW(const_cast<Impl*>(&get_impl()), &s))
43  throw error::windows(GetLastError(), "ConvertSidToStringSidW");
44 
45  return narrow(std::unique_ptr<wchar_t, LocalDelete>{s}.get());
46 }
47 
48 } // namespace winapi
Make std::system_error work with GetLastError().