forked from MoatLab/FEMU
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands-win32.c
2559 lines (2232 loc) · 77.9 KB
/
commands-win32.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* QEMU Guest Agent win32-specific command implementations
*
* Copyright IBM Corp. 2012
*
* Authors:
* Michael Roth <[email protected]>
* Gal Hammer <[email protected]>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include <wtypes.h>
#include <powrprof.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iptypes.h>
#include <iphlpapi.h>
#ifdef HAVE_NTDDSCSI
#include <winioctl.h>
#include <ntddscsi.h>
#endif
#include <setupapi.h>
#include <cfgmgr32.h>
#include <initguid.h>
#include <devpropdef.h>
#include <lm.h>
#include <wtsapi32.h>
#include <wininet.h>
#include "guest-agent-core.h"
#include "vss-win32.h"
#include "qga-qapi-commands.h"
#include "qapi/error.h"
#include "qapi/qmp/qerror.h"
#include "qemu/queue.h"
#include "qemu/host-utils.h"
#include "qemu/base64.h"
#include "commands-common.h"
/*
* The following should be in devpkey.h, but it isn't. The key names were
* prefixed to avoid (future) name clashes. Once the definitions get into
* mingw the following lines can be removed.
*/
DEFINE_DEVPROPKEY(qga_DEVPKEY_NAME, 0xb725f130, 0x47ef, 0x101a, 0xa5,
0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);
/* DEVPROP_TYPE_STRING */
DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_HardwareIds, 0xa45c254e, 0xdf1c,
0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);
/* DEVPROP_TYPE_STRING_LIST */
DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverDate, 0xa8b865dd, 0x2e3d,
0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);
/* DEVPROP_TYPE_FILETIME */
DEFINE_DEVPROPKEY(qga_DEVPKEY_Device_DriverVersion, 0xa8b865dd, 0x2e3d,
0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);
/* DEVPROP_TYPE_STRING */
/* The CM_Get_DevNode_PropertyW prototype is only sometimes in cfgmgr32.h */
#ifndef CM_Get_DevNode_Property
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
CMAPI CONFIGRET WINAPI CM_Get_DevNode_PropertyW(
DEVINST dnDevInst,
CONST DEVPROPKEY * PropertyKey,
DEVPROPTYPE * PropertyType,
PBYTE PropertyBuffer,
PULONG PropertyBufferSize,
ULONG ulFlags
);
#define CM_Get_DevNode_Property CM_Get_DevNode_PropertyW
#pragma GCC diagnostic pop
#endif
#ifndef SHTDN_REASON_FLAG_PLANNED
#define SHTDN_REASON_FLAG_PLANNED 0x80000000
#endif
/* multiple of 100 nanoseconds elapsed between windows baseline
* (1/1/1601) and Unix Epoch (1/1/1970), accounting for leap years */
#define W32_FT_OFFSET (10000000ULL * 60 * 60 * 24 * \
(365 * (1970 - 1601) + \
(1970 - 1601) / 4 - 3))
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
struct GuestFileHandle {
int64_t id;
HANDLE fh;
QTAILQ_ENTRY(GuestFileHandle) next;
};
static struct {
QTAILQ_HEAD(, GuestFileHandle) filehandles;
} guest_file_state = {
.filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
};
#define FILE_GENERIC_APPEND (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
typedef struct OpenFlags {
const char *forms;
DWORD desired_access;
DWORD creation_disposition;
} OpenFlags;
static OpenFlags guest_file_open_modes[] = {
{"r", GENERIC_READ, OPEN_EXISTING},
{"rb", GENERIC_READ, OPEN_EXISTING},
{"w", GENERIC_WRITE, CREATE_ALWAYS},
{"wb", GENERIC_WRITE, CREATE_ALWAYS},
{"a", FILE_GENERIC_APPEND, OPEN_ALWAYS },
{"r+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
{"rb+", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
{"r+b", GENERIC_WRITE | GENERIC_READ, OPEN_EXISTING},
{"w+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
{"wb+", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
{"w+b", GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS},
{"a+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
{"ab+", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS },
{"a+b", FILE_GENERIC_APPEND | GENERIC_READ, OPEN_ALWAYS }
};
#define debug_error(msg) do { \
char *suffix = g_win32_error_message(GetLastError()); \
g_debug("%s: %s", (msg), suffix); \
g_free(suffix); \
} while (0)
static OpenFlags *find_open_flag(const char *mode_str)
{
int mode;
Error **errp = NULL;
for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
OpenFlags *flags = guest_file_open_modes + mode;
if (strcmp(flags->forms, mode_str) == 0) {
return flags;
}
}
error_setg(errp, "invalid file open mode '%s'", mode_str);
return NULL;
}
static int64_t guest_file_handle_add(HANDLE fh, Error **errp)
{
GuestFileHandle *gfh;
int64_t handle;
handle = ga_get_fd_handle(ga_state, errp);
if (handle < 0) {
return -1;
}
gfh = g_new0(GuestFileHandle, 1);
gfh->id = handle;
gfh->fh = fh;
QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
return handle;
}
GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
{
GuestFileHandle *gfh;
QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next) {
if (gfh->id == id) {
return gfh;
}
}
error_setg(errp, "handle '%" PRId64 "' has not been found", id);
return NULL;
}
static void handle_set_nonblocking(HANDLE fh)
{
DWORD file_type, pipe_state;
file_type = GetFileType(fh);
if (file_type != FILE_TYPE_PIPE) {
return;
}
/* If file_type == FILE_TYPE_PIPE, according to MSDN
* the specified file is socket or named pipe */
if (!GetNamedPipeHandleState(fh, &pipe_state, NULL,
NULL, NULL, NULL, 0)) {
return;
}
/* The fd is named pipe fd */
if (pipe_state & PIPE_NOWAIT) {
return;
}
pipe_state |= PIPE_NOWAIT;
SetNamedPipeHandleState(fh, &pipe_state, NULL, NULL);
}
int64_t qmp_guest_file_open(const char *path, bool has_mode,
const char *mode, Error **errp)
{
int64_t fd = -1;
HANDLE fh;
HANDLE templ_file = NULL;
DWORD share_mode = FILE_SHARE_READ;
DWORD flags_and_attr = FILE_ATTRIBUTE_NORMAL;
LPSECURITY_ATTRIBUTES sa_attr = NULL;
OpenFlags *guest_flags;
GError *gerr = NULL;
wchar_t *w_path = NULL;
if (!has_mode) {
mode = "r";
}
slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
guest_flags = find_open_flag(mode);
if (guest_flags == NULL) {
error_setg(errp, "invalid file open mode");
goto done;
}
w_path = g_utf8_to_utf16(path, -1, NULL, NULL, &gerr);
if (!w_path) {
goto done;
}
fh = CreateFileW(w_path, guest_flags->desired_access, share_mode, sa_attr,
guest_flags->creation_disposition, flags_and_attr,
templ_file);
if (fh == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(), "failed to open file '%s'",
path);
goto done;
}
/* set fd non-blocking to avoid common use cases (like reading from a
* named pipe) from hanging the agent
*/
handle_set_nonblocking(fh);
fd = guest_file_handle_add(fh, errp);
if (fd < 0) {
CloseHandle(fh);
error_setg(errp, "failed to add handle to qmp handle table");
goto done;
}
slog("guest-file-open, handle: % " PRId64, fd);
done:
if (gerr) {
error_setg(errp, QERR_QGA_COMMAND_FAILED, gerr->message);
g_error_free(gerr);
}
g_free(w_path);
return fd;
}
void qmp_guest_file_close(int64_t handle, Error **errp)
{
bool ret;
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
slog("guest-file-close called, handle: %" PRId64, handle);
if (gfh == NULL) {
return;
}
ret = CloseHandle(gfh->fh);
if (!ret) {
error_setg_win32(errp, GetLastError(), "failed close handle");
return;
}
QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
g_free(gfh);
}
static void acquire_privilege(const char *name, Error **errp)
{
HANDLE token = NULL;
TOKEN_PRIVILEGES priv;
Error *local_err = NULL;
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token))
{
if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {
error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
"no luid for requested privilege");
goto out;
}
priv.PrivilegeCount = 1;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {
error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
"unable to acquire requested privilege");
goto out;
}
} else {
error_setg(&local_err, QERR_QGA_COMMAND_FAILED,
"failed to open privilege token");
}
out:
if (token) {
CloseHandle(token);
}
error_propagate(errp, local_err);
}
static void execute_async(DWORD WINAPI (*func)(LPVOID), LPVOID opaque,
Error **errp)
{
HANDLE thread = CreateThread(NULL, 0, func, opaque, 0, NULL);
if (!thread) {
error_setg(errp, QERR_QGA_COMMAND_FAILED,
"failed to dispatch asynchronous command");
}
}
void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
{
Error *local_err = NULL;
UINT shutdown_flag = EWX_FORCE;
slog("guest-shutdown called, mode: %s", mode);
if (!has_mode || strcmp(mode, "powerdown") == 0) {
shutdown_flag |= EWX_POWEROFF;
} else if (strcmp(mode, "halt") == 0) {
shutdown_flag |= EWX_SHUTDOWN;
} else if (strcmp(mode, "reboot") == 0) {
shutdown_flag |= EWX_REBOOT;
} else {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "mode",
"'halt', 'powerdown', or 'reboot'");
return;
}
/* Request a shutdown privilege, but try to shut down the system
anyway. */
acquire_privilege(SE_SHUTDOWN_NAME, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {
g_autofree gchar *emsg = g_win32_error_message(GetLastError());
slog("guest-shutdown failed: %s", emsg);
error_setg_win32(errp, GetLastError(), "guest-shutdown failed");
}
}
GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
int64_t count, Error **errp)
{
GuestFileRead *read_data = NULL;
guchar *buf;
HANDLE fh = gfh->fh;
bool is_ok;
DWORD read_count;
buf = g_malloc0(count + 1);
is_ok = ReadFile(fh, buf, count, &read_count, NULL);
if (!is_ok) {
error_setg_win32(errp, GetLastError(), "failed to read file");
} else {
buf[read_count] = 0;
read_data = g_new0(GuestFileRead, 1);
read_data->count = (size_t)read_count;
read_data->eof = read_count == 0;
if (read_count != 0) {
read_data->buf_b64 = g_base64_encode(buf, read_count);
}
}
g_free(buf);
return read_data;
}
GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
bool has_count, int64_t count,
Error **errp)
{
GuestFileWrite *write_data = NULL;
guchar *buf;
gsize buf_len;
bool is_ok;
DWORD write_count;
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
HANDLE fh;
if (!gfh) {
return NULL;
}
fh = gfh->fh;
buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
if (!buf) {
return NULL;
}
if (!has_count) {
count = buf_len;
} else if (count < 0 || count > buf_len) {
error_setg(errp, "value '%" PRId64
"' is invalid for argument count", count);
goto done;
}
is_ok = WriteFile(fh, buf, count, &write_count, NULL);
if (!is_ok) {
error_setg_win32(errp, GetLastError(), "failed to write to file");
slog("guest-file-write-failed, handle: %" PRId64, handle);
} else {
write_data = g_new0(GuestFileWrite, 1);
write_data->count = (size_t) write_count;
}
done:
g_free(buf);
return write_data;
}
GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
GuestFileWhence *whence_code,
Error **errp)
{
GuestFileHandle *gfh;
GuestFileSeek *seek_data;
HANDLE fh;
LARGE_INTEGER new_pos, off_pos;
off_pos.QuadPart = offset;
BOOL res;
int whence;
Error *err = NULL;
gfh = guest_file_handle_find(handle, errp);
if (!gfh) {
return NULL;
}
/* We stupidly exposed 'whence':'int' in our qapi */
whence = ga_parse_whence(whence_code, &err);
if (err) {
error_propagate(errp, err);
return NULL;
}
fh = gfh->fh;
res = SetFilePointerEx(fh, off_pos, &new_pos, whence);
if (!res) {
error_setg_win32(errp, GetLastError(), "failed to seek file");
return NULL;
}
seek_data = g_new0(GuestFileSeek, 1);
seek_data->position = new_pos.QuadPart;
return seek_data;
}
void qmp_guest_file_flush(int64_t handle, Error **errp)
{
HANDLE fh;
GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
if (!gfh) {
return;
}
fh = gfh->fh;
if (!FlushFileBuffers(fh)) {
error_setg_win32(errp, GetLastError(), "failed to flush file");
}
}
#ifdef HAVE_NTDDSCSI
static GuestDiskBusType win2qemu[] = {
[BusTypeUnknown] = GUEST_DISK_BUS_TYPE_UNKNOWN,
[BusTypeScsi] = GUEST_DISK_BUS_TYPE_SCSI,
[BusTypeAtapi] = GUEST_DISK_BUS_TYPE_IDE,
[BusTypeAta] = GUEST_DISK_BUS_TYPE_IDE,
[BusType1394] = GUEST_DISK_BUS_TYPE_IEEE1394,
[BusTypeSsa] = GUEST_DISK_BUS_TYPE_SSA,
[BusTypeFibre] = GUEST_DISK_BUS_TYPE_SSA,
[BusTypeUsb] = GUEST_DISK_BUS_TYPE_USB,
[BusTypeRAID] = GUEST_DISK_BUS_TYPE_RAID,
[BusTypeiScsi] = GUEST_DISK_BUS_TYPE_ISCSI,
[BusTypeSas] = GUEST_DISK_BUS_TYPE_SAS,
[BusTypeSata] = GUEST_DISK_BUS_TYPE_SATA,
[BusTypeSd] = GUEST_DISK_BUS_TYPE_SD,
[BusTypeMmc] = GUEST_DISK_BUS_TYPE_MMC,
#if (_WIN32_WINNT >= 0x0601)
[BusTypeVirtual] = GUEST_DISK_BUS_TYPE_VIRTUAL,
[BusTypeFileBackedVirtual] = GUEST_DISK_BUS_TYPE_FILE_BACKED_VIRTUAL,
#endif
};
static GuestDiskBusType find_bus_type(STORAGE_BUS_TYPE bus)
{
if (bus >= ARRAY_SIZE(win2qemu) || (int)bus < 0) {
return GUEST_DISK_BUS_TYPE_UNKNOWN;
}
return win2qemu[(int)bus];
}
DEFINE_GUID(GUID_DEVINTERFACE_DISK,
0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2,
0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
DEFINE_GUID(GUID_DEVINTERFACE_STORAGEPORT,
0x2accfe60L, 0xc130, 0x11d2, 0xb0, 0x82,
0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
static void get_pci_address_for_device(GuestPCIAddress *pci,
HDEVINFO dev_info)
{
SP_DEVINFO_DATA dev_info_data;
DWORD j;
DWORD size;
bool partial_pci = false;
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
for (j = 0;
SetupDiEnumDeviceInfo(dev_info, j, &dev_info_data);
j++) {
DWORD addr, bus, ui_slot, type;
int func, slot;
size = sizeof(DWORD);
/*
* There is no need to allocate buffer in the next functions. The
* size is known and ULONG according to
* https://msdn.microsoft.com/en-us/library/windows/hardware/ff543095(v=vs.85).aspx
*/
if (!SetupDiGetDeviceRegistryProperty(
dev_info, &dev_info_data, SPDRP_BUSNUMBER,
&type, (PBYTE)&bus, size, NULL)) {
debug_error("failed to get PCI bus");
bus = -1;
partial_pci = true;
}
/*
* The function retrieves the device's address. This value will be
* transformed into device function and number
*/
if (!SetupDiGetDeviceRegistryProperty(
dev_info, &dev_info_data, SPDRP_ADDRESS,
&type, (PBYTE)&addr, size, NULL)) {
debug_error("failed to get PCI address");
addr = -1;
partial_pci = true;
}
/*
* This call returns UINumber of DEVICE_CAPABILITIES structure.
* This number is typically a user-perceived slot number.
*/
if (!SetupDiGetDeviceRegistryProperty(
dev_info, &dev_info_data, SPDRP_UI_NUMBER,
&type, (PBYTE)&ui_slot, size, NULL)) {
debug_error("failed to get PCI slot");
ui_slot = -1;
partial_pci = true;
}
/*
* SetupApi gives us the same information as driver with
* IoGetDeviceProperty. According to Microsoft:
*
* FunctionNumber = (USHORT)((propertyAddress) & 0x0000FFFF)
* DeviceNumber = (USHORT)(((propertyAddress) >> 16) & 0x0000FFFF)
* SPDRP_ADDRESS is propertyAddress, so we do the same.
*
* https://docs.microsoft.com/en-us/windows/desktop/api/setupapi/nf-setupapi-setupdigetdeviceregistrypropertya
*/
if (partial_pci) {
pci->domain = -1;
pci->slot = -1;
pci->function = -1;
pci->bus = -1;
continue;
} else {
func = ((int)addr == -1) ? -1 : addr & 0x0000FFFF;
slot = ((int)addr == -1) ? -1 : (addr >> 16) & 0x0000FFFF;
if ((int)ui_slot != slot) {
g_debug("mismatch with reported slot values: %d vs %d",
(int)ui_slot, slot);
}
pci->domain = 0;
pci->slot = (int)ui_slot;
pci->function = func;
pci->bus = (int)bus;
return;
}
}
}
static GuestPCIAddress *get_pci_info(int number, Error **errp)
{
HDEVINFO dev_info = INVALID_HANDLE_VALUE;
HDEVINFO parent_dev_info = INVALID_HANDLE_VALUE;
SP_DEVINFO_DATA dev_info_data;
SP_DEVICE_INTERFACE_DATA dev_iface_data;
HANDLE dev_file;
int i;
GuestPCIAddress *pci = NULL;
pci = g_malloc0(sizeof(*pci));
pci->domain = -1;
pci->slot = -1;
pci->function = -1;
pci->bus = -1;
dev_info = SetupDiGetClassDevs(&GUID_DEVINTERFACE_DISK, 0, 0,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (dev_info == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(), "failed to get devices tree");
goto end;
}
g_debug("enumerating devices");
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_iface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
for (i = 0; SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data); i++) {
g_autofree PSP_DEVICE_INTERFACE_DETAIL_DATA pdev_iface_detail_data = NULL;
STORAGE_DEVICE_NUMBER sdn;
g_autofree char *parent_dev_id = NULL;
SP_DEVINFO_DATA parent_dev_info_data;
DWORD size = 0;
g_debug("getting device path");
if (SetupDiEnumDeviceInterfaces(dev_info, &dev_info_data,
&GUID_DEVINTERFACE_DISK, 0,
&dev_iface_data)) {
if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
pdev_iface_detail_data,
size, &size,
&dev_info_data)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
pdev_iface_detail_data = g_malloc(size);
pdev_iface_detail_data->cbSize =
sizeof(*pdev_iface_detail_data);
} else {
error_setg_win32(errp, GetLastError(),
"failed to get device interfaces");
goto end;
}
}
if (!SetupDiGetDeviceInterfaceDetail(dev_info, &dev_iface_data,
pdev_iface_detail_data,
size, &size,
&dev_info_data)) {
// pdev_iface_detail_data already is allocated
error_setg_win32(errp, GetLastError(),
"failed to get device interfaces");
goto end;
}
dev_file = CreateFile(pdev_iface_detail_data->DevicePath, 0,
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
NULL);
if (!DeviceIoControl(dev_file, IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL, 0, &sdn, sizeof(sdn), &size, NULL)) {
CloseHandle(dev_file);
error_setg_win32(errp, GetLastError(),
"failed to get device slot number");
goto end;
}
CloseHandle(dev_file);
if (sdn.DeviceNumber != number) {
continue;
}
} else {
error_setg_win32(errp, GetLastError(),
"failed to get device interfaces");
goto end;
}
g_debug("found device slot %d. Getting storage controller", number);
{
CONFIGRET cr;
DEVINST dev_inst, parent_dev_inst;
ULONG dev_id_size = 0;
size = 0;
if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
parent_dev_id, size, &size)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
parent_dev_id = g_malloc(size);
} else {
error_setg_win32(errp, GetLastError(),
"failed to get device instance ID");
goto end;
}
}
if (!SetupDiGetDeviceInstanceId(dev_info, &dev_info_data,
parent_dev_id, size, &size)) {
// parent_dev_id already is allocated
error_setg_win32(errp, GetLastError(),
"failed to get device instance ID");
goto end;
}
/*
* CM API used here as opposed to
* SetupDiGetDeviceProperty(..., DEVPKEY_Device_Parent, ...)
* which exports are only available in mingw-w64 6+
*/
cr = CM_Locate_DevInst(&dev_inst, parent_dev_id, 0);
if (cr != CR_SUCCESS) {
g_error("CM_Locate_DevInst failed with code %lx", cr);
error_setg_win32(errp, GetLastError(),
"failed to get device instance");
goto end;
}
cr = CM_Get_Parent(&parent_dev_inst, dev_inst, 0);
if (cr != CR_SUCCESS) {
g_error("CM_Get_Parent failed with code %lx", cr);
error_setg_win32(errp, GetLastError(),
"failed to get parent device instance");
goto end;
}
cr = CM_Get_Device_ID_Size(&dev_id_size, parent_dev_inst, 0);
if (cr != CR_SUCCESS) {
g_error("CM_Get_Device_ID_Size failed with code %lx", cr);
error_setg_win32(errp, GetLastError(),
"failed to get parent device ID length");
goto end;
}
++dev_id_size;
if (dev_id_size > size) {
g_free(parent_dev_id);
parent_dev_id = g_malloc(dev_id_size);
}
cr = CM_Get_Device_ID(parent_dev_inst, parent_dev_id, dev_id_size,
0);
if (cr != CR_SUCCESS) {
g_error("CM_Get_Device_ID failed with code %lx", cr);
error_setg_win32(errp, GetLastError(),
"failed to get parent device ID");
goto end;
}
}
g_debug("querying storage controller %s for PCI information",
parent_dev_id);
parent_dev_info =
SetupDiGetClassDevs(&GUID_DEVINTERFACE_STORAGEPORT, parent_dev_id,
NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (parent_dev_info == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(),
"failed to get parent device");
goto end;
}
parent_dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(parent_dev_info, 0, &parent_dev_info_data)) {
error_setg_win32(errp, GetLastError(),
"failed to get parent device data");
goto end;
}
get_pci_address_for_device(pci, parent_dev_info);
break;
}
end:
if (parent_dev_info != INVALID_HANDLE_VALUE) {
SetupDiDestroyDeviceInfoList(parent_dev_info);
}
if (dev_info != INVALID_HANDLE_VALUE) {
SetupDiDestroyDeviceInfoList(dev_info);
}
return pci;
}
static void get_disk_properties(HANDLE vol_h, GuestDiskAddress *disk,
Error **errp)
{
STORAGE_PROPERTY_QUERY query;
STORAGE_DEVICE_DESCRIPTOR *dev_desc, buf;
DWORD received;
ULONG size = sizeof(buf);
dev_desc = &buf;
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
size, &received, NULL)) {
error_setg_win32(errp, GetLastError(), "failed to get bus type");
return;
}
disk->bus_type = find_bus_type(dev_desc->BusType);
g_debug("bus type %d", disk->bus_type);
/* Query once more. Now with long enough buffer. */
size = dev_desc->Size;
dev_desc = g_malloc0(size);
if (!DeviceIoControl(vol_h, IOCTL_STORAGE_QUERY_PROPERTY, &query,
sizeof(STORAGE_PROPERTY_QUERY), dev_desc,
size, &received, NULL)) {
error_setg_win32(errp, GetLastError(), "failed to get serial number");
g_debug("failed to get serial number");
goto out_free;
}
if (dev_desc->SerialNumberOffset > 0) {
const char *serial;
size_t len;
if (dev_desc->SerialNumberOffset >= received) {
error_setg(errp, "failed to get serial number: offset outside the buffer");
g_debug("serial number offset outside the buffer");
goto out_free;
}
serial = (char *)dev_desc + dev_desc->SerialNumberOffset;
len = received - dev_desc->SerialNumberOffset;
g_debug("serial number \"%s\"", serial);
if (*serial != 0) {
disk->serial = g_strndup(serial, len);
disk->has_serial = true;
}
}
out_free:
g_free(dev_desc);
return;
}
static void get_single_disk_info(int disk_number,
GuestDiskAddress *disk, Error **errp)
{
SCSI_ADDRESS addr, *scsi_ad;
DWORD len;
HANDLE disk_h;
Error *local_err = NULL;
scsi_ad = &addr;
g_debug("getting disk info for: %s", disk->dev);
disk_h = CreateFile(disk->dev, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
0, NULL);
if (disk_h == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(), "failed to open disk");
return;
}
get_disk_properties(disk_h, disk, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto err_close;
}
g_debug("bus type %d", disk->bus_type);
/* always set pci_controller as required by schema. get_pci_info() should
* report -1 values for non-PCI buses rather than fail. fail the command
* if that doesn't hold since that suggests some other unexpected
* breakage
*/
disk->pci_controller = get_pci_info(disk_number, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto err_close;
}
if (disk->bus_type == GUEST_DISK_BUS_TYPE_SCSI
|| disk->bus_type == GUEST_DISK_BUS_TYPE_IDE
|| disk->bus_type == GUEST_DISK_BUS_TYPE_RAID
/* This bus type is not supported before Windows Server 2003 SP1 */
|| disk->bus_type == GUEST_DISK_BUS_TYPE_SAS
) {
/* We are able to use the same ioctls for different bus types
* according to Microsoft docs
* https://technet.microsoft.com/en-us/library/ee851589(v=ws.10).aspx */
g_debug("getting SCSI info");
if (DeviceIoControl(disk_h, IOCTL_SCSI_GET_ADDRESS, NULL, 0, scsi_ad,
sizeof(SCSI_ADDRESS), &len, NULL)) {
disk->unit = addr.Lun;
disk->target = addr.TargetId;
disk->bus = addr.PathId;
}
/* We do not set error in this case, because we still have enough
* information about volume. */
}
err_close:
CloseHandle(disk_h);
return;
}
/* VSS provider works with volumes, thus there is no difference if
* the volume consist of spanned disks. Info about the first disk in the
* volume is returned for the spanned disk group (LVM) */
static GuestDiskAddressList *build_guest_disk_info(char *guid, Error **errp)
{
Error *local_err = NULL;
GuestDiskAddressList *list = NULL;
GuestDiskAddress *disk = NULL;
int i;
HANDLE vol_h;
DWORD size;
PVOLUME_DISK_EXTENTS extents = NULL;
/* strip final backslash */
char *name = g_strdup(guid);
if (g_str_has_suffix(name, "\\")) {
name[strlen(name) - 1] = 0;
}
g_debug("opening %s", name);
vol_h = CreateFile(name, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
0, NULL);
if (vol_h == INVALID_HANDLE_VALUE) {
error_setg_win32(errp, GetLastError(), "failed to open volume");
goto out;
}
/* Get list of extents */
g_debug("getting disk extents");
size = sizeof(VOLUME_DISK_EXTENTS);
extents = g_malloc0(size);
if (!DeviceIoControl(vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
0, extents, size, &size, NULL)) {
DWORD last_err = GetLastError();
if (last_err == ERROR_MORE_DATA) {
/* Try once more with big enough buffer */
g_free(extents);
extents = g_malloc0(size);
if (!DeviceIoControl(
vol_h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL,
0, extents, size, NULL, NULL)) {
error_setg_win32(errp, GetLastError(),
"failed to get disk extents");
goto out;
}
} else if (last_err == ERROR_INVALID_FUNCTION) {
/* Possibly CD-ROM or a shared drive. Try to pass the volume */
g_debug("volume not on disk");
disk = g_new0(GuestDiskAddress, 1);
disk->has_dev = true;
disk->dev = g_strdup(name);
get_single_disk_info(0xffffffff, disk, &local_err);
if (local_err) {
g_debug("failed to get disk info, ignoring error: %s",
error_get_pretty(local_err));
error_free(local_err);
goto out;
}
QAPI_LIST_PREPEND(list, disk);
disk = NULL;
goto out;
} else {
error_setg_win32(errp, GetLastError(),
"failed to get disk extents");
goto out;
}
}
g_debug("Number of extents: %lu", extents->NumberOfDiskExtents);
/* Go through each extent */
for (i = 0; i < extents->NumberOfDiskExtents; i++) {
disk = g_new0(GuestDiskAddress, 1);
/* Disk numbers directly correspond to numbers used in UNCs
*
* See documentation for DISK_EXTENT:
* https://docs.microsoft.com/en-us/windows/desktop/api/winioctl/ns-winioctl-_disk_extent
*
* See also Naming Files, Paths and Namespaces:
* https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#win32-device-namespaces
*/
disk->has_dev = true;
disk->dev = g_strdup_printf("\\\\.\\PhysicalDrive%lu",
extents->Extents[i].DiskNumber);
get_single_disk_info(extents->Extents[i].DiskNumber, disk, &local_err);
if (local_err) {
error_propagate(errp, local_err);
goto out;
}
QAPI_LIST_PREPEND(list, disk);
disk = NULL;
}
out:
if (vol_h != INVALID_HANDLE_VALUE) {