monitor: Fix tracepoint crash on JSON syntax error
[qemu/armbru.git] / qga / vss-win32 / install.cpp
blob6713e58670f3ff0626f8b2cb82520a4c24629a21
1 /*
2 * QEMU Guest Agent win32 VSS Provider installer
4 * Copyright Hitachi Data Systems Corp. 2013
6 * Authors:
7 * Tomoki Sekiyama <tomoki.sekiyama@hds.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
15 #include "vss-common.h"
16 #include <inc/win2003/vscoordint.h>
17 #include "install.h"
18 #include <wbemidl.h>
19 #include <comdef.h>
20 #include <comutil.h>
21 #include <sddl.h>
23 #define BUFFER_SIZE 1024
25 extern HINSTANCE g_hinstDll;
27 const GUID CLSID_COMAdminCatalog = { 0xF618C514, 0xDFB8, 0x11d1,
28 {0xA2, 0xCF, 0x00, 0x80, 0x5F, 0xC7, 0x92, 0x35} };
29 const GUID IID_ICOMAdminCatalog2 = { 0x790C6E0B, 0x9194, 0x4cc9,
30 {0x94, 0x26, 0xA4, 0x8A, 0x63, 0x18, 0x56, 0x96} };
31 const GUID CLSID_WbemLocator = { 0x4590f811, 0x1d3a, 0x11d0,
32 {0x89, 0x1f, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24} };
33 const GUID IID_IWbemLocator = { 0xdc12a687, 0x737f, 0x11cf,
34 {0x88, 0x4d, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24} };
36 void errmsg(DWORD err, const char *text)
39 * `text' contains function call statement when errmsg is called via chk().
40 * To make error message more readable, we cut off the text after '('.
41 * If text doesn't contains '(', negative precision is given, which is
42 * treated as though it were missing.
44 char *msg = NULL, *nul = strchr(text, '(');
45 int len = nul ? nul - text : -1;
47 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
48 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
49 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
50 (char *)&msg, 0, NULL);
51 fprintf(stderr, "%.*s. (Error: %lx) %s\n", len, text, err, msg);
52 LocalFree(msg);
55 static void errmsg_dialog(DWORD err, const char *text, const char *opt = "")
57 char *msg, buf[512];
59 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
60 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
61 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
62 (char *)&msg, 0, NULL);
63 snprintf(buf, sizeof(buf), "%s%s. (Error: %lx) %s", text, opt, err, msg);
64 MessageBox(NULL, buf, "Error from " QGA_PROVIDER_NAME, MB_OK|MB_ICONERROR);
65 LocalFree(msg);
68 #define _chk(hr, status, msg, err_label) \
69 do { \
70 hr = (status); \
71 if (FAILED(hr)) { \
72 errmsg(hr, msg); \
73 goto err_label; \
74 } \
75 } while (0)
77 #define chk(status) _chk(hr, status, "Failed to " #status, out)
79 #if !defined(__MINGW64_VERSION_MAJOR) || !defined(__MINGW64_VERSION_MINOR) || \
80 __MINGW64_VERSION_MAJOR * 100 + __MINGW64_VERSION_MINOR < 301
81 void __stdcall _com_issue_error(HRESULT hr)
83 errmsg(hr, "Unexpected error in COM");
85 #endif
87 template<class T>
88 HRESULT put_Value(ICatalogObject *pObj, LPCWSTR name, T val)
90 return pObj->put_Value(_bstr_t(name), _variant_t(val));
93 /* Lookup Administrators group name from winmgmt */
94 static HRESULT GetAdminName(_bstr_t *name)
96 HRESULT hr;
97 COMPointer<IWbemLocator> pLoc;
98 COMPointer<IWbemServices> pSvc;
99 COMPointer<IEnumWbemClassObject> pEnum;
100 COMPointer<IWbemClassObject> pWobj;
101 ULONG returned;
102 _variant_t var;
104 chk(CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER,
105 IID_IWbemLocator, (LPVOID *)pLoc.replace()));
106 chk(pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, NULL,
107 0, 0, 0, pSvc.replace()));
108 chk(CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
109 NULL, RPC_C_AUTHN_LEVEL_CALL,
110 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE));
111 chk(pSvc->ExecQuery(_bstr_t(L"WQL"),
112 _bstr_t(L"select * from Win32_Account where "
113 "SID='S-1-5-32-544' and localAccount=TRUE"),
114 WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
115 NULL, pEnum.replace()));
116 if (!pEnum) {
117 hr = E_FAIL;
118 errmsg(hr, "Failed to query for Administrators");
119 goto out;
121 chk(pEnum->Next(WBEM_INFINITE, 1, pWobj.replace(), &returned));
122 if (returned == 0) {
123 hr = E_FAIL;
124 errmsg(hr, "No Administrators found");
125 goto out;
128 chk(pWobj->Get(_bstr_t(L"Name"), 0, &var, 0, 0));
129 try {
130 *name = var;
131 } catch(...) {
132 hr = E_FAIL;
133 errmsg(hr, "Failed to get name of Administrators");
134 goto out;
137 out:
138 return hr;
141 /* Acquire group or user name by SID */
142 static HRESULT getNameByStringSID(
143 const wchar_t *sid, LPWSTR buffer, LPDWORD bufferLen)
145 HRESULT hr = S_OK;
146 PSID psid = NULL;
147 SID_NAME_USE groupType;
148 DWORD domainNameLen = BUFFER_SIZE;
149 wchar_t domainName[BUFFER_SIZE];
151 if (!ConvertStringSidToSidW(sid, &psid)) {
152 hr = HRESULT_FROM_WIN32(GetLastError());
153 goto out;
155 if (!LookupAccountSidW(NULL, psid, buffer, bufferLen,
156 domainName, &domainNameLen, &groupType)) {
157 hr = HRESULT_FROM_WIN32(GetLastError());
158 /* Fall through and free psid */
161 LocalFree(psid);
163 out:
164 return hr;
167 /* Find and iterate QGA VSS provider in COM+ Application Catalog */
168 static HRESULT QGAProviderFind(
169 HRESULT (*found)(ICatalogCollection *, int, void *), void *arg)
171 HRESULT hr;
172 COMInitializer initializer;
173 COMPointer<IUnknown> pUnknown;
174 COMPointer<ICOMAdminCatalog2> pCatalog;
175 COMPointer<ICatalogCollection> pColl;
176 COMPointer<ICatalogObject> pObj;
177 _variant_t var;
178 long i, n;
180 chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
181 IID_IUnknown, (void **)pUnknown.replace()));
182 chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
183 (void **)pCatalog.replace()));
184 chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
185 (IDispatch **)pColl.replace()));
186 chk(pColl->Populate());
188 chk(pColl->get_Count(&n));
189 for (i = n - 1; i >= 0; i--) {
190 chk(pColl->get_Item(i, (IDispatch **)pObj.replace()));
191 chk(pObj->get_Value(_bstr_t(L"Name"), &var));
192 if (var == _variant_t(QGA_PROVIDER_LNAME)) {
193 if (FAILED(found(pColl, i, arg))) {
194 goto out;
198 chk(pColl->SaveChanges(&n));
200 out:
201 return hr;
204 /* Count QGA VSS provider in COM+ Application Catalog */
205 static HRESULT QGAProviderCount(ICatalogCollection *coll, int i, void *arg)
207 (*(int *)arg)++;
208 return S_OK;
211 /* Remove QGA VSS provider from COM+ Application Catalog Collection */
212 static HRESULT QGAProviderRemove(ICatalogCollection *coll, int i, void *arg)
214 HRESULT hr;
216 fprintf(stderr, "Removing COM+ Application: %s\n", QGA_PROVIDER_NAME);
217 chk(coll->Remove(i));
218 out:
219 return hr;
222 /* Unregister this module from COM+ Applications Catalog */
223 STDAPI COMUnregister(void)
225 HRESULT hr;
227 DllUnregisterServer();
228 chk(QGAProviderFind(QGAProviderRemove, NULL));
229 out:
230 return hr;
233 /* Register this module to COM+ Applications Catalog */
234 STDAPI COMRegister(void)
236 HRESULT hr;
237 COMInitializer initializer;
238 COMPointer<IUnknown> pUnknown;
239 COMPointer<ICOMAdminCatalog2> pCatalog;
240 COMPointer<ICatalogCollection> pApps, pRoles, pUsersInRole;
241 COMPointer<ICatalogObject> pObj;
242 long n;
243 _bstr_t name;
244 _variant_t key;
245 CHAR dllPath[MAX_PATH], tlbPath[MAX_PATH];
246 bool unregisterOnFailure = false;
247 int count = 0;
248 DWORD bufferLen = BUFFER_SIZE;
249 wchar_t buffer[BUFFER_SIZE];
250 const wchar_t *administratorsGroupSID = L"S-1-5-32-544";
251 const wchar_t *systemUserSID = L"S-1-5-18";
253 if (!g_hinstDll) {
254 errmsg(E_FAIL, "Failed to initialize DLL");
255 return E_FAIL;
258 chk(QGAProviderFind(QGAProviderCount, (void *)&count));
259 if (count) {
260 errmsg(E_ABORT, "QGA VSS Provider is already installed");
261 return E_ABORT;
264 chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
265 IID_IUnknown, (void **)pUnknown.replace()));
266 chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
267 (void **)pCatalog.replace()));
269 /* Install COM+ Component */
271 chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
272 (IDispatch **)pApps.replace()));
273 chk(pApps->Populate());
274 chk(pApps->Add((IDispatch **)&pObj));
275 chk(put_Value(pObj, L"Name", QGA_PROVIDER_LNAME));
276 chk(put_Value(pObj, L"Description", QGA_PROVIDER_LNAME));
277 chk(put_Value(pObj, L"ApplicationAccessChecksEnabled", true));
278 chk(put_Value(pObj, L"Authentication", short(6)));
279 chk(put_Value(pObj, L"AuthenticationCapability", short(2)));
280 chk(put_Value(pObj, L"ImpersonationLevel", short(2)));
281 chk(pApps->SaveChanges(&n));
283 /* The app should be deleted if something fails after SaveChanges */
284 unregisterOnFailure = true;
286 chk(pObj->get_Key(&key));
288 if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
289 hr = HRESULT_FROM_WIN32(GetLastError());
290 errmsg(hr, "GetModuleFileName failed");
291 goto out;
293 n = strlen(dllPath);
294 if (n < 3) {
295 hr = E_FAIL;
296 errmsg(hr, "Failed to lookup dll");
297 goto out;
299 strcpy(tlbPath, dllPath);
300 strcpy(tlbPath+n-3, "tlb");
301 fprintf(stderr, "Registering " QGA_PROVIDER_NAME ":\n");
302 fprintf(stderr, " %s\n", dllPath);
303 fprintf(stderr, " %s\n", tlbPath);
304 if (!PathFileExists(tlbPath)) {
305 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
306 errmsg(hr, "Failed to lookup tlb");
307 goto out;
310 chk(pCatalog->CreateServiceForApplication(
311 _bstr_t(QGA_PROVIDER_LNAME), _bstr_t(QGA_PROVIDER_LNAME),
312 _bstr_t(L"SERVICE_DEMAND_START"), _bstr_t(L"SERVICE_ERROR_NORMAL"),
313 _bstr_t(L""), _bstr_t(L".\\localsystem"), _bstr_t(L""), FALSE));
314 chk(pCatalog->InstallComponent(_bstr_t(QGA_PROVIDER_LNAME),
315 _bstr_t(dllPath), _bstr_t(tlbPath),
316 _bstr_t("")));
318 /* Setup roles of the applicaion */
320 chk(getNameByStringSID(administratorsGroupSID, buffer, &bufferLen));
321 chk(pApps->GetCollection(_bstr_t(L"Roles"), key,
322 (IDispatch **)pRoles.replace()));
323 chk(pRoles->Populate());
324 chk(pRoles->Add((IDispatch **)pObj.replace()));
325 chk(put_Value(pObj, L"Name", buffer));
326 chk(put_Value(pObj, L"Description", L"Administrators group"));
327 chk(pRoles->SaveChanges(&n));
328 chk(pObj->get_Key(&key));
330 /* Setup users in the role */
332 chk(pRoles->GetCollection(_bstr_t(L"UsersInRole"), key,
333 (IDispatch **)pUsersInRole.replace()));
334 chk(pUsersInRole->Populate());
336 chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
337 chk(GetAdminName(&name));
338 chk(put_Value(pObj, L"User", _bstr_t(".\\") + name));
340 bufferLen = BUFFER_SIZE;
341 chk(getNameByStringSID(systemUserSID, buffer, &bufferLen));
342 chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
343 chk(put_Value(pObj, L"User", buffer));
344 chk(pUsersInRole->SaveChanges(&n));
346 out:
347 if (unregisterOnFailure && FAILED(hr)) {
348 COMUnregister();
351 return hr;
355 static BOOL CreateRegistryKey(LPCTSTR key, LPCTSTR value, LPCTSTR data)
357 HKEY hKey;
358 LONG ret;
359 DWORD size;
361 ret = RegCreateKeyEx(HKEY_CLASSES_ROOT, key, 0, NULL,
362 REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
363 if (ret != ERROR_SUCCESS) {
364 goto out;
367 if (data != NULL) {
368 size = strlen(data) + 1;
369 } else {
370 size = 0;
373 ret = RegSetValueEx(hKey, value, 0, REG_SZ, (LPBYTE)data, size);
374 RegCloseKey(hKey);
376 out:
377 if (ret != ERROR_SUCCESS) {
378 /* As we cannot printf within DllRegisterServer(), show a dialog. */
379 errmsg_dialog(ret, "Cannot add registry", key);
380 return FALSE;
382 return TRUE;
385 /* Register this dll as a VSS provider */
386 STDAPI DllRegisterServer(void)
388 COMInitializer initializer;
389 COMPointer<IVssAdmin> pVssAdmin;
390 HRESULT hr = E_FAIL;
391 char dllPath[MAX_PATH];
392 char key[256];
394 if (!g_hinstDll) {
395 errmsg_dialog(hr, "Module instance is not available");
396 goto out;
399 /* Add this module to registery */
401 sprintf(key, "CLSID\\%s", g_szClsid);
402 if (!CreateRegistryKey(key, NULL, g_szClsid)) {
403 goto out;
406 if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
407 errmsg_dialog(GetLastError(), "GetModuleFileName failed");
408 goto out;
411 sprintf(key, "CLSID\\%s\\InprocServer32", g_szClsid);
412 if (!CreateRegistryKey(key, NULL, dllPath)) {
413 goto out;
416 if (!CreateRegistryKey(key, "ThreadingModel", "Apartment")) {
417 goto out;
420 sprintf(key, "CLSID\\%s\\ProgID", g_szClsid);
421 if (!CreateRegistryKey(key, NULL, g_szProgid)) {
422 goto out;
425 if (!CreateRegistryKey(g_szProgid, NULL, QGA_PROVIDER_NAME)) {
426 goto out;
429 sprintf(key, "%s\\CLSID", g_szProgid);
430 if (!CreateRegistryKey(key, NULL, g_szClsid)) {
431 goto out;
434 hr = CoCreateInstance(CLSID_VSSCoordinator, NULL, CLSCTX_ALL,
435 IID_IVssAdmin, (void **)pVssAdmin.replace());
436 if (FAILED(hr)) {
437 errmsg_dialog(hr, "CoCreateInstance(VSSCoordinator) failed");
438 goto out;
441 hr = pVssAdmin->RegisterProvider(g_gProviderId, CLSID_QGAVSSProvider,
442 const_cast<WCHAR*>(QGA_PROVIDER_LNAME),
443 VSS_PROV_SOFTWARE,
444 const_cast<WCHAR*>(QGA_PROVIDER_VERSION),
445 g_gProviderVersion);
446 if (FAILED(hr)) {
447 errmsg_dialog(hr, "RegisterProvider failed");
450 out:
451 if (FAILED(hr)) {
452 DllUnregisterServer();
455 return hr;
458 /* Unregister this VSS hardware provider from the system */
459 STDAPI DllUnregisterServer(void)
461 TCHAR key[256];
462 COMInitializer initializer;
463 COMPointer<IVssAdmin> pVssAdmin;
465 HRESULT hr = CoCreateInstance(CLSID_VSSCoordinator,
466 NULL, CLSCTX_ALL, IID_IVssAdmin,
467 (void **)pVssAdmin.replace());
468 if (SUCCEEDED(hr)) {
469 hr = pVssAdmin->UnregisterProvider(g_gProviderId);
470 } else {
471 errmsg(hr, "CoCreateInstance(VSSCoordinator) failed");
474 sprintf(key, "CLSID\\%s", g_szClsid);
475 SHDeleteKey(HKEY_CLASSES_ROOT, key);
476 SHDeleteKey(HKEY_CLASSES_ROOT, g_szProgid);
478 return S_OK; /* Uninstall should never fail */
482 /* Support function to convert ASCII string into BSTR (used in _bstr_t) */
483 namespace _com_util
485 BSTR WINAPI ConvertStringToBSTR(const char *ascii) {
486 int len = strlen(ascii);
487 BSTR bstr = SysAllocStringLen(NULL, len);
489 if (!bstr) {
490 return NULL;
493 if (mbstowcs(bstr, ascii, len) == (size_t)-1) {
494 fprintf(stderr, "Failed to convert string '%s' into BSTR", ascii);
495 bstr[0] = 0;
497 return bstr;
501 /* Stop QGA VSS provider service from COM+ Application Admin Catalog */
503 STDAPI StopService(void)
505 HRESULT hr;
506 COMInitializer initializer;
507 COMPointer<IUnknown> pUnknown;
508 COMPointer<ICOMAdminCatalog2> pCatalog;
510 int count = 0;
512 chk(QGAProviderFind(QGAProviderCount, (void *)&count));
513 if (count) {
514 chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
515 IID_IUnknown, (void **)pUnknown.replace()));
516 chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
517 (void **)pCatalog.replace()));
518 chk(pCatalog->ShutdownApplication(_bstr_t(QGA_PROVIDER_LNAME)));
521 out:
522 return hr;