2 // vss.cpp -- Interface to Volume Shadow Copies (VSS)
4 // Copyright transferred from MATRIX-Computer GmbH to
5 // Kern Sibbald by express permission.
7 // Copyright (C) 2005-2006 Kern Sibbald
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License
11 // version 2 as amended with additional clauses defined in the
12 // file LICENSE in the main source directory.
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // the file LICENSE for additional details.
20 // Author : Thorsten Engel
21 // Created On : Fri May 06 21:44:00 2005
27 #include <sys/types.h>
57 #include <atlcomcli.h>
60 // Used for safe string manipulation
63 #include "../../lib/winapi.h"
66 #pragma message("compile VSS for Windows XP")
67 #define VSSClientGeneric VSSClientXP
69 #include "vss/inc/WinXP/vss.h"
70 #include "vss/inc/WinXP/vswriter.h"
71 #include "vss/inc/WinXP/vsbackup.h"
74 typedef HRESULT (STDAPICALLTYPE* t_CreateVssBackupComponents)(OUT IVssBackupComponents **);
75 typedef void (APIENTRY* t_VssFreeSnapshotProperties)(IN VSS_SNAPSHOT_PROP*);
77 static t_CreateVssBackupComponents p_CreateVssBackupComponents = NULL;
78 static t_VssFreeSnapshotProperties p_VssFreeSnapshotProperties = NULL;
80 #define VSSVBACK_ENTRY "?CreateVssBackupComponents@@YGJPAPAVIVssBackupComponents@@@Z"
84 #pragma message("compile VSS for Windows 2003")
85 #define VSSClientGeneric VSSClient2003
87 #include "vss/inc/Win2003/vss.h"
88 #include "vss/inc/Win2003/vswriter.h"
89 #include "vss/inc/Win2003/vsbackup.h"
92 typedef HRESULT (STDAPICALLTYPE* t_CreateVssBackupComponents)(OUT IVssBackupComponents **);
93 typedef void (APIENTRY* t_VssFreeSnapshotProperties)(IN VSS_SNAPSHOT_PROP*);
95 static t_CreateVssBackupComponents p_CreateVssBackupComponents = NULL;
96 static t_VssFreeSnapshotProperties p_VssFreeSnapshotProperties = NULL;
98 #define VSSVBACK_ENTRY "?CreateVssBackupComponents@@YGJPAPAVIVssBackupComponents@@@Z"
105 * some helper functions
110 // Append a backslash to the current string
111 inline wstring AppendBackslash(wstring str)
113 if (str.length() == 0)
114 return wstring(L"\\");
115 if (str[str.length() - 1] == L'\\')
117 return str.append(L"\\");
120 // Get the unique volume name for the given path
121 inline wstring GetUniqueVolumeNameForPath(wstring path)
123 _ASSERTE(path.length() > 0);
125 // Add the backslash termination, if needed
126 path = AppendBackslash(path);
128 // Get the root path of the volume
129 WCHAR volumeRootPath[MAX_PATH];
130 WCHAR volumeName[MAX_PATH];
131 WCHAR volumeUniqueName[MAX_PATH];
133 if (!p_GetVolumePathNameW || !p_GetVolumePathNameW((LPCWSTR)path.c_str(), volumeRootPath, MAX_PATH))
136 // Get the volume name alias (might be different from the unique volume name in rare cases)
137 if (!p_GetVolumeNameForVolumeMountPointW || !p_GetVolumeNameForVolumeMountPointW(volumeRootPath, volumeName, MAX_PATH))
140 // Get the unique volume name
141 if (!p_GetVolumeNameForVolumeMountPointW(volumeName, volumeUniqueName, MAX_PATH))
144 return volumeUniqueName;
148 // Helper macro for quick treatment of case statements for error codes
149 #define GEN_MERGE(A, B) A##B
150 #define GEN_MAKE_W(A) GEN_MERGE(L, A)
152 #define CHECK_CASE_FOR_CONSTANT(value) \
153 case value: return (GEN_MAKE_W(#value));
156 // Convert a writer status into a string
157 inline const WCHAR* GetStringFromWriterStatus(VSS_WRITER_STATE eWriterStatus)
159 switch (eWriterStatus) {
160 CHECK_CASE_FOR_CONSTANT(VSS_WS_STABLE);
161 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_FREEZE);
162 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_THAW);
163 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_POST_SNAPSHOT);
164 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_BACKUP_COMPLETE);
165 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_IDENTIFY);
166 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PREPARE_BACKUP);
167 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PREPARE_SNAPSHOT);
168 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_FREEZE);
169 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_THAW);
170 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_POST_SNAPSHOT);
171 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_BACKUP_COMPLETE);
172 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PRE_RESTORE);
173 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_POST_RESTORE);
176 return L"Error or Undefined";
182 VSSClientGeneric::VSSClientGeneric()
184 m_hLib = LoadLibraryA("VSSAPI.DLL");
186 p_CreateVssBackupComponents = (t_CreateVssBackupComponents)
187 GetProcAddress(m_hLib, VSSVBACK_ENTRY);
189 p_VssFreeSnapshotProperties = (t_VssFreeSnapshotProperties)
190 GetProcAddress(m_hLib, "VssFreeSnapshotProperties");
197 VSSClientGeneric::~VSSClientGeneric()
203 // Initialize the COM infrastructure and the internal pointers
204 BOOL VSSClientGeneric::Initialize(DWORD dwContext, BOOL bDuringRestore)
206 if (!(p_CreateVssBackupComponents && p_VssFreeSnapshotProperties)) {
213 if (!m_bCoInitializeCalled) {
214 if (FAILED(CoInitialize(NULL))) {
215 errno = b_errno_win32;
218 m_bCoInitializeCalled = true;
221 // Initialize COM security
222 if (!m_bCoInitializeSecurityCalled) {
224 CoInitializeSecurity(
225 NULL, // Allow *all* VSS writers to communicate back!
226 -1, // Default COM authentication service
227 NULL, // Default COM authorization service
228 NULL, // reserved parameter
229 RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // Strongest COM authentication level
230 RPC_C_IMP_LEVEL_IDENTIFY, // Minimal impersonation abilities
231 NULL, // Default COM authentication settings
232 EOAC_NONE, // No special options
233 NULL // Reserved parameter
237 errno = b_errno_win32;
240 m_bCoInitializeSecurityCalled = true;
243 // Release the IVssBackupComponents interface
245 m_pVssObject->Release();
249 // Create the internal backup components object
250 hr = p_CreateVssBackupComponents((IVssBackupComponents**) &m_pVssObject);
252 errno = b_errno_win32;
257 if (dwContext != VSS_CTX_BACKUP) {
258 hr = ((IVssBackupComponents*) m_pVssObject)->SetContext(dwContext);
260 errno = b_errno_win32;
266 if (!bDuringRestore) {
267 // 1. InitializeForBackup
268 hr = ((IVssBackupComponents*) m_pVssObject)->InitializeForBackup();
270 errno = b_errno_win32;
275 hr = ((IVssBackupComponents*) m_pVssObject)->SetBackupState(true, true, VSS_BT_FULL, false);
277 errno = b_errno_win32;
281 CComPtr<IVssAsync> pAsync1;
282 // 3. GatherWriterMetaData
283 hr = ((IVssBackupComponents*) m_pVssObject)->GatherWriterMetadata(&pAsync1);
285 errno = b_errno_win32;
288 // Waits for the async operation to finish and checks the result
289 WaitAndCheckForAsyncOperation(pAsync1);
293 // We are during restore now?
294 m_bDuringRestore = bDuringRestore;
297 m_dwContext = dwContext;
303 BOOL VSSClientGeneric::WaitAndCheckForAsyncOperation(IVssAsync* pAsync)
305 // Wait until the async operation finishes
306 // unfortunately we can't use a timeout here yet.
307 // the interface would allow it on W2k3,
308 // but it is not implemented yet....
312 // Check the result of the asynchronous operation
313 HRESULT hrReturned = S_OK;
315 int timeout = 600; // 10 minutes....
319 if (hrReturned != S_OK)
323 hr = pAsync->QueryStatus(&hrReturned, NULL);
327 } while ((timeout-- > 0) && (hrReturned == VSS_S_ASYNC_PENDING));
329 if (hrReturned == VSS_S_ASYNC_FINISHED)
334 // Check if the async operation succeeded...
335 if(hrReturned != VSS_S_ASYNC_FINISHED) {
336 PWCHAR pwszBuffer = NULL;
337 DWORD dwRet = ::FormatMessageW(
338 FORMAT_MESSAGE_ALLOCATE_BUFFER
339 | FORMAT_MESSAGE_FROM_SYSTEM
340 | FORMAT_MESSAGE_IGNORE_INSERTS,
342 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
343 (LPWSTR)&pwszBuffer, 0, NULL);
346 LocalFree(pwszBuffer);
348 errno = b_errno_win32;
355 BOOL VSSClientGeneric::CreateSnapshots(char* szDriveLetters)
357 /* szDriveLetters contains all drive letters in uppercase */
358 /* if a drive can not being added, it's converted to lowercase in szDriveLetters */
359 /* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vss/base/ivssbackupcomponents_startsnapshotset.asp */
361 if (!m_pVssObject || m_bBackupIsInitialized) {
366 m_uidCurrentSnapshotSet = GUID_NULL;
368 IVssBackupComponents *pVss = (IVssBackupComponents*)m_pVssObject;
370 /* startSnapshotSet */
372 pVss->StartSnapshotSet(&m_uidCurrentSnapshotSet);
374 /* AddToSnapshotSet */
382 CComPtr<IVssAsync> pAsync1;
383 CComPtr<IVssAsync> pAsync2;
386 for (size_t i=0; i < strlen (szDriveLetters); i++) {
387 szDrive[0] = szDriveLetters[i];
388 volume = GetUniqueVolumeNameForPath(szDrive);
389 // store uniquevolumname
390 if (SUCCEEDED(pVss->AddToSnapshotSet((LPWSTR)volume.c_str(), GUID_NULL, &pid)))
391 wcsncpy (m_wszUniqueVolumeName[szDriveLetters[i]-'A'], (LPWSTR) volume.c_str(), MAX_PATH);
394 szDriveLetters[i] = tolower (szDriveLetters[i]);
398 /* PrepareForBackup */
399 if (FAILED(pVss->PrepareForBackup(&pAsync1))) {
403 // Waits for the async operation to finish and checks the result
404 WaitAndCheckForAsyncOperation(pAsync1);
406 /* get latest info about writer status */
407 if (!CheckWriterStatus()) {
412 if (FAILED(pVss->DoSnapshotSet(&pAsync2))) {
416 // Waits for the async operation to finish and checks the result
417 WaitAndCheckForAsyncOperation(pAsync2);
419 /* query snapshot info */
420 QuerySnapshotSet(m_uidCurrentSnapshotSet);
422 m_bBackupIsInitialized = true;
427 BOOL VSSClientGeneric::CloseBackup()
433 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
434 CComPtr<IVssAsync> pAsync;
436 m_bBackupIsInitialized = false;
438 if (SUCCEEDED(pVss->BackupComplete(&pAsync))) {
439 // Waits for the async operation to finish and checks the result
440 WaitAndCheckForAsyncOperation(pAsync);
443 errno = b_errno_win32;
447 /* get latest info about writer status */
450 if (m_uidCurrentSnapshotSet != GUID_NULL) {
451 VSS_ID idNonDeletedSnapshotID = GUID_NULL;
454 pVss->DeleteSnapshots(
455 m_uidCurrentSnapshotSet,
456 VSS_OBJECT_SNAPSHOT_SET,
459 &idNonDeletedSnapshotID);
461 m_uidCurrentSnapshotSet = GUID_NULL;
468 // Call CoUninitialize if the CoInitialize was performed sucesfully
469 if (m_bCoInitializeCalled) {
471 m_bCoInitializeCalled = false;
477 // Query all the shadow copies in the given set
478 void VSSClientGeneric::QuerySnapshotSet(GUID snapshotSetID)
480 if (!(p_CreateVssBackupComponents && p_VssFreeSnapshotProperties)) {
485 memset (m_szShadowCopyName,0,sizeof (m_szShadowCopyName));
487 if (snapshotSetID == GUID_NULL || m_pVssObject == NULL) {
492 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
494 // Get list all shadow copies.
495 CComPtr<IVssEnumObject> pIEnumSnapshots;
496 HRESULT hr = pVss->Query( GUID_NULL,
501 // If there are no shadow copies, just return
503 errno = b_errno_win32;
507 // Enumerate all shadow copies.
508 VSS_OBJECT_PROP Prop;
509 VSS_SNAPSHOT_PROP& Snap = Prop.Obj.Snap;
512 // Get the next element
514 hr = pIEnumSnapshots->Next( 1, &Prop, &ulFetched );
516 // We reached the end of list
520 // Print the shadow copy (if not filtered out)
521 if (Snap.m_SnapshotSetId == snapshotSetID) {
522 for (char ch='A'-'A';ch<='Z'-'A';ch++) {
523 if (wcscmp(Snap.m_pwszOriginalVolumeName, m_wszUniqueVolumeName[ch]) == 0) {
524 wcsncpy (m_szShadowCopyName[ch],Snap.m_pwszSnapshotDeviceObject, MAX_PATH-1);
529 p_VssFreeSnapshotProperties(&Snap);
534 // Check the status for all selected writers
535 BOOL VSSClientGeneric::CheckWriterStatus()
538 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vss/base/ivssbackupcomponents_startsnapshotset.asp
540 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
543 // Gather writer status to detect potential errors
544 CComPtr<IVssAsync> pAsync;
546 HRESULT hr = pVss->GatherWriterStatus(&pAsync);
548 errno = b_errno_win32;
552 // Waits for the async operation to finish and checks the result
553 WaitAndCheckForAsyncOperation(pAsync);
555 unsigned cWriters = 0;
557 hr = pVss->GetWriterStatusCount(&cWriters);
559 errno = b_errno_win32;
565 // Enumerate each writer
566 for (unsigned iWriter = 0; iWriter < cWriters; iWriter++) {
567 VSS_ID idInstance = GUID_NULL;
568 VSS_ID idWriter= GUID_NULL;
569 VSS_WRITER_STATE eWriterStatus = VSS_WS_UNKNOWN;
570 CComBSTR bstrWriterName;
571 HRESULT hrWriterFailure = S_OK;
574 hr = pVss->GetWriterStatus(iWriter,
585 switch(eWriterStatus) {
586 case VSS_WS_FAILED_AT_IDENTIFY:
587 case VSS_WS_FAILED_AT_PREPARE_BACKUP:
588 case VSS_WS_FAILED_AT_PREPARE_SNAPSHOT:
589 case VSS_WS_FAILED_AT_FREEZE:
590 case VSS_WS_FAILED_AT_THAW:
591 case VSS_WS_FAILED_AT_POST_SNAPSHOT:
592 case VSS_WS_FAILED_AT_BACKUP_COMPLETE:
593 case VSS_WS_FAILED_AT_PRE_RESTORE:
594 case VSS_WS_FAILED_AT_POST_RESTORE:
596 case VSS_WS_FAILED_AT_BACKUPSHUTDOWN:
608 /* store text info */
611 itoa(eWriterStatus, szBuf, 16);
614 str.Append (bstrWriterName);
615 str.Append ("\", State: 0x");
618 str.Append (GetStringFromWriterStatus(eWriterStatus));
621 AppendWriterInfo(nState, CW2A(str));
622 // SysFreeString (bstrWriterName);
625 hr = pVss->FreeWriterStatus();
628 errno = b_errno_win32;