install.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * QEMU Guest Agent win32 VSS Provider installer
  3. *
  4. * Copyright Hitachi Data Systems Corp. 2013
  5. *
  6. * Authors:
  7. * Tomoki Sekiyama <tomoki.sekiyama@hds.com>
  8. *
  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.
  11. */
  12. #include "qemu/osdep.h"
  13. #include "vss-common.h"
  14. #ifdef HAVE_VSS_SDK
  15. #include <vscoordint.h>
  16. #else
  17. #include <vsadmin.h>
  18. #endif
  19. #include "install.h"
  20. #include <wbemidl.h>
  21. #include <comdef.h>
  22. #include <comutil.h>
  23. #include <sddl.h>
  24. #include <winsvc.h>
  25. #define BUFFER_SIZE 1024
  26. 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} };
  35. void errmsg(DWORD err, const char *text)
  36. {
  37. /*
  38. * `text' contains function call statement when errmsg is called via chk().
  39. * To make error message more readable, we cut off the text after '('.
  40. * If text doesn't contains '(', negative precision is given, which is
  41. * treated as though it were missing.
  42. */
  43. char *msg = NULL;
  44. const char *nul = strchr(text, '(');
  45. int len = nul ? nul - text : -1;
  46. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  47. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  48. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  49. (char *)&msg, 0, NULL);
  50. fprintf(stderr, "%.*s. (Error: %lx) %s\n", len, text, err, msg);
  51. LocalFree(msg);
  52. }
  53. static void errmsg_dialog(DWORD err, const char *text, const char *opt = "")
  54. {
  55. char *msg, buf[512];
  56. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  57. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  58. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  59. (char *)&msg, 0, NULL);
  60. snprintf(buf, sizeof(buf), "%s%s. (Error: %lx) %s", text, opt, err, msg);
  61. MessageBox(NULL, buf, "Error from " QGA_PROVIDER_NAME, MB_OK|MB_ICONERROR);
  62. LocalFree(msg);
  63. }
  64. #define _chk(hr, status, msg, err_label) \
  65. do { \
  66. hr = (status); \
  67. if (FAILED(hr)) { \
  68. errmsg(hr, msg); \
  69. goto err_label; \
  70. } \
  71. } while (0)
  72. #define chk(status) _chk(hr, status, "Failed to " #status, out)
  73. #if !defined(__MINGW64_VERSION_MAJOR) || !defined(__MINGW64_VERSION_MINOR) || \
  74. __MINGW64_VERSION_MAJOR * 100 + __MINGW64_VERSION_MINOR < 301
  75. void __stdcall _com_issue_error(HRESULT hr)
  76. {
  77. errmsg(hr, "Unexpected error in COM");
  78. }
  79. #endif
  80. template<class T>
  81. HRESULT put_Value(ICatalogObject *pObj, LPCWSTR name, T val)
  82. {
  83. return pObj->put_Value(_bstr_t(name), _variant_t(val));
  84. }
  85. /* Lookup Administrators group name from winmgmt */
  86. static HRESULT GetAdminName(_bstr_t *name)
  87. {
  88. HRESULT hr;
  89. COMPointer<IWbemLocator> pLoc;
  90. COMPointer<IWbemServices> pSvc;
  91. COMPointer<IEnumWbemClassObject> pEnum;
  92. COMPointer<IWbemClassObject> pWobj;
  93. ULONG returned;
  94. _variant_t var;
  95. chk(CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER,
  96. IID_IWbemLocator, (LPVOID *)pLoc.replace()));
  97. chk(pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, NULL,
  98. 0, 0, 0, pSvc.replace()));
  99. chk(CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
  100. NULL, RPC_C_AUTHN_LEVEL_CALL,
  101. RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE));
  102. chk(pSvc->ExecQuery(_bstr_t(L"WQL"),
  103. _bstr_t(L"select * from Win32_Account where "
  104. "SID='S-1-5-32-544' and localAccount=TRUE"),
  105. WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
  106. NULL, pEnum.replace()));
  107. if (!pEnum) {
  108. hr = E_FAIL;
  109. errmsg(hr, "Failed to query for Administrators");
  110. goto out;
  111. }
  112. chk(pEnum->Next(WBEM_INFINITE, 1, pWobj.replace(), &returned));
  113. if (returned == 0) {
  114. hr = E_FAIL;
  115. errmsg(hr, "No Administrators found");
  116. goto out;
  117. }
  118. chk(pWobj->Get(_bstr_t(L"Name"), 0, &var, 0, 0));
  119. try {
  120. *name = var;
  121. } catch(...) {
  122. hr = E_FAIL;
  123. errmsg(hr, "Failed to get name of Administrators");
  124. goto out;
  125. }
  126. out:
  127. return hr;
  128. }
  129. /* Acquire group or user name by SID */
  130. static HRESULT getNameByStringSID(
  131. const wchar_t *sid, LPWSTR buffer, LPDWORD bufferLen)
  132. {
  133. HRESULT hr = S_OK;
  134. PSID psid = NULL;
  135. SID_NAME_USE groupType;
  136. DWORD domainNameLen = BUFFER_SIZE;
  137. wchar_t domainName[BUFFER_SIZE];
  138. if (!ConvertStringSidToSidW(sid, &psid)) {
  139. hr = HRESULT_FROM_WIN32(GetLastError());
  140. goto out;
  141. }
  142. if (!LookupAccountSidW(NULL, psid, buffer, bufferLen,
  143. domainName, &domainNameLen, &groupType)) {
  144. hr = HRESULT_FROM_WIN32(GetLastError());
  145. /* Fall through and free psid */
  146. }
  147. LocalFree(psid);
  148. out:
  149. return hr;
  150. }
  151. /* Find and iterate QGA VSS provider in COM+ Application Catalog */
  152. static HRESULT QGAProviderFind(
  153. HRESULT (*found)(ICatalogCollection *, int, void *), void *arg)
  154. {
  155. HRESULT hr;
  156. COMInitializer initializer;
  157. COMPointer<IUnknown> pUnknown;
  158. COMPointer<ICOMAdminCatalog2> pCatalog;
  159. COMPointer<ICatalogCollection> pColl;
  160. COMPointer<ICatalogObject> pObj;
  161. _variant_t var;
  162. long i, n;
  163. chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
  164. IID_IUnknown, (void **)pUnknown.replace()));
  165. chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
  166. (void **)pCatalog.replace()));
  167. chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
  168. (IDispatch **)pColl.replace()));
  169. chk(pColl->Populate());
  170. chk(pColl->get_Count(&n));
  171. for (i = n - 1; i >= 0; i--) {
  172. chk(pColl->get_Item(i, (IDispatch **)pObj.replace()));
  173. chk(pObj->get_Value(_bstr_t(L"Name"), &var));
  174. if (var == _variant_t(QGA_PROVIDER_LNAME)) {
  175. if (FAILED(found(pColl, i, arg))) {
  176. goto out;
  177. }
  178. }
  179. }
  180. chk(pColl->SaveChanges(&n));
  181. out:
  182. return hr;
  183. }
  184. /* Count QGA VSS provider in COM+ Application Catalog */
  185. static HRESULT QGAProviderCount(ICatalogCollection *coll, int i, void *arg)
  186. {
  187. (*(int *)arg)++;
  188. return S_OK;
  189. }
  190. /* Remove QGA VSS provider from COM+ Application Catalog Collection */
  191. static HRESULT QGAProviderRemove(ICatalogCollection *coll, int i, void *arg)
  192. {
  193. HRESULT hr;
  194. fprintf(stderr, "Removing COM+ Application: %s\n", QGA_PROVIDER_NAME);
  195. chk(coll->Remove(i));
  196. out:
  197. return hr;
  198. }
  199. /* Unregister this module from COM+ Applications Catalog */
  200. STDAPI COMUnregister(void)
  201. {
  202. HRESULT hr;
  203. DllUnregisterServer();
  204. chk(QGAProviderFind(QGAProviderRemove, NULL));
  205. out:
  206. return hr;
  207. }
  208. /* Register this module to COM+ Applications Catalog */
  209. STDAPI COMRegister(void)
  210. {
  211. HRESULT hr;
  212. COMInitializer initializer;
  213. COMPointer<IUnknown> pUnknown;
  214. COMPointer<ICOMAdminCatalog2> pCatalog;
  215. COMPointer<ICatalogCollection> pApps, pRoles, pUsersInRole;
  216. COMPointer<ICatalogObject> pObj;
  217. long n;
  218. _bstr_t name;
  219. _variant_t key;
  220. CHAR dllPath[MAX_PATH], tlbPath[MAX_PATH];
  221. bool unregisterOnFailure = false;
  222. int count = 0;
  223. DWORD bufferLen = BUFFER_SIZE;
  224. wchar_t buffer[BUFFER_SIZE];
  225. const wchar_t *administratorsGroupSID = L"S-1-5-32-544";
  226. const wchar_t *systemUserSID = L"S-1-5-18";
  227. if (!g_hinstDll) {
  228. errmsg(E_FAIL, "Failed to initialize DLL");
  229. return E_FAIL;
  230. }
  231. chk(QGAProviderFind(QGAProviderCount, (void *)&count));
  232. if (count) {
  233. errmsg(E_ABORT, "QGA VSS Provider is already installed");
  234. return E_ABORT;
  235. }
  236. chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
  237. IID_IUnknown, (void **)pUnknown.replace()));
  238. chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
  239. (void **)pCatalog.replace()));
  240. /* Install COM+ Component */
  241. chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
  242. (IDispatch **)pApps.replace()));
  243. chk(pApps->Populate());
  244. chk(pApps->Add((IDispatch **)&pObj));
  245. chk(put_Value(pObj, L"Name", QGA_PROVIDER_LNAME));
  246. chk(put_Value(pObj, L"Description", QGA_PROVIDER_LNAME));
  247. chk(put_Value(pObj, L"ApplicationAccessChecksEnabled", true));
  248. chk(put_Value(pObj, L"Authentication", short(6)));
  249. chk(put_Value(pObj, L"AuthenticationCapability", short(2)));
  250. chk(put_Value(pObj, L"ImpersonationLevel", short(2)));
  251. chk(pApps->SaveChanges(&n));
  252. /* The app should be deleted if something fails after SaveChanges */
  253. unregisterOnFailure = true;
  254. chk(pObj->get_Key(&key));
  255. if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
  256. hr = HRESULT_FROM_WIN32(GetLastError());
  257. errmsg(hr, "GetModuleFileName failed");
  258. goto out;
  259. }
  260. n = strlen(dllPath);
  261. if (n < 3) {
  262. hr = E_FAIL;
  263. errmsg(hr, "Failed to lookup dll");
  264. goto out;
  265. }
  266. strcpy(tlbPath, dllPath);
  267. strcpy(tlbPath+n-3, "tlb");
  268. fprintf(stderr, "Registering " QGA_PROVIDER_NAME ":\n");
  269. fprintf(stderr, " %s\n", dllPath);
  270. fprintf(stderr, " %s\n", tlbPath);
  271. if (!PathFileExists(tlbPath)) {
  272. hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
  273. errmsg(hr, "Failed to lookup tlb");
  274. goto out;
  275. }
  276. chk(pCatalog->CreateServiceForApplication(
  277. _bstr_t(QGA_PROVIDER_LNAME), _bstr_t(QGA_PROVIDER_LNAME),
  278. _bstr_t(L"SERVICE_DEMAND_START"), _bstr_t(L"SERVICE_ERROR_NORMAL"),
  279. _bstr_t(L""), _bstr_t(L".\\localsystem"), _bstr_t(L""), FALSE));
  280. chk(pCatalog->InstallComponent(_bstr_t(QGA_PROVIDER_LNAME),
  281. _bstr_t(dllPath), _bstr_t(tlbPath),
  282. _bstr_t("")));
  283. /* Setup roles of the applicaion */
  284. chk(getNameByStringSID(administratorsGroupSID, buffer, &bufferLen));
  285. chk(pApps->GetCollection(_bstr_t(L"Roles"), key,
  286. (IDispatch **)pRoles.replace()));
  287. chk(pRoles->Populate());
  288. chk(pRoles->Add((IDispatch **)pObj.replace()));
  289. chk(put_Value(pObj, L"Name", buffer));
  290. chk(put_Value(pObj, L"Description", L"Administrators group"));
  291. chk(pRoles->SaveChanges(&n));
  292. chk(pObj->get_Key(&key));
  293. /* Setup users in the role */
  294. chk(pRoles->GetCollection(_bstr_t(L"UsersInRole"), key,
  295. (IDispatch **)pUsersInRole.replace()));
  296. chk(pUsersInRole->Populate());
  297. chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
  298. chk(GetAdminName(&name));
  299. chk(put_Value(pObj, L"User", _bstr_t(".\\") + name));
  300. bufferLen = BUFFER_SIZE;
  301. chk(getNameByStringSID(systemUserSID, buffer, &bufferLen));
  302. chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
  303. chk(put_Value(pObj, L"User", buffer));
  304. chk(pUsersInRole->SaveChanges(&n));
  305. out:
  306. if (unregisterOnFailure && FAILED(hr)) {
  307. COMUnregister();
  308. }
  309. return hr;
  310. }
  311. STDAPI_(void) CALLBACK DLLCOMRegister(HWND, HINSTANCE, LPSTR, int)
  312. {
  313. COMRegister();
  314. }
  315. STDAPI_(void) CALLBACK DLLCOMUnregister(HWND, HINSTANCE, LPSTR, int)
  316. {
  317. COMUnregister();
  318. }
  319. static BOOL CreateRegistryKey(LPCTSTR key, LPCTSTR value, LPCTSTR data)
  320. {
  321. HKEY hKey;
  322. LONG ret;
  323. DWORD size;
  324. ret = RegCreateKeyEx(HKEY_CLASSES_ROOT, key, 0, NULL,
  325. REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
  326. if (ret != ERROR_SUCCESS) {
  327. goto out;
  328. }
  329. if (data != NULL) {
  330. size = strlen(data) + 1;
  331. } else {
  332. size = 0;
  333. }
  334. ret = RegSetValueEx(hKey, value, 0, REG_SZ, (LPBYTE)data, size);
  335. RegCloseKey(hKey);
  336. out:
  337. if (ret != ERROR_SUCCESS) {
  338. /* As we cannot printf within DllRegisterServer(), show a dialog. */
  339. errmsg_dialog(ret, "Cannot add registry", key);
  340. return FALSE;
  341. }
  342. return TRUE;
  343. }
  344. /* Register this dll as a VSS provider */
  345. STDAPI DllRegisterServer(void)
  346. {
  347. COMInitializer initializer;
  348. COMPointer<IVssAdmin> pVssAdmin;
  349. HRESULT hr = E_FAIL;
  350. char dllPath[MAX_PATH];
  351. char key[256];
  352. if (!g_hinstDll) {
  353. errmsg_dialog(hr, "Module instance is not available");
  354. goto out;
  355. }
  356. /* Add this module to registery */
  357. sprintf(key, "CLSID\\%s", g_szClsid);
  358. if (!CreateRegistryKey(key, NULL, g_szClsid)) {
  359. goto out;
  360. }
  361. if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
  362. errmsg_dialog(GetLastError(), "GetModuleFileName failed");
  363. goto out;
  364. }
  365. sprintf(key, "CLSID\\%s\\InprocServer32", g_szClsid);
  366. if (!CreateRegistryKey(key, NULL, dllPath)) {
  367. goto out;
  368. }
  369. if (!CreateRegistryKey(key, "ThreadingModel", "Apartment")) {
  370. goto out;
  371. }
  372. sprintf(key, "CLSID\\%s\\ProgID", g_szClsid);
  373. if (!CreateRegistryKey(key, NULL, g_szProgid)) {
  374. goto out;
  375. }
  376. if (!CreateRegistryKey(g_szProgid, NULL, QGA_PROVIDER_NAME)) {
  377. goto out;
  378. }
  379. sprintf(key, "%s\\CLSID", g_szProgid);
  380. if (!CreateRegistryKey(key, NULL, g_szClsid)) {
  381. goto out;
  382. }
  383. hr = CoCreateInstance(CLSID_VSSCoordinator, NULL, CLSCTX_ALL,
  384. IID_IVssAdmin, (void **)pVssAdmin.replace());
  385. if (FAILED(hr)) {
  386. errmsg_dialog(hr, "CoCreateInstance(VSSCoordinator) failed");
  387. goto out;
  388. }
  389. hr = pVssAdmin->RegisterProvider(g_gProviderId, CLSID_QGAVSSProvider,
  390. const_cast<WCHAR*>(QGA_PROVIDER_LNAME),
  391. VSS_PROV_SOFTWARE,
  392. const_cast<WCHAR*>(QGA_PROVIDER_VERSION),
  393. g_gProviderVersion);
  394. if (hr == (long int) VSS_E_PROVIDER_ALREADY_REGISTERED) {
  395. DllUnregisterServer();
  396. hr = pVssAdmin->RegisterProvider(g_gProviderId, CLSID_QGAVSSProvider,
  397. const_cast<WCHAR * >
  398. (QGA_PROVIDER_LNAME),
  399. VSS_PROV_SOFTWARE,
  400. const_cast<WCHAR * >
  401. (QGA_PROVIDER_VERSION),
  402. g_gProviderVersion);
  403. }
  404. if (FAILED(hr)) {
  405. errmsg_dialog(hr, "RegisterProvider failed");
  406. }
  407. out:
  408. if (FAILED(hr)) {
  409. DllUnregisterServer();
  410. }
  411. return hr;
  412. }
  413. /* Unregister this VSS hardware provider from the system */
  414. STDAPI DllUnregisterServer(void)
  415. {
  416. TCHAR key[256];
  417. COMInitializer initializer;
  418. COMPointer<IVssAdmin> pVssAdmin;
  419. HRESULT hr = CoCreateInstance(CLSID_VSSCoordinator,
  420. NULL, CLSCTX_ALL, IID_IVssAdmin,
  421. (void **)pVssAdmin.replace());
  422. if (SUCCEEDED(hr)) {
  423. hr = pVssAdmin->UnregisterProvider(g_gProviderId);
  424. } else {
  425. errmsg(hr, "CoCreateInstance(VSSCoordinator) failed");
  426. }
  427. sprintf(key, "CLSID\\%s", g_szClsid);
  428. SHDeleteKey(HKEY_CLASSES_ROOT, key);
  429. SHDeleteKey(HKEY_CLASSES_ROOT, g_szProgid);
  430. return S_OK; /* Uninstall should never fail */
  431. }
  432. /* Support function to convert ASCII string into BSTR (used in _bstr_t) */
  433. namespace _com_util
  434. {
  435. BSTR WINAPI ConvertStringToBSTR(const char *ascii) {
  436. int len = strlen(ascii);
  437. BSTR bstr = SysAllocStringLen(NULL, len);
  438. if (!bstr) {
  439. return NULL;
  440. }
  441. if (mbstowcs(bstr, ascii, len) == (size_t)-1) {
  442. fprintf(stderr, "Failed to convert string '%s' into BSTR", ascii);
  443. bstr[0] = 0;
  444. }
  445. return bstr;
  446. }
  447. }
  448. /* Stop QGA VSS provider service using Winsvc API */
  449. STDAPI StopService(void)
  450. {
  451. HRESULT hr = S_OK;
  452. SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  453. SC_HANDLE service = NULL;
  454. if (!manager) {
  455. errmsg(E_FAIL, "Failed to open service manager");
  456. hr = E_FAIL;
  457. goto out;
  458. }
  459. service = OpenService(manager, QGA_PROVIDER_NAME, SC_MANAGER_ALL_ACCESS);
  460. if (!service) {
  461. errmsg(E_FAIL, "Failed to open service");
  462. hr = E_FAIL;
  463. goto out;
  464. }
  465. if (!(ControlService(service, SERVICE_CONTROL_STOP, NULL))) {
  466. errmsg(E_FAIL, "Failed to stop service");
  467. hr = E_FAIL;
  468. }
  469. out:
  470. CloseServiceHandle(service);
  471. CloseServiceHandle(manager);
  472. return hr;
  473. }