commands-win32.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450
  1. /*
  2. * QEMU Guest Agent win32-specific command implementations
  3. *
  4. * Copyright IBM Corp. 2012
  5. *
  6. * Authors:
  7. * Michael Roth <mdroth@linux.vnet.ibm.com>
  8. * Gal Hammer <ghammer@redhat.com>
  9. *
  10. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11. * See the COPYING file in the top-level directory.
  12. */
  13. #include "qemu/osdep.h"
  14. #include <wtypes.h>
  15. #include <powrprof.h>
  16. #include <winsock2.h>
  17. #include <ws2tcpip.h>
  18. #include <iptypes.h>
  19. #include <iphlpapi.h>
  20. #include <winioctl.h>
  21. #include <ntddscsi.h>
  22. #include <setupapi.h>
  23. #include <cfgmgr32.h>
  24. #include <initguid.h>
  25. #include <devpropdef.h>
  26. #include <lm.h>
  27. #include <wtsapi32.h>
  28. #include <wininet.h>
  29. #include "guest-agent-core.h"
  30. #include "vss-win32.h"
  31. #include "qga-qapi-commands.h"
  32. #include "qapi/error.h"
  33. #include "qapi/qmp/qerror.h"
  34. #include "qemu/queue.h"
  35. #include "qemu/host-utils.h"
  36. #include "qemu/base64.h"
  37. #include "commands-common.h"
  38. /*
  39. * The following should be in devpkey.h, but it isn't. The key names were
  40. * prefixed to avoid (future) name clashes. Once the definitions get into
  41. * mingw the following lines can be removed.
  42. */
  43. DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME, 0xb725f130, 0x47ef, 0x101a, 0xa5,
  44. 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
  45. /* DEVPROP_TYPE_STRING */
  46. DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds, 0xa45c254e, 0xdf1c,
  47. 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
  48. /* DEVPROP_TYPE_STRING_LIST */
  49. DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate, 0xa8b865dd, 0x2e3d,
  50. 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
  51. /* DEVPROP_TYPE_FILETIME */
  52. DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion, 0xa8b865dd, 0x2e3d,
  53. 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
  54. /* DEVPROP_TYPE_STRING */
  55. /* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
  56. #ifndef CM_Get_DevNode_Property
  57. #pragma GCC diagnostic push
  58. #pragma GCC diagnostic ignored "-Wredundant-decls"
  59. CMAPI CONFIGRET WINAPI CM_Get_DevNode_PropertyW(
  60. DEVINST dnDevInst,
  61. CONST DEVPROPKEY * PropertyKey,
  62. DEVPROPTYPE * PropertyType,
  63. PBYTE PropertyBuffer,
  64. PULONG PropertyBufferSize,
  65. ULONG ulFlags
  66. );
  67. #define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
  68. #pragma GCC diagnostic pop
  69. #endif
  70. #ifndef SHTDN_REASON_FLAG_PLANNED
  71. #define SHTDN_REASON_FLAG_PLANNED 0x80000000
  72. #endif
  73. /* multiple of 100 nanoseconds elapsed between windows baseline
  74. * (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
  75. #define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
  76. (365 * (1970 - 1601) + \
  77. (1970 - 1601) / 4 - 3))
  78. #define INVALID_SET_FILE_POINTER ((DWORD)-1)
  79. struct GuestFileHandle {
  80. int64_t id;
  81. HANDLE fh;
  82. QTAILQ_ENTRY(GuestFileHandle) next;
  83. };
  84. static struct {
  85. QTAILQ_HEAD(, GuestFileHandle) filehandles;
  86. } guest_file_state = {
  87. .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
  88. };
  89. #define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
  90. typedef struct OpenFlags {
  91. const char *forms;
  92. DWORD desired_access;
  93. DWORD creation_disposition;
  94. } OpenFlags;
  95. static OpenFlags guest_file_open_modes[] = {
  96. {"r", GENERIC_READ, OPEN_EXISTING},
  97. {"rb", GENERIC_READ, OPEN_EXISTING},
  98. {"w", GENERIC_WRITE, CREATE_ALWAYS},
  99. {"wb", GENERIC_WRITE, CREATE_ALWAYS},
  100. {"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
  101. {"r+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
  102. {"rb+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
  103. {"r+b", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
  104. {"w+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
  105. {"wb+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
  106. {"w+b", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
  107. {"a+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
  108. {"ab+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
  109. {"a+b", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS }
  110. };
  111. #define debug_error(msg) do { \
  112. char *suffix = g_win32_error_message(GetLastError()); \
  113. g_debug("%s: %s", (msg), suffix); \
  114. g_free(suffix); \
  115. } while (0)
  116. static OpenFlags *find_open_flag(const char *mode_str)
  117. {
  118. int mode;
  119. Error **errp = NULL;
  120. for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
  121. OpenFlags *flags = guest_file_open_modes + mode;
  122. if (strcmp(flags->forms, mode_str) == 0) {
  123. return flags;
  124. }
  125. }
  126. error_setg(errp, "invalid file open mode '%s'", mode_str);
  127. return NULL;
  128. }
  129. static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
  130. {
  131. GuestFileHandle *gfh;
  132. int64_t handle;
  133. handle = ga_get_fd_handle(ga_state, errp);
  134. if (handle < 0) {
  135. return -1;
  136. }
  137. gfh = g_new0(GuestFileHandle, 1);
  138. gfh->id = handle;
  139. gfh->fh = fh;
  140. QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
  141. return handle;
  142. }
  143. GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
  144. {
  145. GuestFileHandle *gfh;
  146. QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
  147. if (gfh->id == id) {
  148. return gfh;
  149. }
  150. }
  151. error_setg(errp, "handle '%" PRId64 "' has not been found", id);
  152. return NULL;
  153. }
  154. static void handle_set_nonblocking(HANDLE fh)
  155. {
  156. DWORD file_type, pipe_state;
  157. file_type = GetFileType(fh);
  158. if (file_type != FILE_TYPE_PIPE) {
  159. return;
  160. }
  161. /* If file_type == FILE_TYPE_PIPE, according to MSDN
  162. * the specified file is socket or named pipe */
  163. if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
  164. NULL, NULL, NULL, 0)) {
  165. return;
  166. }
  167. /* The fd is named pipe fd */
  168. if (pipe_state & PIPE_NOWAIT) {
  169. return;
  170. }
  171. pipe_state |= PIPE_NOWAIT;
  172. SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
  173. }
  174. int64_t qmp_guest_file_open(const char *path, const char *mode, Error **errp)
  175. {
  176. int64_t fd = -1;
  177. HANDLE fh;
  178. HANDLE templ_file = NULL;
  179. DWORD share_mode = FILE_SHARE_READ;
  180. DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
  181. LPSECURITY_ATTRIBUTES sa_attr = NULL;
  182. OpenFlags *guest_flags;
  183. GError *gerr = NULL;
  184. wchar_t *w_path = NULL;
  185. if (!mode) {
  186. mode = "r";
  187. }
  188. slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
  189. guest_flags = find_open_flag(mode);
  190. if (guest_flags == NULL) {
  191. error_setg(errp, "invalid file open mode");
  192. goto done;
  193. }
  194. w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
  195. if (!w_path) {
  196. error_setg(errp, "can't convert 'path' to UTF-16: %s",
  197. gerr->message);
  198. g_error_free(gerr);
  199. goto done;
  200. }
  201. fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
  202. guest_flags->creation_disposition, flags_and_attr,
  203. templ_file);
  204. if (fh == INVALID_HANDLE_VALUE) {
  205. error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
  206. path);
  207. goto done;
  208. }
  209. /* set fd non-blocking to avoid common use cases (like reading from a
  210. * named pipe) from hanging the agent
  211. */
  212. handle_set_nonblocking(fh);
  213. fd = guest_file_handle_add(fh, errp);
  214. if (fd < 0) {
  215. CloseHandle(fh);
  216. error_setg(errp, "failed to add handle to qmp handle table");
  217. goto done;
  218. }
  219. slog("guest-file-open, handle: % " PRId64, fd);
  220. done:
  221. g_free(w_path);
  222. return fd;
  223. }
  224. void qmp_guest_file_close(int64_t handle, Error **errp)
  225. {
  226. bool ret;
  227. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  228. slog("guest-file-close called, handle: %" PRId64, handle);
  229. if (gfh == NULL) {
  230. return;
  231. }
  232. ret = CloseHandle(gfh->fh);
  233. if (!ret) {
  234. error_setg_win32(errp, GetLastError(), "failed close handle");
  235. return;
  236. }
  237. QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
  238. g_free(gfh);
  239. }
  240. static void acquire_privilege(const char *name, Error **errp)
  241. {
  242. HANDLE token = NULL;
  243. TOKEN_PRIVILEGES priv;
  244. if (OpenProcessToken(GetCurrentProcess(),
  245. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token))
  246. {
  247. if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
  248. error_setg(errp, "no luid for requested privilege");
  249. goto out;
  250. }
  251. priv.PrivilegeCount = 1;
  252. priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  253. if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
  254. error_setg(errp, "unable to acquire requested privilege");
  255. goto out;
  256. }
  257. } else {
  258. error_setg(errp, "failed to open privilege token");
  259. }
  260. out:
  261. if (token) {
  262. CloseHandle(token);
  263. }
  264. }
  265. static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
  266. Error **errp)
  267. {
  268. HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
  269. if (!thread) {
  270. error_setg(errp, "failed to dispatch asynchronous command");
  271. }
  272. }
  273. void qmp_guest_shutdown(const char *mode, Error **errp)
  274. {
  275. Error *local_err = NULL;
  276. UINT shutdown_flag = EWX_FORCE;
  277. slog("guest-shutdown called, mode: %s", mode);
  278. if (!mode || strcmp(mode, "powerdown") == 0) {
  279. shutdown_flag |= EWX_POWEROFF;
  280. } else if (strcmp(mode, "halt") == 0) {
  281. shutdown_flag |= EWX_SHUTDOWN;
  282. } else if (strcmp(mode, "reboot") == 0) {
  283. shutdown_flag |= EWX_REBOOT;
  284. } else {
  285. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
  286. "'halt', 'powerdown', or 'reboot'");
  287. return;
  288. }
  289. /* Request a shutdown privilege, but try to shut down the system
  290. anyway. */
  291. acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
  292. if (local_err) {
  293. error_propagate(errp, local_err);
  294. return;
  295. }
  296. if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
  297. g_autofree gchar *emsg = g_win32_error_message(GetLastError());
  298. slog("guest-shutdown failed: %s", emsg);
  299. error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
  300. }
  301. }
  302. GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
  303. int64_t count, Error **errp)
  304. {
  305. GuestFileRead *read_data = NULL;
  306. guchar *buf;
  307. HANDLE fh = gfh->fh;
  308. bool is_ok;
  309. DWORD read_count;
  310. buf = g_malloc0(count + 1);
  311. is_ok = ReadFile(fh, buf, count, &read_count, NULL);
  312. if (!is_ok) {
  313. error_setg_win32(errp, GetLastError(), "failed to read file");
  314. } else {
  315. buf[read_count] = 0;
  316. read_data = g_new0(GuestFileRead, 1);
  317. read_data->count = (size_t)read_count;
  318. read_data->eof = read_count == 0;
  319. if (read_count != 0) {
  320. read_data->buf_b64 = g_base64_encode(buf, read_count);
  321. }
  322. }
  323. g_free(buf);
  324. return read_data;
  325. }
  326. GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
  327. bool has_count, int64_t count,
  328. Error **errp)
  329. {
  330. GuestFileWrite *write_data = NULL;
  331. guchar *buf;
  332. gsize buf_len;
  333. bool is_ok;
  334. DWORD write_count;
  335. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  336. HANDLE fh;
  337. if (!gfh) {
  338. return NULL;
  339. }
  340. fh = gfh->fh;
  341. buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
  342. if (!buf) {
  343. return NULL;
  344. }
  345. if (!has_count) {
  346. count = buf_len;
  347. } else if (count < 0 || count > buf_len) {
  348. error_setg(errp, "value '%" PRId64
  349. "' is invalid for argument count", count);
  350. goto done;
  351. }
  352. is_ok = WriteFile(fh, buf, count, &write_count, NULL);
  353. if (!is_ok) {
  354. error_setg_win32(errp, GetLastError(), "failed to write to file");
  355. slog("guest-file-write-failed, handle: %" PRId64, handle);
  356. } else {
  357. write_data = g_new0(GuestFileWrite, 1);
  358. write_data->count = (size_t) write_count;
  359. }
  360. done:
  361. g_free(buf);
  362. return write_data;
  363. }
  364. GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
  365. GuestFileWhence *whence_code,
  366. Error **errp)
  367. {
  368. GuestFileHandle *gfh;
  369. GuestFileSeek *seek_data;
  370. HANDLE fh;
  371. LARGE_INTEGER new_pos, off_pos;
  372. off_pos.QuadPart = offset;
  373. BOOL res;
  374. int whence;
  375. Error *err = NULL;
  376. gfh = guest_file_handle_find(handle, errp);
  377. if (!gfh) {
  378. return NULL;
  379. }
  380. /* We stupidly exposed 'whence':'int' in our qapi */
  381. whence = ga_parse_whence(whence_code, &err);
  382. if (err) {
  383. error_propagate(errp, err);
  384. return NULL;
  385. }
  386. fh = gfh->fh;
  387. res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
  388. if (!res) {
  389. error_setg_win32(errp, GetLastError(), "failed to seek file");
  390. return NULL;
  391. }
  392. seek_data = g_new0(GuestFileSeek, 1);
  393. seek_data->position = new_pos.QuadPart;
  394. return seek_data;
  395. }
  396. void qmp_guest_file_flush(int64_t handle, Error **errp)
  397. {
  398. HANDLE fh;
  399. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  400. if (!gfh) {
  401. return;
  402. }
  403. fh = gfh->fh;
  404. if (!FlushFileBuffers(fh)) {
  405. error_setg_win32(errp, GetLastError(), "failed to flush file");
  406. }
  407. }
  408. static GuestDiskBusType win2qemu[] = {
  409. [BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
  410. [BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
  411. [BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
  412. [BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
  413. [BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
  414. [BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
  415. [BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
  416. [BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
  417. [BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
  418. [BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
  419. [BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
  420. [BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
  421. [BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
  422. [BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
  423. [BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
  424. [BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
  425. /*
  426. * BusTypeSpaces currently is not supported
  427. */
  428. [BusTypeSpaces] = GUEST_DISK_BUS_TYPE_UNKNOWN,
  429. [BusTypeNvme] = GUEST_DISK_BUS_TYPE_NVME,
  430. };
  431. static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
  432. {
  433. if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
  434. return GUEST_DISK_BUS_TYPE_UNKNOWN;
  435. }
  436. return win2qemu[(int)bus];
  437. }
  438. static void get_pci_address_for_device(GuestPCIAddress *pci,
  439. HDEVINFO dev_info)
  440. {
  441. SP_DEVINFO_DATA dev_info_data;
  442. DWORD j;
  443. DWORD size;
  444. bool partial_pci = false;
  445. dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
  446. for (j = 0;
  447. SetupDiEnumDeviceInfo(dev_info, j, &dev_info_data);
  448. j++) {
  449. DWORD addr, bus, ui_slot, type;
  450. int func, slot;
  451. size = sizeof(DWORD);
  452. /*
  453. * There is no need to allocate buffer in the next functions. The
  454. * size is known and ULONG according to
  455. * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
  456. */
  457. if (!SetupDiGetDeviceRegistryProperty(
  458. dev_info, &dev_info_data, SPDRP_BUSNUMBER,
  459. &type, (PBYTE)&bus, size, NULL)) {
  460. debug_error("failed to get PCI bus");
  461. bus = -1;
  462. partial_pci = true;
  463. }
  464. /*
  465. * The function retrieves the device's address. This value will be
  466. * transformed into device function and number
  467. */
  468. if (!SetupDiGetDeviceRegistryProperty(
  469. dev_info, &dev_info_data, SPDRP_ADDRESS,
  470. &type, (PBYTE)&addr, size, NULL)) {
  471. debug_error("failed to get PCI address");
  472. addr = -1;
  473. partial_pci = true;
  474. }
  475. /*
  476. * This call returns UINumber of DEVICE_CAPABILITIES structure.
  477. * This number is typically a user-perceived slot number.
  478. */
  479. if (!SetupDiGetDeviceRegistryProperty(
  480. dev_info, &dev_info_data, SPDRP_UI_NUMBER,
  481. &type, (PBYTE)&ui_slot, size, NULL)) {
  482. debug_error("failed to get PCI slot");
  483. ui_slot = -1;
  484. partial_pci = true;
  485. }
  486. /*
  487. * SetupApi gives us the same information as driver with
  488. * IoGetDeviceProperty. According to Microsoft:
  489. *
  490. * FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
  491. * DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
  492. * SPDRP_ADDRESS is propertyAddress, so we do the same.
  493. *
  494. * https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
  495. */
  496. if (partial_pci) {
  497. pci->domain = -1;
  498. pci->slot = -1;
  499. pci->function = -1;
  500. pci->bus = -1;
  501. continue;
  502. } else {
  503. func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
  504. slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
  505. if ((int)ui_slot != slot) {
  506. g_debug("mismatch with reported slot values: %d vs %d",
  507. (int)ui_slot, slot);
  508. }
  509. pci->domain = 0;
  510. pci->slot = (int)ui_slot;
  511. pci->function = func;
  512. pci->bus = (int)bus;
  513. return;
  514. }
  515. }
  516. }
  517. static GuestPCIAddress *get_empty_pci_address(void)
  518. {
  519. GuestPCIAddress *pci = NULL;
  520. pci = g_malloc0(sizeof(*pci));
  521. pci->domain = -1;
  522. pci->slot = -1;
  523. pci->function = -1;
  524. pci->bus = -1;
  525. return pci;
  526. }
  527. static GuestPCIAddress *get_pci_info(int number, Error **errp)
  528. {
  529. HDEVINFO dev_info = INVALID_HANDLE_VALUE;
  530. HDEVINFO parent_dev_info = INVALID_HANDLE_VALUE;
  531. SP_DEVINFO_DATA dev_info_data;
  532. SP_DEVICE_INTERFACE_DATA dev_iface_data;
  533. HANDLE dev_file;
  534. int i;
  535. GuestPCIAddress *pci = get_empty_pci_address();
  536. dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
  537. DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  538. if (dev_info == INVALID_HANDLE_VALUE) {
  539. error_setg_win32(errp, GetLastError(), "failed to get devices tree");
  540. goto end;
  541. }
  542. g_debug("enumerating devices");
  543. dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
  544. dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  545. for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
  546. g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
  547. STORAGE_DEVICE_NUMBER sdn;
  548. g_autofree char *parent_dev_id = NULL;
  549. SP_DEVINFO_DATA parent_dev_info_data;
  550. DWORD size = 0;
  551. g_debug("getting device path");
  552. if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
  553. &GUID_DEVINTERFACE_DISK, 0,
  554. &dev_iface_data)) {
  555. if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
  556. pdev_iface_detail_data,
  557. size, &size,
  558. &dev_info_data)) {
  559. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  560. pdev_iface_detail_data = g_malloc(size);
  561. pdev_iface_detail_data->cbSize =
  562. sizeof(*pdev_iface_detail_data);
  563. } else {
  564. error_setg_win32(errp, GetLastError(),
  565. "failed to get device interfaces");
  566. goto end;
  567. }
  568. }
  569. if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
  570. pdev_iface_detail_data,
  571. size, &size,
  572. &dev_info_data)) {
  573. // pdev_iface_detail_data already is allocated
  574. error_setg_win32(errp, GetLastError(),
  575. "failed to get device interfaces");
  576. goto end;
  577. }
  578. dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
  579. FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
  580. NULL);
  581. if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
  582. NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
  583. CloseHandle(dev_file);
  584. error_setg_win32(errp, GetLastError(),
  585. "failed to get device slot number");
  586. goto end;
  587. }
  588. CloseHandle(dev_file);
  589. if (sdn.DeviceNumber != number) {
  590. continue;
  591. }
  592. } else {
  593. error_setg_win32(errp, GetLastError(),
  594. "failed to get device interfaces");
  595. goto end;
  596. }
  597. g_debug("found device slot %d. Getting storage controller", number);
  598. {
  599. CONFIGRET cr;
  600. DEVINST dev_inst, parent_dev_inst;
  601. ULONG dev_id_size = 0;
  602. size = 0;
  603. if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
  604. parent_dev_id, size, &size)) {
  605. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  606. parent_dev_id = g_malloc(size);
  607. } else {
  608. error_setg_win32(errp, GetLastError(),
  609. "failed to get device instance ID");
  610. goto end;
  611. }
  612. }
  613. if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
  614. parent_dev_id, size, &size)) {
  615. // parent_dev_id already is allocated
  616. error_setg_win32(errp, GetLastError(),
  617. "failed to get device instance ID");
  618. goto end;
  619. }
  620. /*
  621. * CM API used here as opposed to
  622. * SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
  623. * which exports are only available in mingw-w64 6+
  624. */
  625. cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
  626. if (cr != CR_SUCCESS) {
  627. g_error("CM_Locate_DevInst failed with code %lx", cr);
  628. error_setg_win32(errp, GetLastError(),
  629. "failed to get device instance");
  630. goto end;
  631. }
  632. cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
  633. if (cr != CR_SUCCESS) {
  634. g_error("CM_Get_Parent failed with code %lx", cr);
  635. error_setg_win32(errp, GetLastError(),
  636. "failed to get parent device instance");
  637. goto end;
  638. }
  639. cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
  640. if (cr != CR_SUCCESS) {
  641. g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
  642. error_setg_win32(errp, GetLastError(),
  643. "failed to get parent device ID length");
  644. goto end;
  645. }
  646. ++dev_id_size;
  647. if (dev_id_size > size) {
  648. g_free(parent_dev_id);
  649. parent_dev_id = g_malloc(dev_id_size);
  650. }
  651. cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
  652. 0);
  653. if (cr != CR_SUCCESS) {
  654. g_error("CM_Get_Device_ID failed with code %lx", cr);
  655. error_setg_win32(errp, GetLastError(),
  656. "failed to get parent device ID");
  657. goto end;
  658. }
  659. }
  660. g_debug("querying storage controller %s for PCI information",
  661. parent_dev_id);
  662. parent_dev_info =
  663. SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
  664. NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  665. if (parent_dev_info == INVALID_HANDLE_VALUE) {
  666. error_setg_win32(errp, GetLastError(),
  667. "failed to get parent device");
  668. goto end;
  669. }
  670. parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
  671. if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
  672. error_setg_win32(errp, GetLastError(),
  673. "failed to get parent device data");
  674. goto end;
  675. }
  676. get_pci_address_for_device(pci, parent_dev_info);
  677. break;
  678. }
  679. end:
  680. if (parent_dev_info != INVALID_HANDLE_VALUE) {
  681. SetupDiDestroyDeviceInfoList(parent_dev_info);
  682. }
  683. if (dev_info != INVALID_HANDLE_VALUE) {
  684. SetupDiDestroyDeviceInfoList(dev_info);
  685. }
  686. return pci;
  687. }
  688. static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
  689. Error **errp)
  690. {
  691. STORAGE_PROPERTY_QUERY query;
  692. STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
  693. DWORD received;
  694. ULONG size = sizeof(buf);
  695. dev_desc = &buf;
  696. query.PropertyId = StorageDeviceProperty;
  697. query.QueryType = PropertyStandardQuery;
  698. if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
  699. sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
  700. size, &received, NULL)) {
  701. error_setg_win32(errp, GetLastError(), "failed to get bus type");
  702. return;
  703. }
  704. disk->bus_type = find_bus_type(dev_desc->BusType);
  705. g_debug("bus type %d", disk->bus_type);
  706. /* Query once more. Now with long enough buffer. */
  707. size = dev_desc->Size;
  708. dev_desc = g_malloc0(size);
  709. if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
  710. sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
  711. size, &received, NULL)) {
  712. error_setg_win32(errp, GetLastError(), "failed to get serial number");
  713. g_debug("failed to get serial number");
  714. goto out_free;
  715. }
  716. if (dev_desc->SerialNumberOffset > 0) {
  717. const char *serial;
  718. size_t len;
  719. if (dev_desc->SerialNumberOffset >= received) {
  720. error_setg(errp, "failed to get serial number: offset outside the buffer");
  721. g_debug("serial number offset outside the buffer");
  722. goto out_free;
  723. }
  724. serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
  725. len = received - dev_desc->SerialNumberOffset;
  726. g_debug("serial number \"%s\"", serial);
  727. if (*serial != 0) {
  728. disk->serial = g_strndup(serial, len);
  729. }
  730. }
  731. out_free:
  732. g_free(dev_desc);
  733. return;
  734. }
  735. static void get_single_disk_info(int disk_number,
  736. GuestDiskAddress *disk, Error **errp)
  737. {
  738. SCSI_ADDRESS addr, *scsi_ad;
  739. DWORD len;
  740. HANDLE disk_h;
  741. Error *local_err = NULL;
  742. scsi_ad = &addr;
  743. g_debug("getting disk info for: %s", disk->dev);
  744. disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
  745. 0, NULL);
  746. if (disk_h == INVALID_HANDLE_VALUE) {
  747. error_setg_win32(errp, GetLastError(), "failed to open disk");
  748. return;
  749. }
  750. get_disk_properties(disk_h, disk, &local_err);
  751. if (local_err) {
  752. error_propagate(errp, local_err);
  753. goto err_close;
  754. }
  755. g_debug("bus type %d", disk->bus_type);
  756. /* always set pci_controller as required by schema. get_pci_info() should
  757. * report -1 values for non-PCI buses rather than fail. fail the command
  758. * if that doesn't hold since that suggests some other unexpected
  759. * breakage
  760. */
  761. if (disk->bus_type == GUEST_DISK_BUS_TYPE_USB) {
  762. disk->pci_controller = get_empty_pci_address();
  763. } else {
  764. disk->pci_controller = get_pci_info(disk_number, &local_err);
  765. if (local_err) {
  766. error_propagate(errp, local_err);
  767. goto err_close;
  768. }
  769. }
  770. if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
  771. || disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
  772. || disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
  773. /* This bus type is not supported before Windows Server 2003 SP1 */
  774. || disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
  775. ) {
  776. /* We are able to use the same ioctls for different bus types
  777. * according to Microsoft docs
  778. * https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
  779. g_debug("getting SCSI info");
  780. if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
  781. sizeof(SCSI_ADDRESS), &len, NULL)) {
  782. disk->unit = addr.Lun;
  783. disk->target = addr.TargetId;
  784. disk->bus = addr.PathId;
  785. }
  786. /* We do not set error in this case, because we still have enough
  787. * information about volume. */
  788. }
  789. err_close:
  790. CloseHandle(disk_h);
  791. return;
  792. }
  793. /* VSS provider works with volumes, thus there is no difference if
  794. * the volume consist of spanned disks. Info about the first disk in the
  795. * volume is returned for the spanned disk group (LVM) */
  796. static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
  797. {
  798. Error *local_err = NULL;
  799. GuestDiskAddressList *list = NULL;
  800. GuestDiskAddress *disk = NULL;
  801. int i;
  802. HANDLE vol_h;
  803. DWORD size;
  804. PVOLUME_DISK_EXTENTS extents = NULL;
  805. /* strip final backslash */
  806. char *name = g_strdup(guid);
  807. if (g_str_has_suffix(name, "\\")) {
  808. name[strlen(name) - 1] = 0;
  809. }
  810. g_debug("opening %s", name);
  811. vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
  812. 0, NULL);
  813. if (vol_h == INVALID_HANDLE_VALUE) {
  814. error_setg_win32(errp, GetLastError(), "failed to open volume");
  815. goto out;
  816. }
  817. /* Get list of extents */
  818. g_debug("getting disk extents");
  819. size = sizeof(VOLUME_DISK_EXTENTS);
  820. extents = g_malloc0(size);
  821. if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
  822. 0, extents, size, &size, NULL)) {
  823. DWORD last_err = GetLastError();
  824. if (last_err == ERROR_MORE_DATA) {
  825. /* Try once more with big enough buffer */
  826. size = sizeof(VOLUME_DISK_EXTENTS) +
  827. (sizeof(DISK_EXTENT) * (extents->NumberOfDiskExtents - 1));
  828. g_free(extents);
  829. extents = g_malloc0(size);
  830. if (!DeviceIoControl(
  831. vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
  832. 0, extents, size, NULL, NULL)) {
  833. error_setg_win32(errp, GetLastError(),
  834. "failed to get disk extents");
  835. goto out;
  836. }
  837. } else if (last_err == ERROR_INVALID_FUNCTION) {
  838. /* Possibly CD-ROM or a shared drive. Try to pass the volume */
  839. g_debug("volume not on disk");
  840. disk = g_new0(GuestDiskAddress, 1);
  841. disk->dev = g_strdup(name);
  842. get_single_disk_info(0xffffffff, disk, &local_err);
  843. if (local_err) {
  844. g_debug("failed to get disk info, ignoring error: %s",
  845. error_get_pretty(local_err));
  846. error_free(local_err);
  847. goto out;
  848. }
  849. QAPI_LIST_PREPEND(list, disk);
  850. disk = NULL;
  851. goto out;
  852. } else {
  853. error_setg_win32(errp, GetLastError(),
  854. "failed to get disk extents");
  855. goto out;
  856. }
  857. }
  858. g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
  859. /* Go through each extent */
  860. for (i = 0; i < extents->NumberOfDiskExtents; i++) {
  861. disk = g_new0(GuestDiskAddress, 1);
  862. /* Disk numbers directly correspond to numbers used in UNCs
  863. *
  864. * See documentation for DISK_EXTENT:
  865. * https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
  866. *
  867. * See also Naming Files, Paths and Namespaces:
  868. * https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
  869. */
  870. disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
  871. extents->Extents[i].DiskNumber);
  872. get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
  873. if (local_err) {
  874. error_propagate(errp, local_err);
  875. goto out;
  876. }
  877. QAPI_LIST_PREPEND(list, disk);
  878. disk = NULL;
  879. }
  880. out:
  881. if (vol_h != INVALID_HANDLE_VALUE) {
  882. CloseHandle(vol_h);
  883. }
  884. qapi_free_GuestDiskAddress(disk);
  885. g_free(extents);
  886. g_free(name);
  887. return list;
  888. }
  889. GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
  890. {
  891. GuestDiskInfoList *ret = NULL;
  892. HDEVINFO dev_info;
  893. SP_DEVICE_INTERFACE_DATA dev_iface_data;
  894. int i;
  895. dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
  896. DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  897. if (dev_info == INVALID_HANDLE_VALUE) {
  898. error_setg_win32(errp, GetLastError(), "failed to get device tree");
  899. return NULL;
  900. }
  901. g_debug("enumerating devices");
  902. dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  903. for (i = 0;
  904. SetupDiEnumDeviceInterfaces(dev_info, NULL, &GUID_DEVINTERFACE_DISK,
  905. i, &dev_iface_data);
  906. i++) {
  907. GuestDiskAddress *address = NULL;
  908. GuestDiskInfo *disk = NULL;
  909. Error *local_err = NULL;
  910. g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA
  911. pdev_iface_detail_data = NULL;
  912. STORAGE_DEVICE_NUMBER sdn;
  913. HANDLE dev_file;
  914. DWORD size = 0;
  915. BOOL result;
  916. int attempt;
  917. g_debug(" getting device path");
  918. for (attempt = 0, result = FALSE; attempt < 2 && !result; attempt++) {
  919. result = SetupDiGetDeviceInterfaceDetail(dev_info,
  920. &dev_iface_data, pdev_iface_detail_data, size, &size, NULL);
  921. if (result) {
  922. break;
  923. }
  924. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  925. pdev_iface_detail_data = g_realloc(pdev_iface_detail_data,
  926. size);
  927. pdev_iface_detail_data->cbSize =
  928. sizeof(*pdev_iface_detail_data);
  929. } else {
  930. g_debug("failed to get device interface details");
  931. break;
  932. }
  933. }
  934. if (!result) {
  935. g_debug("skipping device");
  936. continue;
  937. }
  938. g_debug(" device: %s", pdev_iface_detail_data->DevicePath);
  939. dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
  940. FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  941. if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
  942. NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
  943. CloseHandle(dev_file);
  944. debug_error("failed to get storage device number");
  945. continue;
  946. }
  947. CloseHandle(dev_file);
  948. disk = g_new0(GuestDiskInfo, 1);
  949. disk->name = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
  950. sdn.DeviceNumber);
  951. g_debug(" number: %lu", sdn.DeviceNumber);
  952. address = g_new0(GuestDiskAddress, 1);
  953. address->dev = g_strdup(disk->name);
  954. get_single_disk_info(sdn.DeviceNumber, address, &local_err);
  955. if (local_err) {
  956. g_debug("failed to get disk info: %s",
  957. error_get_pretty(local_err));
  958. error_free(local_err);
  959. qapi_free_GuestDiskAddress(address);
  960. address = NULL;
  961. } else {
  962. disk->address = address;
  963. }
  964. QAPI_LIST_PREPEND(ret, disk);
  965. }
  966. SetupDiDestroyDeviceInfoList(dev_info);
  967. return ret;
  968. }
  969. static GuestFilesystemInfo *build_guest_fsinfo(char *guid, Error **errp)
  970. {
  971. DWORD info_size;
  972. char mnt, *mnt_point;
  973. wchar_t wfs_name[32];
  974. char fs_name[32];
  975. wchar_t vol_info[MAX_PATH + 1];
  976. size_t len;
  977. uint64_t i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;
  978. GuestFilesystemInfo *fs = NULL;
  979. HANDLE hLocalDiskHandle = INVALID_HANDLE_VALUE;
  980. GetVolumePathNamesForVolumeName(guid, (LPCH)&mnt, 0, &info_size);
  981. if (GetLastError() != ERROR_MORE_DATA) {
  982. error_setg_win32(errp, GetLastError(), "failed to get volume name");
  983. return NULL;
  984. }
  985. mnt_point = g_malloc(info_size + 1);
  986. if (!GetVolumePathNamesForVolumeName(guid, mnt_point, info_size,
  987. &info_size)) {
  988. error_setg_win32(errp, GetLastError(), "failed to get volume name");
  989. goto free;
  990. }
  991. hLocalDiskHandle = CreateFile(guid, 0 , 0, NULL, OPEN_EXISTING,
  992. FILE_ATTRIBUTE_NORMAL |
  993. FILE_FLAG_BACKUP_SEMANTICS, NULL);
  994. if (INVALID_HANDLE_VALUE == hLocalDiskHandle) {
  995. error_setg_win32(errp, GetLastError(), "failed to get handle for volume");
  996. goto free;
  997. }
  998. len = strlen(mnt_point);
  999. mnt_point[len] = '\\';
  1000. mnt_point[len + 1] = 0;
  1001. if (!GetVolumeInformationByHandleW(hLocalDiskHandle, vol_info,
  1002. sizeof(vol_info), NULL, NULL, NULL,
  1003. (LPWSTR) & wfs_name, sizeof(wfs_name))) {
  1004. if (GetLastError() != ERROR_NOT_READY) {
  1005. error_setg_win32(errp, GetLastError(), "failed to get volume info");
  1006. }
  1007. goto free;
  1008. }
  1009. fs = g_malloc(sizeof(*fs));
  1010. fs->name = g_strdup(guid);
  1011. fs->has_total_bytes = false;
  1012. fs->has_total_bytes_privileged = false;
  1013. fs->has_used_bytes = false;
  1014. if (len == 0) {
  1015. fs->mountpoint = g_strdup("System Reserved");
  1016. } else {
  1017. fs->mountpoint = g_strndup(mnt_point, len);
  1018. if (GetDiskFreeSpaceEx(fs->mountpoint,
  1019. (PULARGE_INTEGER) & i64FreeBytesToCaller,
  1020. (PULARGE_INTEGER) & i64TotalBytes,
  1021. (PULARGE_INTEGER) & i64FreeBytes)) {
  1022. fs->used_bytes = i64TotalBytes - i64FreeBytes;
  1023. fs->total_bytes = i64TotalBytes;
  1024. fs->has_total_bytes = true;
  1025. fs->has_used_bytes = true;
  1026. }
  1027. }
  1028. wcstombs(fs_name, wfs_name, sizeof(wfs_name));
  1029. fs->type = g_strdup(fs_name);
  1030. fs->disk = build_guest_disk_info(guid, errp);
  1031. free:
  1032. if (hLocalDiskHandle != INVALID_HANDLE_VALUE) {
  1033. CloseHandle(hLocalDiskHandle);
  1034. }
  1035. g_free(mnt_point);
  1036. return fs;
  1037. }
  1038. GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
  1039. {
  1040. HANDLE vol_h;
  1041. GuestFilesystemInfoList *ret = NULL;
  1042. char guid[256];
  1043. vol_h = FindFirstVolume(guid, sizeof(guid));
  1044. if (vol_h == INVALID_HANDLE_VALUE) {
  1045. error_setg_win32(errp, GetLastError(), "failed to find any volume");
  1046. return NULL;
  1047. }
  1048. do {
  1049. Error *local_err = NULL;
  1050. GuestFilesystemInfo *info = build_guest_fsinfo(guid, &local_err);
  1051. if (local_err) {
  1052. g_debug("failed to get filesystem info, ignoring error: %s",
  1053. error_get_pretty(local_err));
  1054. error_free(local_err);
  1055. continue;
  1056. }
  1057. QAPI_LIST_PREPEND(ret, info);
  1058. } while (FindNextVolume(vol_h, guid, sizeof(guid)));
  1059. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1060. error_setg_win32(errp, GetLastError(), "failed to find next volume");
  1061. }
  1062. FindVolumeClose(vol_h);
  1063. return ret;
  1064. }
  1065. /*
  1066. * Return status of freeze/thaw
  1067. */
  1068. GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
  1069. {
  1070. if (!vss_initialized()) {
  1071. error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
  1072. return 0;
  1073. }
  1074. if (ga_is_frozen(ga_state)) {
  1075. return GUEST_FSFREEZE_STATUS_FROZEN;
  1076. }
  1077. return GUEST_FSFREEZE_STATUS_THAWED;
  1078. }
  1079. /*
  1080. * Freeze local file systems using Volume Shadow-copy Service.
  1081. * The frozen state is limited for up to 10 seconds by VSS.
  1082. */
  1083. int64_t qmp_guest_fsfreeze_freeze(Error **errp)
  1084. {
  1085. return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
  1086. }
  1087. int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
  1088. strList *mountpoints,
  1089. Error **errp)
  1090. {
  1091. int i;
  1092. Error *local_err = NULL;
  1093. if (!vss_initialized()) {
  1094. error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
  1095. return 0;
  1096. }
  1097. slog("guest-fsfreeze called");
  1098. /* cannot risk guest agent blocking itself on a write in this state */
  1099. ga_set_frozen(ga_state);
  1100. qga_vss_fsfreeze(&i, true, mountpoints, &local_err);
  1101. if (local_err) {
  1102. error_propagate(errp, local_err);
  1103. goto error;
  1104. }
  1105. return i;
  1106. error:
  1107. local_err = NULL;
  1108. qmp_guest_fsfreeze_thaw(&local_err);
  1109. if (local_err) {
  1110. g_debug("cleanup thaw: %s", error_get_pretty(local_err));
  1111. error_free(local_err);
  1112. }
  1113. return 0;
  1114. }
  1115. /*
  1116. * Thaw local file systems using Volume Shadow-copy Service.
  1117. */
  1118. int64_t qmp_guest_fsfreeze_thaw(Error **errp)
  1119. {
  1120. int i;
  1121. if (!vss_initialized()) {
  1122. error_setg(errp, "fsfreeze not possible as VSS failed to initialize");
  1123. return 0;
  1124. }
  1125. qga_vss_fsfreeze(&i, false, NULL, errp);
  1126. ga_unset_frozen(ga_state);
  1127. slog("guest-fsthaw called");
  1128. return i;
  1129. }
  1130. static void guest_fsfreeze_cleanup(void)
  1131. {
  1132. Error *err = NULL;
  1133. if (!vss_initialized()) {
  1134. return;
  1135. }
  1136. if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
  1137. qmp_guest_fsfreeze_thaw(&err);
  1138. if (err) {
  1139. slog("failed to clean up frozen filesystems: %s",
  1140. error_get_pretty(err));
  1141. error_free(err);
  1142. }
  1143. }
  1144. vss_deinit(true);
  1145. }
  1146. /*
  1147. * Walk list of mounted file systems in the guest, and discard unused
  1148. * areas.
  1149. */
  1150. GuestFilesystemTrimResponse *
  1151. qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
  1152. {
  1153. GuestFilesystemTrimResponse *resp;
  1154. HANDLE handle;
  1155. WCHAR guid[MAX_PATH] = L"";
  1156. OSVERSIONINFO osvi;
  1157. BOOL win8_or_later;
  1158. ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  1159. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  1160. GetVersionEx(&osvi);
  1161. win8_or_later = (osvi.dwMajorVersion > 6 ||
  1162. ((osvi.dwMajorVersion == 6) &&
  1163. (osvi.dwMinorVersion >= 2)));
  1164. if (!win8_or_later) {
  1165. error_setg(errp, "fstrim is only supported for Win8+");
  1166. return NULL;
  1167. }
  1168. handle = FindFirstVolumeW(guid, ARRAYSIZE(guid));
  1169. if (handle == INVALID_HANDLE_VALUE) {
  1170. error_setg_win32(errp, GetLastError(), "failed to find any volume");
  1171. return NULL;
  1172. }
  1173. resp = g_new0(GuestFilesystemTrimResponse, 1);
  1174. do {
  1175. GuestFilesystemTrimResult *res;
  1176. PWCHAR uc_path;
  1177. DWORD char_count = 0;
  1178. char *path, *out;
  1179. GError *gerr = NULL;
  1180. gchar *argv[4];
  1181. GetVolumePathNamesForVolumeNameW(guid, NULL, 0, &char_count);
  1182. if (GetLastError() != ERROR_MORE_DATA) {
  1183. continue;
  1184. }
  1185. if (GetDriveTypeW(guid) != DRIVE_FIXED) {
  1186. continue;
  1187. }
  1188. uc_path = g_new(WCHAR, char_count);
  1189. if (!GetVolumePathNamesForVolumeNameW(guid, uc_path, char_count,
  1190. &char_count) || !*uc_path) {
  1191. /* strange, but this condition could be faced even with size == 2 */
  1192. g_free(uc_path);
  1193. continue;
  1194. }
  1195. res = g_new0(GuestFilesystemTrimResult, 1);
  1196. path = g_utf16_to_utf8(uc_path, char_count, NULL, NULL, &gerr);
  1197. g_free(uc_path);
  1198. if (!path) {
  1199. res->error = g_strdup(gerr->message);
  1200. g_error_free(gerr);
  1201. break;
  1202. }
  1203. res->path = path;
  1204. QAPI_LIST_PREPEND(resp->paths, res);
  1205. memset(argv, 0, sizeof(argv));
  1206. argv[0] = (gchar *)"defrag.exe";
  1207. argv[1] = (gchar *)"/L";
  1208. argv[2] = path;
  1209. if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
  1210. &out /* stdout */, NULL /* stdin */,
  1211. NULL, &gerr)) {
  1212. res->error = g_strdup(gerr->message);
  1213. g_error_free(gerr);
  1214. } else {
  1215. /* defrag.exe is UGLY. Exit code is ALWAYS zero.
  1216. Error is reported in the output with something like
  1217. (x89000020) etc code in the stdout */
  1218. int i;
  1219. gchar **lines = g_strsplit(out, "\r\n", 0);
  1220. g_free(out);
  1221. for (i = 0; lines[i] != NULL; i++) {
  1222. if (g_strstr_len(lines[i], -1, "(0x") == NULL) {
  1223. continue;
  1224. }
  1225. res->error = g_strdup(lines[i]);
  1226. break;
  1227. }
  1228. g_strfreev(lines);
  1229. }
  1230. } while (FindNextVolumeW(handle, guid, ARRAYSIZE(guid)));
  1231. FindVolumeClose(handle);
  1232. return resp;
  1233. }
  1234. typedef enum {
  1235. GUEST_SUSPEND_MODE_DISK,
  1236. GUEST_SUSPEND_MODE_RAM
  1237. } GuestSuspendMode;
  1238. static void check_suspend_mode(GuestSuspendMode mode, Error **errp)
  1239. {
  1240. SYSTEM_POWER_CAPABILITIES sys_pwr_caps;
  1241. ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));
  1242. if (!GetPwrCapabilities(&sys_pwr_caps)) {
  1243. error_setg(errp, "failed to determine guest suspend capabilities");
  1244. return;
  1245. }
  1246. switch (mode) {
  1247. case GUEST_SUSPEND_MODE_DISK:
  1248. if (!sys_pwr_caps.SystemS4) {
  1249. error_setg(errp, "suspend-to-disk not supported by OS");
  1250. }
  1251. break;
  1252. case GUEST_SUSPEND_MODE_RAM:
  1253. if (!sys_pwr_caps.SystemS3) {
  1254. error_setg(errp, "suspend-to-ram not supported by OS");
  1255. }
  1256. break;
  1257. default:
  1258. abort();
  1259. }
  1260. }
  1261. static DWORD WINAPI do_suspend(LPVOID opaque)
  1262. {
  1263. GuestSuspendMode *mode = opaque;
  1264. DWORD ret = 0;
  1265. if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {
  1266. g_autofree gchar *emsg = g_win32_error_message(GetLastError());
  1267. slog("failed to suspend guest: %s", emsg);
  1268. ret = -1;
  1269. }
  1270. g_free(mode);
  1271. return ret;
  1272. }
  1273. void qmp_guest_suspend_disk(Error **errp)
  1274. {
  1275. Error *local_err = NULL;
  1276. GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
  1277. *mode = GUEST_SUSPEND_MODE_DISK;
  1278. check_suspend_mode(*mode, &local_err);
  1279. if (local_err) {
  1280. goto out;
  1281. }
  1282. acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
  1283. if (local_err) {
  1284. goto out;
  1285. }
  1286. execute_async(do_suspend, mode, &local_err);
  1287. out:
  1288. if (local_err) {
  1289. error_propagate(errp, local_err);
  1290. g_free(mode);
  1291. }
  1292. }
  1293. void qmp_guest_suspend_ram(Error **errp)
  1294. {
  1295. Error *local_err = NULL;
  1296. GuestSuspendMode *mode = g_new(GuestSuspendMode, 1);
  1297. *mode = GUEST_SUSPEND_MODE_RAM;
  1298. check_suspend_mode(*mode, &local_err);
  1299. if (local_err) {
  1300. goto out;
  1301. }
  1302. acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
  1303. if (local_err) {
  1304. goto out;
  1305. }
  1306. execute_async(do_suspend, mode, &local_err);
  1307. out:
  1308. if (local_err) {
  1309. error_propagate(errp, local_err);
  1310. g_free(mode);
  1311. }
  1312. }
  1313. static IP_ADAPTER_ADDRESSES *guest_get_adapters_addresses(Error **errp)
  1314. {
  1315. IP_ADAPTER_ADDRESSES *adptr_addrs = NULL;
  1316. ULONG adptr_addrs_len = 0;
  1317. DWORD ret;
  1318. /* Call the first time to get the adptr_addrs_len. */
  1319. GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
  1320. NULL, adptr_addrs, &adptr_addrs_len);
  1321. adptr_addrs = g_malloc(adptr_addrs_len);
  1322. ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX,
  1323. NULL, adptr_addrs, &adptr_addrs_len);
  1324. if (ret != ERROR_SUCCESS) {
  1325. error_setg_win32(errp, ret, "failed to get adapters addresses");
  1326. g_free(adptr_addrs);
  1327. adptr_addrs = NULL;
  1328. }
  1329. return adptr_addrs;
  1330. }
  1331. static char *guest_wctomb_dup(WCHAR *wstr)
  1332. {
  1333. char *str;
  1334. size_t str_size;
  1335. str_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
  1336. /* add 1 to str_size for NULL terminator */
  1337. str = g_malloc(str_size + 1);
  1338. WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, str_size, NULL, NULL);
  1339. return str;
  1340. }
  1341. static char *guest_addr_to_str(IP_ADAPTER_UNICAST_ADDRESS *ip_addr,
  1342. Error **errp)
  1343. {
  1344. char addr_str[INET6_ADDRSTRLEN + INET_ADDRSTRLEN];
  1345. DWORD len;
  1346. int ret;
  1347. if (ip_addr->Address.lpSockaddr->sa_family == AF_INET ||
  1348. ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
  1349. len = sizeof(addr_str);
  1350. ret = WSAAddressToString(ip_addr->Address.lpSockaddr,
  1351. ip_addr->Address.iSockaddrLength,
  1352. NULL,
  1353. addr_str,
  1354. &len);
  1355. if (ret != 0) {
  1356. error_setg_win32(errp, WSAGetLastError(),
  1357. "failed address presentation form conversion");
  1358. return NULL;
  1359. }
  1360. return g_strdup(addr_str);
  1361. }
  1362. return NULL;
  1363. }
  1364. static int64_t guest_ip_prefix(IP_ADAPTER_UNICAST_ADDRESS *ip_addr)
  1365. {
  1366. /* For Windows Vista/2008 and newer, use the OnLinkPrefixLength
  1367. * field to obtain the prefix.
  1368. */
  1369. return ip_addr->OnLinkPrefixLength;
  1370. }
  1371. #define INTERFACE_PATH_BUF_SZ 512
  1372. static DWORD get_interface_index(const char *guid)
  1373. {
  1374. ULONG index;
  1375. DWORD status;
  1376. wchar_t wbuf[INTERFACE_PATH_BUF_SZ];
  1377. snwprintf(wbuf, INTERFACE_PATH_BUF_SZ, L"\\device\\tcpip_%s", guid);
  1378. wbuf[INTERFACE_PATH_BUF_SZ - 1] = 0;
  1379. status = GetAdapterIndex (wbuf, &index);
  1380. if (status != NO_ERROR) {
  1381. return (DWORD)~0;
  1382. } else {
  1383. return index;
  1384. }
  1385. }
  1386. typedef NETIOAPI_API (WINAPI *GetIfEntry2Func)(PMIB_IF_ROW2 Row);
  1387. static int guest_get_network_stats(const char *name,
  1388. GuestNetworkInterfaceStat *stats)
  1389. {
  1390. OSVERSIONINFO os_ver;
  1391. os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  1392. GetVersionEx(&os_ver);
  1393. if (os_ver.dwMajorVersion >= 6) {
  1394. MIB_IF_ROW2 a_mid_ifrow;
  1395. GetIfEntry2Func getifentry2_ex;
  1396. DWORD if_index = 0;
  1397. HMODULE module = GetModuleHandle("iphlpapi");
  1398. PVOID func = GetProcAddress(module, "GetIfEntry2");
  1399. if (func == NULL) {
  1400. return -1;
  1401. }
  1402. getifentry2_ex = (GetIfEntry2Func)func;
  1403. if_index = get_interface_index(name);
  1404. if (if_index == (DWORD)~0) {
  1405. return -1;
  1406. }
  1407. memset(&a_mid_ifrow, 0, sizeof(a_mid_ifrow));
  1408. a_mid_ifrow.InterfaceIndex = if_index;
  1409. if (NO_ERROR == getifentry2_ex(&a_mid_ifrow)) {
  1410. stats->rx_bytes = a_mid_ifrow.InOctets;
  1411. stats->rx_packets = a_mid_ifrow.InUcastPkts;
  1412. stats->rx_errs = a_mid_ifrow.InErrors;
  1413. stats->rx_dropped = a_mid_ifrow.InDiscards;
  1414. stats->tx_bytes = a_mid_ifrow.OutOctets;
  1415. stats->tx_packets = a_mid_ifrow.OutUcastPkts;
  1416. stats->tx_errs = a_mid_ifrow.OutErrors;
  1417. stats->tx_dropped = a_mid_ifrow.OutDiscards;
  1418. return 0;
  1419. }
  1420. }
  1421. return -1;
  1422. }
  1423. GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
  1424. {
  1425. IP_ADAPTER_ADDRESSES *adptr_addrs, *addr;
  1426. IP_ADAPTER_UNICAST_ADDRESS *ip_addr = NULL;
  1427. GuestNetworkInterfaceList *head = NULL, **tail = &head;
  1428. GuestIpAddressList *head_addr, **tail_addr;
  1429. GuestNetworkInterface *info;
  1430. GuestNetworkInterfaceStat *interface_stat = NULL;
  1431. GuestIpAddress *address_item = NULL;
  1432. unsigned char *mac_addr;
  1433. char *addr_str;
  1434. WORD wsa_version;
  1435. WSADATA wsa_data;
  1436. int ret;
  1437. adptr_addrs = guest_get_adapters_addresses(errp);
  1438. if (adptr_addrs == NULL) {
  1439. return NULL;
  1440. }
  1441. /* Make WSA APIs available. */
  1442. wsa_version = MAKEWORD(2, 2);
  1443. ret = WSAStartup(wsa_version, &wsa_data);
  1444. if (ret != 0) {
  1445. error_setg_win32(errp, ret, "failed socket startup");
  1446. goto out;
  1447. }
  1448. for (addr = adptr_addrs; addr; addr = addr->Next) {
  1449. info = g_malloc0(sizeof(*info));
  1450. QAPI_LIST_APPEND(tail, info);
  1451. info->name = guest_wctomb_dup(addr->FriendlyName);
  1452. if (addr->PhysicalAddressLength != 0) {
  1453. mac_addr = addr->PhysicalAddress;
  1454. info->hardware_address =
  1455. g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
  1456. (int) mac_addr[0], (int) mac_addr[1],
  1457. (int) mac_addr[2], (int) mac_addr[3],
  1458. (int) mac_addr[4], (int) mac_addr[5]);
  1459. }
  1460. head_addr = NULL;
  1461. tail_addr = &head_addr;
  1462. for (ip_addr = addr->FirstUnicastAddress;
  1463. ip_addr;
  1464. ip_addr = ip_addr->Next) {
  1465. addr_str = guest_addr_to_str(ip_addr, errp);
  1466. if (addr_str == NULL) {
  1467. continue;
  1468. }
  1469. address_item = g_malloc0(sizeof(*address_item));
  1470. QAPI_LIST_APPEND(tail_addr, address_item);
  1471. address_item->ip_address = addr_str;
  1472. address_item->prefix = guest_ip_prefix(ip_addr);
  1473. if (ip_addr->Address.lpSockaddr->sa_family == AF_INET) {
  1474. address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
  1475. } else if (ip_addr->Address.lpSockaddr->sa_family == AF_INET6) {
  1476. address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
  1477. }
  1478. }
  1479. if (head_addr) {
  1480. info->has_ip_addresses = true;
  1481. info->ip_addresses = head_addr;
  1482. }
  1483. if (!info->statistics) {
  1484. interface_stat = g_malloc0(sizeof(*interface_stat));
  1485. if (guest_get_network_stats(addr->AdapterName, interface_stat)
  1486. == -1) {
  1487. g_free(interface_stat);
  1488. } else {
  1489. info->statistics = interface_stat;
  1490. }
  1491. }
  1492. }
  1493. WSACleanup();
  1494. out:
  1495. g_free(adptr_addrs);
  1496. return head;
  1497. }
  1498. static int64_t filetime_to_ns(const FILETIME *tf)
  1499. {
  1500. return ((((int64_t)tf->dwHighDateTime << 32) | tf->dwLowDateTime)
  1501. - W32_FT_OFFSET) * 100;
  1502. }
  1503. void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
  1504. {
  1505. Error *local_err = NULL;
  1506. SYSTEMTIME ts;
  1507. FILETIME tf;
  1508. LONGLONG time;
  1509. if (!has_time) {
  1510. /* Unfortunately, Windows libraries don't provide an easy way to access
  1511. * RTC yet:
  1512. *
  1513. * https://msdn.microsoft.com/en-us/library/aa908981.aspx
  1514. *
  1515. * Instead, a workaround is to use the Windows win32tm command to
  1516. * resync the time using the Windows Time service.
  1517. */
  1518. LPVOID msg_buffer;
  1519. DWORD ret_flags;
  1520. HRESULT hr = system("w32tm /resync /nowait");
  1521. if (GetLastError() != 0) {
  1522. strerror_s((LPTSTR) & msg_buffer, 0, errno);
  1523. error_setg(errp, "system(...) failed: %s", (LPCTSTR)msg_buffer);
  1524. } else if (hr != 0) {
  1525. if (hr == HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_ACTIVE)) {
  1526. error_setg(errp, "Windows Time service not running on the "
  1527. "guest");
  1528. } else {
  1529. if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1530. FORMAT_MESSAGE_FROM_SYSTEM |
  1531. FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
  1532. (DWORD)hr, MAKELANGID(LANG_NEUTRAL,
  1533. SUBLANG_DEFAULT), (LPTSTR) & msg_buffer, 0,
  1534. NULL)) {
  1535. error_setg(errp, "w32tm failed with error (0x%lx), couldn'"
  1536. "t retrieve error message", hr);
  1537. } else {
  1538. error_setg(errp, "w32tm failed with error (0x%lx): %s", hr,
  1539. (LPCTSTR)msg_buffer);
  1540. LocalFree(msg_buffer);
  1541. }
  1542. }
  1543. } else if (!InternetGetConnectedState(&ret_flags, 0)) {
  1544. error_setg(errp, "No internet connection on guest, sync not "
  1545. "accurate");
  1546. }
  1547. return;
  1548. }
  1549. /* Validate time passed by user. */
  1550. if (time_ns < 0 || time_ns / 100 > INT64_MAX - W32_FT_OFFSET) {
  1551. error_setg(errp, "Time %" PRId64 "is invalid", time_ns);
  1552. return;
  1553. }
  1554. time = time_ns / 100 + W32_FT_OFFSET;
  1555. tf.dwLowDateTime = (DWORD) time;
  1556. tf.dwHighDateTime = (DWORD) (time >> 32);
  1557. if (!FileTimeToSystemTime(&tf, &ts)) {
  1558. error_setg(errp, "Failed to convert system time %d",
  1559. (int)GetLastError());
  1560. return;
  1561. }
  1562. acquire_privilege(SE_SYSTEMTIME_NAME, &local_err);
  1563. if (local_err) {
  1564. error_propagate(errp, local_err);
  1565. return;
  1566. }
  1567. if (!SetSystemTime(&ts)) {
  1568. error_setg(errp, "Failed to set time to guest: %d", (int)GetLastError());
  1569. return;
  1570. }
  1571. }
  1572. GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
  1573. {
  1574. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION pslpi, ptr;
  1575. DWORD length;
  1576. GuestLogicalProcessorList *head, **tail;
  1577. Error *local_err = NULL;
  1578. int64_t current;
  1579. ptr = pslpi = NULL;
  1580. length = 0;
  1581. current = 0;
  1582. head = NULL;
  1583. tail = &head;
  1584. if ((GetLogicalProcessorInformation(pslpi, &length) == FALSE) &&
  1585. (GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
  1586. (length > sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION))) {
  1587. ptr = pslpi = g_malloc0(length);
  1588. if (GetLogicalProcessorInformation(pslpi, &length) == FALSE) {
  1589. error_setg(&local_err, "Failed to get processor information: %d",
  1590. (int)GetLastError());
  1591. }
  1592. } else {
  1593. error_setg(&local_err,
  1594. "Failed to get processor information buffer length: %d",
  1595. (int)GetLastError());
  1596. }
  1597. while ((local_err == NULL) && (length > 0)) {
  1598. if (pslpi->Relationship == RelationProcessorCore) {
  1599. ULONG_PTR cpu_bits = pslpi->ProcessorMask;
  1600. while (cpu_bits > 0) {
  1601. if (!!(cpu_bits & 1)) {
  1602. GuestLogicalProcessor *vcpu;
  1603. vcpu = g_malloc0(sizeof *vcpu);
  1604. vcpu->logical_id = current++;
  1605. vcpu->online = true;
  1606. vcpu->has_can_offline = true;
  1607. QAPI_LIST_APPEND(tail, vcpu);
  1608. }
  1609. cpu_bits >>= 1;
  1610. }
  1611. }
  1612. length -= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
  1613. pslpi++; /* next entry */
  1614. }
  1615. g_free(ptr);
  1616. if (local_err == NULL) {
  1617. if (head != NULL) {
  1618. return head;
  1619. }
  1620. /* there's no guest with zero VCPUs */
  1621. error_setg(&local_err, "Guest reported zero VCPUs");
  1622. }
  1623. qapi_free_GuestLogicalProcessorList(head);
  1624. error_propagate(errp, local_err);
  1625. return NULL;
  1626. }
  1627. static gchar *
  1628. get_net_error_message(gint error)
  1629. {
  1630. HMODULE module = NULL;
  1631. gchar *retval = NULL;
  1632. wchar_t *msg = NULL;
  1633. int flags;
  1634. size_t nchars;
  1635. flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1636. FORMAT_MESSAGE_IGNORE_INSERTS |
  1637. FORMAT_MESSAGE_FROM_SYSTEM;
  1638. if (error >= NERR_BASE && error <= MAX_NERR) {
  1639. module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);
  1640. if (module != NULL) {
  1641. flags |= FORMAT_MESSAGE_FROM_HMODULE;
  1642. }
  1643. }
  1644. FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);
  1645. if (msg != NULL) {
  1646. nchars = wcslen(msg);
  1647. if (nchars >= 2 &&
  1648. msg[nchars - 1] == L'\n' &&
  1649. msg[nchars - 2] == L'\r') {
  1650. msg[nchars - 2] = L'\0';
  1651. }
  1652. retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);
  1653. LocalFree(msg);
  1654. }
  1655. if (module != NULL) {
  1656. FreeLibrary(module);
  1657. }
  1658. return retval;
  1659. }
  1660. void qmp_guest_set_user_password(const char *username,
  1661. const char *password,
  1662. bool crypted,
  1663. Error **errp)
  1664. {
  1665. NET_API_STATUS nas;
  1666. char *rawpasswddata = NULL;
  1667. size_t rawpasswdlen;
  1668. wchar_t *user = NULL, *wpass = NULL;
  1669. USER_INFO_1003 pi1003 = { 0, };
  1670. GError *gerr = NULL;
  1671. if (crypted) {
  1672. error_setg(errp, "'crypted' must be off on this host");
  1673. return;
  1674. }
  1675. rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
  1676. if (!rawpasswddata) {
  1677. return;
  1678. }
  1679. rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
  1680. rawpasswddata[rawpasswdlen] = '\0';
  1681. user = g_utf8_to_utf16(username, -1, NULL, NULL, &gerr);
  1682. if (!user) {
  1683. error_setg(errp, "can't convert 'username' to UTF-16: %s",
  1684. gerr->message);
  1685. g_error_free(gerr);
  1686. goto done;
  1687. }
  1688. wpass = g_utf8_to_utf16(rawpasswddata, -1, NULL, NULL, &gerr);
  1689. if (!wpass) {
  1690. error_setg(errp, "can't convert 'password' to UTF-16: %s",
  1691. gerr->message);
  1692. g_error_free(gerr);
  1693. goto done;
  1694. }
  1695. pi1003.usri1003_password = wpass;
  1696. nas = NetUserSetInfo(NULL, user,
  1697. 1003, (LPBYTE)&pi1003,
  1698. NULL);
  1699. if (nas != NERR_Success) {
  1700. gchar *msg = get_net_error_message(nas);
  1701. error_setg(errp, "failed to set password: %s", msg);
  1702. g_free(msg);
  1703. }
  1704. done:
  1705. g_free(user);
  1706. g_free(wpass);
  1707. g_free(rawpasswddata);
  1708. }
  1709. /* register init/cleanup routines for stateful command groups */
  1710. void ga_command_state_init(GAState *s, GACommandState *cs)
  1711. {
  1712. if (!vss_initialized()) {
  1713. ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
  1714. }
  1715. }
  1716. /* MINGW is missing two fields: IncomingFrames & OutgoingFrames */
  1717. typedef struct _GA_WTSINFOA {
  1718. WTS_CONNECTSTATE_CLASS State;
  1719. DWORD SessionId;
  1720. DWORD IncomingBytes;
  1721. DWORD OutgoingBytes;
  1722. DWORD IncomingFrames;
  1723. DWORD OutgoingFrames;
  1724. DWORD IncomingCompressedBytes;
  1725. DWORD OutgoingCompressedBy;
  1726. CHAR WinStationName[WINSTATIONNAME_LENGTH];
  1727. CHAR Domain[DOMAIN_LENGTH];
  1728. CHAR UserName[USERNAME_LENGTH + 1];
  1729. LARGE_INTEGER ConnectTime;
  1730. LARGE_INTEGER DisconnectTime;
  1731. LARGE_INTEGER LastInputTime;
  1732. LARGE_INTEGER LogonTime;
  1733. LARGE_INTEGER CurrentTime;
  1734. } GA_WTSINFOA;
  1735. GuestUserList *qmp_guest_get_users(Error **errp)
  1736. {
  1737. #define QGA_NANOSECONDS 10000000
  1738. GHashTable *cache = NULL;
  1739. GuestUserList *head = NULL, **tail = &head;
  1740. DWORD buffer_size = 0, count = 0, i = 0;
  1741. GA_WTSINFOA *info = NULL;
  1742. WTS_SESSION_INFOA *entries = NULL;
  1743. GuestUser *user = NULL;
  1744. gpointer value = NULL;
  1745. INT64 login = 0;
  1746. double login_time = 0;
  1747. cache = g_hash_table_new(g_str_hash, g_str_equal);
  1748. if (WTSEnumerateSessionsA(NULL, 0, 1, &entries, &count)) {
  1749. for (i = 0; i < count; ++i) {
  1750. buffer_size = 0;
  1751. info = NULL;
  1752. if (WTSQuerySessionInformationA(
  1753. NULL,
  1754. entries[i].SessionId,
  1755. WTSSessionInfo,
  1756. (LPSTR *)&info,
  1757. &buffer_size
  1758. )) {
  1759. if (strlen(info->UserName) == 0) {
  1760. WTSFreeMemory(info);
  1761. continue;
  1762. }
  1763. login = info->LogonTime.QuadPart;
  1764. login -= W32_FT_OFFSET;
  1765. login_time = ((double)login) / QGA_NANOSECONDS;
  1766. if (g_hash_table_contains(cache, info->UserName)) {
  1767. value = g_hash_table_lookup(cache, info->UserName);
  1768. user = (GuestUser *)value;
  1769. if (user->login_time > login_time) {
  1770. user->login_time = login_time;
  1771. }
  1772. } else {
  1773. user = g_new0(GuestUser, 1);
  1774. user->user = g_strdup(info->UserName);
  1775. user->domain = g_strdup(info->Domain);
  1776. user->login_time = login_time;
  1777. g_hash_table_add(cache, user->user);
  1778. QAPI_LIST_APPEND(tail, user);
  1779. }
  1780. }
  1781. WTSFreeMemory(info);
  1782. }
  1783. WTSFreeMemory(entries);
  1784. }
  1785. g_hash_table_destroy(cache);
  1786. return head;
  1787. }
  1788. typedef struct _ga_matrix_lookup_t {
  1789. int major;
  1790. int minor;
  1791. const char *version;
  1792. const char *version_id;
  1793. } ga_matrix_lookup_t;
  1794. static const ga_matrix_lookup_t WIN_CLIENT_VERSION_MATRIX[] = {
  1795. { 5, 0, "Microsoft Windows 2000", "2000"},
  1796. { 5, 1, "Microsoft Windows XP", "xp"},
  1797. { 6, 0, "Microsoft Windows Vista", "vista"},
  1798. { 6, 1, "Microsoft Windows 7" "7"},
  1799. { 6, 2, "Microsoft Windows 8", "8"},
  1800. { 6, 3, "Microsoft Windows 8.1", "8.1"},
  1801. { }
  1802. };
  1803. static const ga_matrix_lookup_t WIN_SERVER_VERSION_MATRIX[] = {
  1804. { 5, 2, "Microsoft Windows Server 2003", "2003"},
  1805. { 6, 0, "Microsoft Windows Server 2008", "2008"},
  1806. { 6, 1, "Microsoft Windows Server 2008 R2", "2008r2"},
  1807. { 6, 2, "Microsoft Windows Server 2012", "2012"},
  1808. { 6, 3, "Microsoft Windows Server 2012 R2", "2012r2"},
  1809. { },
  1810. };
  1811. typedef struct _ga_win_10_0_t {
  1812. int first_build;
  1813. const char *version;
  1814. const char *version_id;
  1815. } ga_win_10_0_t;
  1816. static const ga_win_10_0_t WIN_10_0_SERVER_VERSION_MATRIX[] = {
  1817. {14393, "Microsoft Windows Server 2016", "2016"},
  1818. {17763, "Microsoft Windows Server 2019", "2019"},
  1819. {20344, "Microsoft Windows Server 2022", "2022"},
  1820. {26040, "Microsoft Windows Server 2025", "2025"},
  1821. { }
  1822. };
  1823. static const ga_win_10_0_t WIN_10_0_CLIENT_VERSION_MATRIX[] = {
  1824. {10240, "Microsoft Windows 10", "10"},
  1825. {22000, "Microsoft Windows 11", "11"},
  1826. { }
  1827. };
  1828. static void ga_get_win_version(RTL_OSVERSIONINFOEXW *info, Error **errp)
  1829. {
  1830. typedef NTSTATUS(WINAPI *rtl_get_version_t)(
  1831. RTL_OSVERSIONINFOEXW *os_version_info_ex);
  1832. info->dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
  1833. HMODULE module = GetModuleHandle("ntdll");
  1834. PVOID fun = GetProcAddress(module, "RtlGetVersion");
  1835. if (fun == NULL) {
  1836. error_setg(errp, "Failed to get address of RtlGetVersion");
  1837. return;
  1838. }
  1839. rtl_get_version_t rtl_get_version = (rtl_get_version_t)fun;
  1840. rtl_get_version(info);
  1841. return;
  1842. }
  1843. static char *ga_get_win_name(const OSVERSIONINFOEXW *os_version, bool id)
  1844. {
  1845. DWORD major = os_version->dwMajorVersion;
  1846. DWORD minor = os_version->dwMinorVersion;
  1847. DWORD build = os_version->dwBuildNumber;
  1848. int tbl_idx = (os_version->wProductType != VER_NT_WORKSTATION);
  1849. const ga_matrix_lookup_t *table = tbl_idx ?
  1850. WIN_SERVER_VERSION_MATRIX : WIN_CLIENT_VERSION_MATRIX;
  1851. const ga_win_10_0_t *win_10_0_table = tbl_idx ?
  1852. WIN_10_0_SERVER_VERSION_MATRIX : WIN_10_0_CLIENT_VERSION_MATRIX;
  1853. const ga_win_10_0_t *win_10_0_version = NULL;
  1854. while (table->version != NULL) {
  1855. if (major == 10 && minor == 0) {
  1856. while (win_10_0_table->version != NULL) {
  1857. if (build >= win_10_0_table->first_build) {
  1858. win_10_0_version = win_10_0_table;
  1859. }
  1860. win_10_0_table++;
  1861. }
  1862. if (win_10_0_table) {
  1863. if (id) {
  1864. return g_strdup(win_10_0_version->version_id);
  1865. } else {
  1866. return g_strdup(win_10_0_version->version);
  1867. }
  1868. }
  1869. } else if (major == table->major && minor == table->minor) {
  1870. if (id) {
  1871. return g_strdup(table->version_id);
  1872. } else {
  1873. return g_strdup(table->version);
  1874. }
  1875. }
  1876. ++table;
  1877. }
  1878. slog("failed to lookup Windows version: major=%lu, minor=%lu",
  1879. major, minor);
  1880. return g_strdup("N/A");
  1881. }
  1882. static char *ga_get_win_product_name(Error **errp)
  1883. {
  1884. HKEY key = INVALID_HANDLE_VALUE;
  1885. DWORD size = 128;
  1886. char *result = g_malloc0(size);
  1887. LONG err = ERROR_SUCCESS;
  1888. err = RegOpenKeyA(HKEY_LOCAL_MACHINE,
  1889. "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
  1890. &key);
  1891. if (err != ERROR_SUCCESS) {
  1892. error_setg_win32(errp, err, "failed to open registry key");
  1893. g_free(result);
  1894. return NULL;
  1895. }
  1896. err = RegQueryValueExA(key, "ProductName", NULL, NULL,
  1897. (LPBYTE)result, &size);
  1898. if (err == ERROR_MORE_DATA) {
  1899. slog("ProductName longer than expected (%lu bytes), retrying",
  1900. size);
  1901. g_free(result);
  1902. result = NULL;
  1903. if (size > 0) {
  1904. result = g_malloc0(size);
  1905. err = RegQueryValueExA(key, "ProductName", NULL, NULL,
  1906. (LPBYTE)result, &size);
  1907. }
  1908. }
  1909. if (err != ERROR_SUCCESS) {
  1910. error_setg_win32(errp, err, "failed to retrieve ProductName");
  1911. goto fail;
  1912. }
  1913. RegCloseKey(key);
  1914. return result;
  1915. fail:
  1916. if (key != INVALID_HANDLE_VALUE) {
  1917. RegCloseKey(key);
  1918. }
  1919. g_free(result);
  1920. return NULL;
  1921. }
  1922. static char *ga_get_current_arch(void)
  1923. {
  1924. SYSTEM_INFO info;
  1925. GetNativeSystemInfo(&info);
  1926. char *result = NULL;
  1927. switch (info.wProcessorArchitecture) {
  1928. case PROCESSOR_ARCHITECTURE_AMD64:
  1929. result = g_strdup("x86_64");
  1930. break;
  1931. case PROCESSOR_ARCHITECTURE_ARM:
  1932. result = g_strdup("arm");
  1933. break;
  1934. case PROCESSOR_ARCHITECTURE_IA64:
  1935. result = g_strdup("ia64");
  1936. break;
  1937. case PROCESSOR_ARCHITECTURE_INTEL:
  1938. result = g_strdup("x86");
  1939. break;
  1940. case PROCESSOR_ARCHITECTURE_UNKNOWN:
  1941. default:
  1942. slog("unknown processor architecture 0x%0x",
  1943. info.wProcessorArchitecture);
  1944. result = g_strdup("unknown");
  1945. break;
  1946. }
  1947. return result;
  1948. }
  1949. GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
  1950. {
  1951. Error *local_err = NULL;
  1952. OSVERSIONINFOEXW os_version = {0};
  1953. bool server;
  1954. char *product_name;
  1955. GuestOSInfo *info;
  1956. ga_get_win_version(&os_version, &local_err);
  1957. if (local_err) {
  1958. error_propagate(errp, local_err);
  1959. return NULL;
  1960. }
  1961. server = os_version.wProductType != VER_NT_WORKSTATION;
  1962. product_name = ga_get_win_product_name(errp);
  1963. if (product_name == NULL) {
  1964. return NULL;
  1965. }
  1966. info = g_new0(GuestOSInfo, 1);
  1967. info->kernel_version = g_strdup_printf("%lu.%lu",
  1968. os_version.dwMajorVersion,
  1969. os_version.dwMinorVersion);
  1970. info->kernel_release = g_strdup_printf("%lu",
  1971. os_version.dwBuildNumber);
  1972. info->machine = ga_get_current_arch();
  1973. info->id = g_strdup("mswindows");
  1974. info->name = g_strdup("Microsoft Windows");
  1975. info->pretty_name = product_name;
  1976. info->version = ga_get_win_name(&os_version, false);
  1977. info->version_id = ga_get_win_name(&os_version, true);
  1978. info->variant = g_strdup(server ? "server" : "client");
  1979. info->variant_id = g_strdup(server ? "server" : "client");
  1980. return info;
  1981. }
  1982. /*
  1983. * Safely get device property. Returned strings are using wide characters.
  1984. * Caller is responsible for freeing the buffer.
  1985. */
  1986. static LPBYTE cm_get_property(DEVINST devInst, const DEVPROPKEY *propName,
  1987. PDEVPROPTYPE propType)
  1988. {
  1989. CONFIGRET cr;
  1990. g_autofree LPBYTE buffer = NULL;
  1991. ULONG buffer_len = 0;
  1992. /* First query for needed space */
  1993. cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
  1994. buffer, &buffer_len, 0);
  1995. if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) {
  1996. slog("failed to get property size, error=0x%lx", cr);
  1997. return NULL;
  1998. }
  1999. buffer = g_new0(BYTE, buffer_len + 1);
  2000. cr = CM_Get_DevNode_PropertyW(devInst, propName, propType,
  2001. buffer, &buffer_len, 0);
  2002. if (cr != CR_SUCCESS) {
  2003. slog("failed to get device property, error=0x%lx", cr);
  2004. return NULL;
  2005. }
  2006. return g_steal_pointer(&buffer);
  2007. }
  2008. static GStrv ga_get_hardware_ids(DEVINST devInstance)
  2009. {
  2010. GArray *values = NULL;
  2011. DEVPROPTYPE cm_type;
  2012. LPWSTR id;
  2013. g_autofree LPWSTR property = (LPWSTR)cm_get_property(devInstance,
  2014. &qga_DEVPKEY_Device_HardwareIds, &cm_type);
  2015. if (property == NULL) {
  2016. slog("failed to get hardware IDs");
  2017. return NULL;
  2018. }
  2019. if (*property == '\0') {
  2020. /* empty list */
  2021. return NULL;
  2022. }
  2023. values = g_array_new(TRUE, TRUE, sizeof(gchar *));
  2024. for (id = property; '\0' != *id; id += lstrlenW(id) + 1) {
  2025. gchar *id8 = g_utf16_to_utf8(id, -1, NULL, NULL, NULL);
  2026. g_array_append_val(values, id8);
  2027. }
  2028. return (GStrv)g_array_free(values, FALSE);
  2029. }
  2030. /*
  2031. * https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
  2032. */
  2033. #define DEVICE_PCI_RE "PCI\\\\VEN_(1AF4|1B36)&DEV_([0-9A-B]{4})(&|$)"
  2034. GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
  2035. {
  2036. GuestDeviceInfoList *head = NULL, **tail = &head;
  2037. HDEVINFO dev_info = INVALID_HANDLE_VALUE;
  2038. SP_DEVINFO_DATA dev_info_data;
  2039. int i, j;
  2040. GError *gerr = NULL;
  2041. g_autoptr(GRegex) device_pci_re = NULL;
  2042. DEVPROPTYPE cm_type;
  2043. device_pci_re = g_regex_new(DEVICE_PCI_RE,
  2044. G_REGEX_ANCHORED | G_REGEX_OPTIMIZE, 0,
  2045. &gerr);
  2046. g_assert(device_pci_re != NULL);
  2047. dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
  2048. dev_info = SetupDiGetClassDevs(0, 0, 0, DIGCF_PRESENT | DIGCF_ALLCLASSES);
  2049. if (dev_info == INVALID_HANDLE_VALUE) {
  2050. error_setg(errp, "failed to get device tree");
  2051. return NULL;
  2052. }
  2053. slog("enumerating devices");
  2054. for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
  2055. bool skip = true;
  2056. g_autofree LPWSTR name = NULL;
  2057. g_autofree LPFILETIME date = NULL;
  2058. g_autofree LPWSTR version = NULL;
  2059. g_auto(GStrv) hw_ids = NULL;
  2060. g_autoptr(GuestDeviceInfo) device = g_new0(GuestDeviceInfo, 1);
  2061. g_autofree char *vendor_id = NULL;
  2062. g_autofree char *device_id = NULL;
  2063. name = (LPWSTR)cm_get_property(dev_info_data.DevInst,
  2064. &qga_DEVPKEY_NAME, &cm_type);
  2065. if (name == NULL) {
  2066. slog("failed to get device description");
  2067. continue;
  2068. }
  2069. device->driver_name = g_utf16_to_utf8(name, -1, NULL, NULL, NULL);
  2070. if (device->driver_name == NULL) {
  2071. error_setg(errp, "conversion to utf8 failed (driver name)");
  2072. return NULL;
  2073. }
  2074. slog("querying device: %s", device->driver_name);
  2075. hw_ids = ga_get_hardware_ids(dev_info_data.DevInst);
  2076. if (hw_ids == NULL) {
  2077. continue;
  2078. }
  2079. for (j = 0; hw_ids[j] != NULL; j++) {
  2080. g_autoptr(GMatchInfo) match_info;
  2081. GuestDeviceIdPCI *id;
  2082. if (!g_regex_match(device_pci_re, hw_ids[j], 0, &match_info)) {
  2083. continue;
  2084. }
  2085. skip = false;
  2086. vendor_id = g_match_info_fetch(match_info, 1);
  2087. device_id = g_match_info_fetch(match_info, 2);
  2088. device->id = g_new0(GuestDeviceId, 1);
  2089. device->id->type = GUEST_DEVICE_TYPE_PCI;
  2090. id = &device->id->u.pci;
  2091. id->vendor_id = g_ascii_strtoull(vendor_id, NULL, 16);
  2092. id->device_id = g_ascii_strtoull(device_id, NULL, 16);
  2093. break;
  2094. }
  2095. if (skip) {
  2096. continue;
  2097. }
  2098. version = (LPWSTR)cm_get_property(dev_info_data.DevInst,
  2099. &qga_DEVPKEY_Device_DriverVersion, &cm_type);
  2100. if (version == NULL) {
  2101. slog("failed to get driver version");
  2102. continue;
  2103. }
  2104. device->driver_version = g_utf16_to_utf8(version, -1, NULL,
  2105. NULL, NULL);
  2106. if (device->driver_version == NULL) {
  2107. error_setg(errp, "conversion to utf8 failed (driver version)");
  2108. return NULL;
  2109. }
  2110. date = (LPFILETIME)cm_get_property(dev_info_data.DevInst,
  2111. &qga_DEVPKEY_Device_DriverDate, &cm_type);
  2112. if (date == NULL) {
  2113. slog("failed to get driver date");
  2114. continue;
  2115. }
  2116. device->driver_date = filetime_to_ns(date);
  2117. device->has_driver_date = true;
  2118. slog("driver: %s\ndriver version: %" PRId64 ",%s\n",
  2119. device->driver_name, device->driver_date,
  2120. device->driver_version);
  2121. QAPI_LIST_APPEND(tail, g_steal_pointer(&device));
  2122. }
  2123. if (dev_info != INVALID_HANDLE_VALUE) {
  2124. SetupDiDestroyDeviceInfoList(dev_info);
  2125. }
  2126. return head;
  2127. }
  2128. char *qga_get_host_name(Error **errp)
  2129. {
  2130. wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
  2131. DWORD size = G_N_ELEMENTS(tmp);
  2132. if (GetComputerNameW(tmp, &size) == 0) {
  2133. error_setg_win32(errp, GetLastError(), "failed close handle");
  2134. return NULL;
  2135. }
  2136. return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
  2137. }