2 * QEMU Guest Agent win32 VSS Requester implementations
4 * Copyright Hitachi Data Systems Corp. 2013
7 * Tomoki Sekiyama <tomoki.sekiyama@hds.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
13 #include "qemu/osdep.h"
14 #include "vss-common.h"
15 #include "vss-debug.h"
16 #include "requester.h"
21 /* Max wait time for frozen event (VSS can only hold writes for 10 seconds) */
22 #define VSS_TIMEOUT_FREEZE_MSEC 60000
24 /* Call QueryStatus every 10 ms while waiting for frozen event */
25 #define VSS_TIMEOUT_EVENT_MSEC 10
27 #define DEFAULT_VSS_BACKUP_TYPE VSS_BT_FULL
29 #define err_set(e, err, fmt, ...) { \
30 (e)->error_setg_win32_wrapper((e)->errp, __FILE__, __LINE__, __func__, \
31 err, fmt, ## __VA_ARGS__); \
32 qga_debug(fmt, ## __VA_ARGS__); \
34 /* Bad idea, works only when (e)->errp != NULL: */
35 #define err_is_set(e) ((e)->errp && *(e)->errp)
36 /* To lift this restriction, error_propagate(), like we do in QEMU code */
38 /* Handle to VSSAPI.DLL */
41 /* Functions in VSSAPI.DLL */
42 typedef HRESULT(STDAPICALLTYPE
* t_CreateVssBackupComponents
)(
43 OUT IVssBackupComponents
**);
44 typedef void(APIENTRY
* t_VssFreeSnapshotProperties
)(IN VSS_SNAPSHOT_PROP
*);
45 static t_CreateVssBackupComponents pCreateVssBackupComponents
;
46 static t_VssFreeSnapshotProperties pVssFreeSnapshotProperties
;
48 /* Variables used while applications and filesystes are frozen by VSS */
49 static struct QGAVSSContext
{
50 IVssBackupComponents
*pVssbc
; /* VSS requester interface */
51 IVssAsync
*pAsyncSnapshot
; /* async info of VSS snapshot operation */
52 HANDLE hEventFrozen
; /* notify fs/writer freeze from provider */
53 HANDLE hEventThaw
; /* request provider to thaw */
54 HANDLE hEventTimeout
; /* notify timeout in provider */
55 int cFrozenVols
; /* number of frozen volumes */
58 STDAPI
requester_init(void)
62 COMInitializer initializer
; /* to call CoInitializeSecurity */
63 HRESULT hr
= CoInitializeSecurity(
64 NULL
, -1, NULL
, NULL
, RPC_C_AUTHN_LEVEL_PKT_PRIVACY
,
65 RPC_C_IMP_LEVEL_IDENTIFY
, NULL
, EOAC_NONE
, NULL
);
67 qga_debug("failed to CoInitializeSecurity (error %lx)", hr
);
71 hLib
= LoadLibraryA("VSSAPI.DLL");
73 qga_debug("failed to load VSSAPI.DLL");
74 return HRESULT_FROM_WIN32(GetLastError());
77 pCreateVssBackupComponents
= (t_CreateVssBackupComponents
)
79 #ifdef _WIN64 /* 64bit environment */
80 "?CreateVssBackupComponents@@YAJPEAPEAVIVssBackupComponents@@@Z"
81 #else /* 32bit environment */
82 "?CreateVssBackupComponents@@YGJPAPAVIVssBackupComponents@@@Z"
85 if (!pCreateVssBackupComponents
) {
86 qga_debug("failed to get proc address from VSSAPI.DLL");
87 return HRESULT_FROM_WIN32(GetLastError());
90 pVssFreeSnapshotProperties
= (t_VssFreeSnapshotProperties
)
91 GetProcAddress(hLib
, "VssFreeSnapshotProperties");
92 if (!pVssFreeSnapshotProperties
) {
93 qga_debug("failed to get proc address from VSSAPI.DLL");
94 return HRESULT_FROM_WIN32(GetLastError());
101 static void requester_cleanup(void)
105 if (vss_ctx
.hEventFrozen
) {
106 CloseHandle(vss_ctx
.hEventFrozen
);
107 vss_ctx
.hEventFrozen
= NULL
;
109 if (vss_ctx
.hEventThaw
) {
110 CloseHandle(vss_ctx
.hEventThaw
);
111 vss_ctx
.hEventThaw
= NULL
;
113 if (vss_ctx
.hEventTimeout
) {
114 CloseHandle(vss_ctx
.hEventTimeout
);
115 vss_ctx
.hEventTimeout
= NULL
;
117 if (vss_ctx
.pAsyncSnapshot
) {
118 vss_ctx
.pAsyncSnapshot
->Release();
119 vss_ctx
.pAsyncSnapshot
= NULL
;
121 if (vss_ctx
.pVssbc
) {
122 vss_ctx
.pVssbc
->Release();
123 vss_ctx
.pVssbc
= NULL
;
125 vss_ctx
.cFrozenVols
= 0;
129 STDAPI
requester_deinit(void)
135 pCreateVssBackupComponents
= NULL
;
136 pVssFreeSnapshotProperties
= NULL
;
146 static HRESULT
WaitForAsync(IVssAsync
*pAsync
)
158 hr
= pAsync
->QueryStatus(&ret
, NULL
);
163 } while (ret
== VSS_S_ASYNC_PENDING
);
169 static void AddComponents(ErrorSet
*errset
)
173 unsigned int cWriters
, i
;
174 VSS_ID id
, idInstance
, idWriter
;
175 BSTR bstrWriterName
= NULL
;
176 VSS_USAGE_TYPE usage
;
177 VSS_SOURCE_TYPE source
;
178 unsigned int cComponents
, c1
, c2
, j
;
179 COMPointer
<IVssExamineWriterMetadata
> pMetadata
;
180 COMPointer
<IVssWMComponent
> pComponent
;
181 PVSSCOMPONENTINFO info
;
184 hr
= vss_ctx
.pVssbc
->GetWriterMetadataCount(&cWriters
);
186 err_set(errset
, hr
, "failed to get writer metadata count");
190 for (i
= 0; i
< cWriters
; i
++) {
191 hr
= vss_ctx
.pVssbc
->GetWriterMetadata(i
, &id
, pMetadata
.replace());
193 err_set(errset
, hr
, "failed to get writer metadata of %d/%d",
198 hr
= pMetadata
->GetIdentity(&idInstance
, &idWriter
,
199 &bstrWriterName
, &usage
, &source
);
201 err_set(errset
, hr
, "failed to get identity of writer %d/%d",
206 hr
= pMetadata
->GetFileCounts(&c1
, &c2
, &cComponents
);
208 err_set(errset
, hr
, "failed to get file counts of %S",
213 for (j
= 0; j
< cComponents
; j
++) {
214 hr
= pMetadata
->GetComponent(j
, pComponent
.replace());
217 "failed to get component %d/%d of %S",
218 j
, cComponents
, bstrWriterName
);
222 hr
= pComponent
->GetComponentInfo(&info
);
225 "failed to get component info %d/%d of %S",
226 j
, cComponents
, bstrWriterName
);
230 if (info
->bSelectable
) {
231 hr
= vss_ctx
.pVssbc
->AddComponent(idInstance
, idWriter
,
233 info
->bstrLogicalPath
,
234 info
->bstrComponentName
);
236 err_set(errset
, hr
, "failed to add component %S(%S)",
237 info
->bstrComponentName
, bstrWriterName
);
241 SysFreeString(bstrWriterName
);
242 bstrWriterName
= NULL
;
243 pComponent
->FreeComponentInfo(info
);
248 if (bstrWriterName
) {
249 SysFreeString(bstrWriterName
);
251 if (pComponent
&& info
) {
252 pComponent
->FreeComponentInfo(info
);
257 DWORD
get_reg_dword_value(HKEY baseKey
, LPCSTR subKey
, LPCSTR valueName
,
262 DWORD regGetValueError
;
264 DWORD dataSize
= sizeof(DWORD
);
266 regGetValueError
= RegGetValue(baseKey
, subKey
, valueName
, RRF_RT_DWORD
,
267 NULL
, &dwordData
, &dataSize
);
269 if (regGetValueError
!= ERROR_SUCCESS
) {
275 bool is_valid_vss_backup_type(VSS_BACKUP_TYPE vssBT
)
277 return (vssBT
> VSS_BT_UNDEFINED
&& vssBT
< VSS_BT_OTHER
);
280 VSS_BACKUP_TYPE
get_vss_backup_type(
281 VSS_BACKUP_TYPE defaultVssBT
= DEFAULT_VSS_BACKUP_TYPE
)
285 VSS_BACKUP_TYPE vssBackupType
;
287 vssBackupType
= static_cast<VSS_BACKUP_TYPE
>(
288 get_reg_dword_value(HKEY_LOCAL_MACHINE
,
289 QGA_PROVIDER_REGISTRY_ADDRESS
,
293 if (!is_valid_vss_backup_type(vssBackupType
)) {
296 return vssBackupType
;
299 void requester_freeze(int *num_vols
, void *mountpoints
, ErrorSet
*errset
)
303 COMPointer
<IVssAsync
> pAsync
;
307 GUID guidSnapshotSet
= GUID_NULL
;
308 SECURITY_DESCRIPTOR sd
;
309 SECURITY_ATTRIBUTES sa
;
310 WCHAR short_volume_name
[64], *display_name
= short_volume_name
;
312 int num_fixed_drives
= 0, i
;
313 int num_mount_points
= 0;
314 VSS_BACKUP_TYPE vss_bt
= get_vss_backup_type();
316 if (vss_ctx
.pVssbc
) { /* already frozen */
318 qga_debug("finished, already frozen");
324 /* Allow unrestricted access to events */
325 InitializeSecurityDescriptor(&sd
, SECURITY_DESCRIPTOR_REVISION
);
326 SetSecurityDescriptorDacl(&sd
, TRUE
, NULL
, FALSE
);
327 sa
.nLength
= sizeof(sa
);
328 sa
.lpSecurityDescriptor
= &sd
;
329 sa
.bInheritHandle
= FALSE
;
331 vss_ctx
.hEventFrozen
= CreateEvent(&sa
, TRUE
, FALSE
, EVENT_NAME_FROZEN
);
332 if (!vss_ctx
.hEventFrozen
) {
333 err_set(errset
, GetLastError(), "failed to create event %s",
337 vss_ctx
.hEventThaw
= CreateEvent(&sa
, TRUE
, FALSE
, EVENT_NAME_THAW
);
338 if (!vss_ctx
.hEventThaw
) {
339 err_set(errset
, GetLastError(), "failed to create event %s",
343 vss_ctx
.hEventTimeout
= CreateEvent(&sa
, TRUE
, FALSE
, EVENT_NAME_TIMEOUT
);
344 if (!vss_ctx
.hEventTimeout
) {
345 err_set(errset
, GetLastError(), "failed to create event %s",
350 assert(pCreateVssBackupComponents
!= NULL
);
351 hr
= pCreateVssBackupComponents(&vss_ctx
.pVssbc
);
353 err_set(errset
, hr
, "failed to create VSS backup components");
357 hr
= vss_ctx
.pVssbc
->InitializeForBackup();
359 err_set(errset
, hr
, "failed to initialize for backup");
363 hr
= vss_ctx
.pVssbc
->SetBackupState(true, true, vss_bt
, false);
365 err_set(errset
, hr
, "failed to set backup state");
370 * Currently writable snapshots are not supported.
371 * To prevent the final commit (which requires to write to snapshots),
372 * ATTR_NO_AUTORECOVERY and ATTR_TRANSPORTABLE are specified here.
374 ctx
= VSS_CTX_APP_ROLLBACK
| VSS_VOLSNAP_ATTR_TRANSPORTABLE
|
375 VSS_VOLSNAP_ATTR_NO_AUTORECOVERY
| VSS_VOLSNAP_ATTR_TXF_RECOVERY
;
376 hr
= vss_ctx
.pVssbc
->SetContext(ctx
);
377 if (hr
== (HRESULT
)VSS_E_UNSUPPORTED_CONTEXT
) {
378 /* Non-server version of Windows doesn't support ATTR_TRANSPORTABLE */
379 ctx
&= ~VSS_VOLSNAP_ATTR_TRANSPORTABLE
;
380 hr
= vss_ctx
.pVssbc
->SetContext(ctx
);
383 err_set(errset
, hr
, "failed to set backup context");
387 hr
= vss_ctx
.pVssbc
->GatherWriterMetadata(pAsync
.replace());
389 hr
= WaitForAsync(pAsync
);
392 err_set(errset
, hr
, "failed to gather writer metadata");
396 AddComponents(errset
);
397 if (err_is_set(errset
)) {
401 hr
= vss_ctx
.pVssbc
->StartSnapshotSet(&guidSnapshotSet
);
403 err_set(errset
, hr
, "failed to start snapshot set");
408 PWCHAR volume_name_wchar
;
409 for (volList
*list
= (volList
*)mountpoints
; list
; list
= list
->next
) {
410 size_t len
= strlen(list
->value
) + 1;
411 size_t converted
= 0;
414 volume_name_wchar
= new wchar_t[len
];
415 mbstowcs_s(&converted
, volume_name_wchar
, len
,
416 list
->value
, _TRUNCATE
);
418 hr
= vss_ctx
.pVssbc
->AddToSnapshotSet(volume_name_wchar
,
419 g_gProviderId
, &pid
);
421 err_set(errset
, hr
, "failed to add %S to snapshot set",
423 delete[] volume_name_wchar
;
428 delete[] volume_name_wchar
;
431 if (num_mount_points
== 0) {
432 /* If there is no valid mount points, just exit. */
438 volume
= FindFirstVolumeW(short_volume_name
, sizeof(short_volume_name
));
439 if (volume
== INVALID_HANDLE_VALUE
) {
440 err_set(errset
, hr
, "failed to find first volume");
445 if (GetDriveTypeW(short_volume_name
) == DRIVE_FIXED
) {
447 hr
= vss_ctx
.pVssbc
->AddToSnapshotSet(short_volume_name
,
448 g_gProviderId
, &pid
);
450 WCHAR volume_path_name
[PATH_MAX
];
451 if (GetVolumePathNamesForVolumeNameW(
452 short_volume_name
, volume_path_name
,
453 sizeof(volume_path_name
), NULL
) &&
455 display_name
= volume_path_name
;
457 err_set(errset
, hr
, "failed to add %S to snapshot set",
459 FindVolumeClose(volume
);
464 if (!FindNextVolumeW(volume
, short_volume_name
,
465 sizeof(short_volume_name
))) {
466 FindVolumeClose(volume
);
471 if (num_fixed_drives
== 0) {
472 goto out
; /* If there is no fixed drive, just exit. */
476 qga_debug("preparing for backup");
477 hr
= vss_ctx
.pVssbc
->PrepareForBackup(pAsync
.replace());
479 hr
= WaitForAsync(pAsync
);
482 err_set(errset
, hr
, "failed to prepare for backup");
486 hr
= vss_ctx
.pVssbc
->GatherWriterStatus(pAsync
.replace());
488 hr
= WaitForAsync(pAsync
);
491 err_set(errset
, hr
, "failed to gather writer status");
496 * Start VSS quiescing operations.
497 * CQGAVssProvider::CommitSnapshots will kick vss_ctx.hEventFrozen
498 * after the applications and filesystems are frozen.
500 qga_debug("do snapshot set");
501 hr
= vss_ctx
.pVssbc
->DoSnapshotSet(&vss_ctx
.pAsyncSnapshot
);
503 err_set(errset
, hr
, "failed to do snapshot set");
507 /* Need to call QueryStatus several times to make VSS provider progress */
508 for (i
= 0; i
< VSS_TIMEOUT_FREEZE_MSEC
/VSS_TIMEOUT_EVENT_MSEC
; i
++) {
509 HRESULT hr2
= vss_ctx
.pAsyncSnapshot
->QueryStatus(&hr
, NULL
);
511 err_set(errset
, hr
, "failed to do snapshot set");
514 if (hr
!= VSS_S_ASYNC_PENDING
) {
515 err_set(errset
, E_FAIL
,
516 "DoSnapshotSet exited without Frozen event");
519 wait_status
= WaitForSingleObject(vss_ctx
.hEventFrozen
,
520 VSS_TIMEOUT_EVENT_MSEC
);
521 if (wait_status
!= WAIT_TIMEOUT
) {
526 if (wait_status
== WAIT_TIMEOUT
) {
527 err_set(errset
, E_FAIL
,
528 "timeout when try to receive Frozen event from VSS provider");
529 /* If we are here, VSS had timeout.
530 * Don't call AbortBackup, just return directly.
535 if (wait_status
!= WAIT_OBJECT_0
) {
536 err_set(errset
, E_FAIL
,
537 "couldn't receive Frozen event from VSS provider");
542 *num_vols
= vss_ctx
.cFrozenVols
= num_mount_points
;
544 *num_vols
= vss_ctx
.cFrozenVols
= num_fixed_drives
;
547 qga_debug("end successful");
551 if (vss_ctx
.pVssbc
) {
552 vss_ctx
.pVssbc
->AbortBackup();
563 void requester_thaw(int *num_vols
, void *mountpints
, ErrorSet
*errset
)
566 COMPointer
<IVssAsync
> pAsync
;
568 if (!vss_ctx
.hEventThaw
) {
570 * In this case, DoSnapshotSet is aborted or not started,
571 * and no volumes must be frozen. We return without an error.
574 qga_debug("finished, no volumes were frozen");
579 /* Tell the provider that the snapshot is finished. */
580 SetEvent(vss_ctx
.hEventThaw
);
582 assert(vss_ctx
.pVssbc
);
583 assert(vss_ctx
.pAsyncSnapshot
);
585 HRESULT hr
= WaitForAsync(vss_ctx
.pAsyncSnapshot
);
587 case VSS_S_ASYNC_FINISHED
:
588 hr
= vss_ctx
.pVssbc
->BackupComplete(pAsync
.replace());
590 hr
= WaitForAsync(pAsync
);
593 err_set(errset
, hr
, "failed to complete backup");
597 case (HRESULT
)VSS_E_OBJECT_NOT_FOUND
:
599 * On Windows earlier than 2008 SP2 which does not support
600 * VSS_VOLSNAP_ATTR_NO_AUTORECOVERY context, the final commit is not
601 * skipped and VSS is aborted by VSS_E_OBJECT_NOT_FOUND. However, as
602 * the system had been frozen until fsfreeze-thaw command was issued,
603 * we ignore this error.
605 vss_ctx
.pVssbc
->AbortBackup();
608 case VSS_E_UNEXPECTED_PROVIDER_ERROR
:
609 if (WaitForSingleObject(vss_ctx
.hEventTimeout
, 0) != WAIT_OBJECT_0
) {
610 err_set(errset
, hr
, "unexpected error in VSS provider");
613 /* fall through if hEventTimeout is signaled */
615 case (HRESULT
)VSS_E_HOLD_WRITES_TIMEOUT
:
616 err_set(errset
, hr
, "couldn't hold writes: "
617 "fsfreeze is limited up to 10 seconds");
621 err_set(errset
, hr
, "failed to do snapshot set");
624 if (err_is_set(errset
)) {
625 vss_ctx
.pVssbc
->AbortBackup();
627 *num_vols
= vss_ctx
.cFrozenVols
;