commands-win32.c 77 KB

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