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 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>
59 #include <atlcomcli.h>
62 // Used for safe string manipulation
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 (!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 (!GetVolumeNameForVolumeMountPointW(volumeRootPath, volumeName, MAX_PATH))
140 // Get the unique volume name
141 if (!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 wstring(GEN_MAKE_W(#value));
156 // Convert a writer status into a string
157 inline wstring GetStringFromWriterStatus(VSS_WRITER_STATE eWriterStatus)
159 switch (eWriterStatus)
161 CHECK_CASE_FOR_CONSTANT(VSS_WS_STABLE);
162 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_FREEZE);
163 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_THAW);
164 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_POST_SNAPSHOT);
165 CHECK_CASE_FOR_CONSTANT(VSS_WS_WAITING_FOR_BACKUP_COMPLETE);
166 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_IDENTIFY);
167 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PREPARE_BACKUP);
168 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PREPARE_SNAPSHOT);
169 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_FREEZE);
170 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_THAW);
171 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_POST_SNAPSHOT);
172 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_BACKUP_COMPLETE);
173 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_PRE_RESTORE);
174 CHECK_CASE_FOR_CONSTANT(VSS_WS_FAILED_AT_POST_RESTORE);
177 return wstring(L"Undefined");
183 VSSClientGeneric::VSSClientGeneric()
185 m_hLib = LoadLibraryA("VSSAPI.DLL");
187 p_CreateVssBackupComponents = (t_CreateVssBackupComponents)
188 GetProcAddress(m_hLib, VSSVBACK_ENTRY);
190 p_VssFreeSnapshotProperties = (t_VssFreeSnapshotProperties)
191 GetProcAddress(m_hLib, "VssFreeSnapshotProperties");
198 VSSClientGeneric::~VSSClientGeneric()
204 // Initialize the COM infrastructure and the internal pointers
205 BOOL VSSClientGeneric::Initialize(DWORD dwContext, BOOL bDuringRestore)
207 if (!(p_CreateVssBackupComponents && p_VssFreeSnapshotProperties))
212 if (!m_bCoInitializeCalled) {
213 if (FAILED(CoInitialize(NULL)))
216 m_bCoInitializeCalled = true;
218 // Initialize COM security
220 CoInitializeSecurity(
221 NULL, // Allow *all* VSS writers to communicate back!
222 -1, // Default COM authentication service
223 NULL, // Default COM authorization service
224 NULL, // reserved parameter
225 RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // Strongest COM authentication level
226 RPC_C_IMP_LEVEL_IDENTIFY, // Minimal impersonation abilities
227 NULL, // Default COM authentication settings
228 EOAC_NONE, // No special options
229 NULL // Reserved parameter
236 // Release the IVssBackupComponents interface
238 m_pVssObject->Release();
242 // Create the internal backup components object
243 hr = p_CreateVssBackupComponents((IVssBackupComponents**) &m_pVssObject);
248 if (dwContext != VSS_CTX_BACKUP) {
249 hr = ((IVssBackupComponents*) m_pVssObject)->SetContext(dwContext);
255 // We are during restore now?
256 m_bDuringRestore = bDuringRestore;
259 m_dwContext = dwContext;
265 void VSSClientGeneric::WaitAndCheckForAsyncOperation(IVssAsync* pAsync)
267 // Wait until the async operation finishes
268 HRESULT hr = pAsync->Wait();
270 // Check the result of the asynchronous operation
271 HRESULT hrReturned = S_OK;
272 hr = pAsync->QueryStatus(&hrReturned, NULL);
274 // Check if the async operation succeeded...
275 if(FAILED(hrReturned))
277 PWCHAR pwszBuffer = NULL;
278 DWORD dwRet = ::FormatMessageW(
279 FORMAT_MESSAGE_ALLOCATE_BUFFER
280 | FORMAT_MESSAGE_FROM_SYSTEM
281 | FORMAT_MESSAGE_IGNORE_INSERTS,
283 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
284 (LPWSTR)&pwszBuffer, 0, NULL);
286 // No message found for this error. Just return <Unknown>
289 // Convert the message into wstring
291 LocalFree(pwszBuffer);
296 BOOL VSSClientGeneric::CreateSnapshots(char* szDriveLetters)
298 /* szDriveLetters contains all drive letters in uppercase */
299 /* if a drive can not being added, it's converted to lowercase in szDriveLetters */
300 /* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vss/base/ivssbackupcomponents_startsnapshotset.asp */
302 if (!m_pVssObject || m_bBackupIsInitialized)
305 m_uidCurrentSnapshotSet = GUID_NULL;
307 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
309 // 1. InitializeForBackup
310 HRESULT hr = pVss->InitializeForBackup();
315 hr = pVss->SetBackupState(true, true, VSS_BT_FULL, false);
319 CComPtr<IVssAsync> pAsync1;
320 CComPtr<IVssAsync> pAsync2;
321 CComPtr<IVssAsync> pAsync3;
324 // 3. GatherWriterMetaData
325 hr = pVss->GatherWriterMetadata(&pAsync3);
329 // Waits for the async operation to finish and checks the result
330 WaitAndCheckForAsyncOperation(pAsync3);
334 // 4. startSnapshotSet
336 pVss->StartSnapshotSet(&m_uidCurrentSnapshotSet);
338 // 4. AddToSnapshotSet
346 for (size_t i=0; i < strlen (szDriveLetters); i++) {
347 szDrive[0] = szDriveLetters[i];
348 volume = GetUniqueVolumeNameForPath(szDrive);
349 // store uniquevolumname
350 if (SUCCEEDED(pVss->AddToSnapshotSet((LPWSTR)volume.c_str(), GUID_NULL, &pid)))
351 wcsncpy (m_wszUniqueVolumeName[szDriveLetters[i]-'A'], (LPWSTR) volume.c_str(), MAX_PATH);
353 szDriveLetters[i] = tolower (szDriveLetters[i]);
356 // 5. PrepareForBackup
357 pVss->PrepareForBackup(&pAsync1);
359 // Waits for the async operation to finish and checks the result
360 WaitAndCheckForAsyncOperation(pAsync1);
363 pVss->DoSnapshotSet(&pAsync2);
365 // Waits for the async operation to finish and checks the result
366 WaitAndCheckForAsyncOperation(pAsync2);
368 /* query snapshot info */
369 QuerySnapshotSet(m_uidCurrentSnapshotSet);
371 m_bBackupIsInitialized = true;
376 BOOL VSSClientGeneric::CloseBackup()
382 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
383 CComPtr<IVssAsync> pAsync;
385 m_bBackupIsInitialized = false;
387 if (SUCCEEDED(pVss->BackupComplete(&pAsync))) {
388 // Waits for the async operation to finish and checks the result
389 WaitAndCheckForAsyncOperation(pAsync);
396 if (m_uidCurrentSnapshotSet != GUID_NULL) {
397 VSS_ID idNonDeletedSnapshotID = GUID_NULL;
400 pVss->DeleteSnapshots(
401 m_uidCurrentSnapshotSet,
402 VSS_OBJECT_SNAPSHOT_SET,
405 &idNonDeletedSnapshotID);
407 m_uidCurrentSnapshotSet = GUID_NULL;
417 // Query all the shadow copies in the given set
418 void VSSClientGeneric::QuerySnapshotSet(GUID snapshotSetID)
420 if (!(p_CreateVssBackupComponents && p_VssFreeSnapshotProperties))
423 memset (m_szShadowCopyName,0,sizeof (m_szShadowCopyName));
425 if (snapshotSetID == GUID_NULL || m_pVssObject == NULL)
428 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
430 // Get list all shadow copies.
431 CComPtr<IVssEnumObject> pIEnumSnapshots;
432 HRESULT hr = pVss->Query( GUID_NULL,
437 // If there are no shadow copies, just return
441 // Enumerate all shadow copies.
442 VSS_OBJECT_PROP Prop;
443 VSS_SNAPSHOT_PROP& Snap = Prop.Obj.Snap;
447 // Get the next element
449 hr = pIEnumSnapshots->Next( 1, &Prop, &ulFetched );
451 // We reached the end of list
455 // Print the shadow copy (if not filtered out)
456 if (Snap.m_SnapshotSetId == snapshotSetID) {
457 for (char ch='A'-'A';ch<='Z'-'A';ch++) {
458 if (wcscmp(Snap.m_pwszOriginalVolumeName, m_wszUniqueVolumeName[ch]) == 0) {
459 WideCharToMultiByte(CP_UTF8,0,Snap.m_pwszSnapshotDeviceObject,-1,m_szShadowCopyName[ch],MAX_PATH*2,NULL,NULL);
464 p_VssFreeSnapshotProperties(&Snap);
468 // Check the status for all selected writers
469 BOOL VSSClientGeneric::CheckWriterStatus()
471 IVssBackupComponents* pVss = (IVssBackupComponents*) m_pVssObject;
472 vector<int>* pVWriterStates = (vector<int>*) m_pVectorWriterStates;
473 vector<string>* pVWriterInfo = (vector<string>*) m_pVectorWriterInfo;
475 pVWriterStates->clear();
476 pVWriterInfo->clear();
478 // Gather writer status to detect potential errors
479 CComPtr<IVssAsync> pAsync;
481 HRESULT hr = pVss->GatherWriterStatus(&pAsync);
485 // Waits for the async operation to finish and checks the result
486 WaitAndCheckForAsyncOperation(pAsync);
488 unsigned cWriters = 0;
490 hr = pVss->GetWriterStatusCount(&cWriters);
494 // Enumerate each writer
495 for(unsigned iWriter = 0; iWriter < cWriters; iWriter++)
497 VSS_ID idInstance = GUID_NULL;
498 VSS_ID idWriter= GUID_NULL;
499 VSS_WRITER_STATE eWriterStatus = VSS_WS_UNKNOWN;
500 CComBSTR bstrWriterName;
501 HRESULT hrWriterFailure = S_OK;
504 hr = pVss->GetWriterStatus(iWriter,
513 // If the writer is in non-stable state, break
514 switch(eWriterStatus)
516 case VSS_WS_FAILED_AT_IDENTIFY:
517 case VSS_WS_FAILED_AT_PREPARE_BACKUP:
518 case VSS_WS_FAILED_AT_PREPARE_SNAPSHOT:
519 case VSS_WS_FAILED_AT_FREEZE:
520 case VSS_WS_FAILED_AT_THAW:
521 case VSS_WS_FAILED_AT_POST_SNAPSHOT:
522 case VSS_WS_FAILED_AT_BACKUP_COMPLETE:
523 case VSS_WS_FAILED_AT_PRE_RESTORE:
524 case VSS_WS_FAILED_AT_POST_RESTORE:
526 case VSS_WS_FAILED_AT_BACKUPSHUTDOWN:
529 pVWriterStates->push_back(-1);
534 pVWriterStates->push_back(1);
539 osf << "\"" << CW2A(bstrWriterName) << "\", State: " << eWriterStatus << " (" << CW2A(GetStringFromWriterStatus(eWriterStatus).c_str()) << ")";
541 pVWriterInfo->push_back(osf.str());