install.cpp 17 KB

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