-
Notifications
You must be signed in to change notification settings - Fork 17
/
BackupClientDirectoryRecord.cpp
2298 lines (2044 loc) · 64.2 KB
/
BackupClientDirectoryRecord.cpp
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
// --------------------------------------------------------------------------
//
// File
// Name: BackupClientDirectoryRecord.cpp
// Purpose: Implementation of record about directory for
// backup client
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
#include "Box.h"
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#include <errno.h>
#include <string.h>
#include "autogen_BackupProtocol.h"
#include "autogen_CipherException.h"
#include "autogen_ClientException.h"
#include "Archive.h"
#include "BackupClientContext.h"
#include "BackupClientDirectoryRecord.h"
#include "BackupClientInodeToIDMap.h"
#include "BackupDaemon.h"
#include "BackupStoreException.h"
#include "BackupStoreFile.h"
#include "BackupStoreFileEncodeStream.h"
#include "BufferedStream.h"
#include "CommonException.h"
#include "CollectInBufferStream.h"
#include "FileModificationTime.h"
#include "IOStream.h"
#include "Logging.h"
#include "MemBlockStream.h"
#include "PathUtils.h"
#include "RateLimitingStream.h"
#include "ReadLoggingStream.h"
#include "MemLeakFindOn.h"
typedef std::map<std::string, BackupStoreDirectory::Entry *> DecryptedEntriesMap_t;
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::BackupClientDirectoryRecord()
// Purpose: Constructor
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupClientDirectoryRecord::BackupClientDirectoryRecord(int64_t ObjectID, const std::string &rSubDirName)
: mObjectID(ObjectID),
mSubDirName(rSubDirName),
mInitialSyncDone(false),
mSyncDone(false),
mpPendingEntries(0)
{
::memset(mStateChecksum, 0, sizeof(mStateChecksum));
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::~BackupClientDirectoryRecord()
// Purpose: Destructor
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
BackupClientDirectoryRecord::~BackupClientDirectoryRecord()
{
// Make deletion recursive
DeleteSubDirectories();
// Delete maps
if(mpPendingEntries != 0)
{
delete mpPendingEntries;
mpPendingEntries = 0;
}
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::DeleteSubDirectories();
// Purpose: Delete all sub directory entries
// Created: 2003/10/09
//
// --------------------------------------------------------------------------
void BackupClientDirectoryRecord::DeleteSubDirectories()
{
// Delete all pointers
for(std::map<std::string, BackupClientDirectoryRecord *>::iterator i = mSubDirectories.begin();
i != mSubDirectories.end(); ++i)
{
delete i->second;
}
// Empty list
mSubDirectories.clear();
}
std::string BackupClientDirectoryRecord::ConvertVssPathToRealPath(
const std::string &rVssPath,
const Location& rBackupLocation)
{
#ifdef ENABLE_VSS
BOX_TRACE("VSS: ConvertVssPathToRealPath: mIsSnapshotCreated = " <<
rBackupLocation.mIsSnapshotCreated);
BOX_TRACE("VSS: ConvertVssPathToRealPath: File/Directory Path = " <<
rVssPath.substr(0, rBackupLocation.mSnapshotPath.length()));
BOX_TRACE("VSS: ConvertVssPathToRealPath: Snapshot Path = " <<
rBackupLocation.mSnapshotPath);
if (rBackupLocation.mIsSnapshotCreated &&
rVssPath.substr(0, rBackupLocation.mSnapshotPath.length()) ==
rBackupLocation.mSnapshotPath)
{
std::string convertedPath = rBackupLocation.mPath +
rVssPath.substr(rBackupLocation.mSnapshotPath.length());
BOX_TRACE("VSS: ConvertVssPathToRealPath: Converted Path = " <<
convertedPath);
return convertedPath;
}
#endif
return rVssPath;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::SyncDirectory(i
// BackupClientDirectoryRecord::SyncParams &,
// int64_t, const std::string &,
// const std::string &, bool)
// Purpose: Recursively synchronise a local directory
// with the server.
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
void BackupClientDirectoryRecord::SyncDirectory(
BackupClientDirectoryRecord::SyncParams &rParams,
int64_t ContainingDirectoryID,
const std::string &rLocalPath,
const std::string &rRemotePath,
const Location& rBackupLocation,
bool ThisDirHasJustBeenCreated)
{
BackupClientContext& rContext(rParams.mrContext);
ProgressNotifier& rNotifier(rContext.GetProgressNotifier());
// Signal received by daemon?
if(rParams.mrRunStatusProvider.StopRun())
{
// Yes. Stop now.
THROW_EXCEPTION(BackupStoreException, SignalReceived)
}
// Start by making some flag changes, marking this sync as not done,
// and on the immediate sub directories.
mSyncDone = false;
for(std::map<std::string, BackupClientDirectoryRecord *>::iterator
i = mSubDirectories.begin();
i != mSubDirectories.end(); ++i)
{
i->second->mSyncDone = false;
}
// Work out the time in the future after which the file should
// be uploaded regardless. This is a simple way to avoid having
// too many problems with file servers when they have clients
// with badly out of sync clocks.
rParams.mUploadAfterThisTimeInTheFuture = GetCurrentBoxTime() +
rParams.mMaxFileTimeInFuture;
// Build the current state checksum to compare against while
// getting info from dirs. Note checksum is used locally only,
// so byte order isn't considered.
MD5Digest currentStateChecksum;
EMU_STRUCT_STAT dest_st;
// Stat the directory, to get attribute info
// If it's a symbolic link, we want the link target here
// (as we're about to back up the contents of the directory)
{
if(EMU_STAT(rLocalPath.c_str(), &dest_st) != 0)
{
// The directory has probably been deleted, so
// just ignore this error. In a future scan, this
// deletion will be noticed, deleted from server,
// and this object deleted.
rNotifier.NotifyDirStatFailed(this,
ConvertVssPathToRealPath(rLocalPath, rBackupLocation),
strerror(errno));
return;
}
BOX_TRACE("Stat dir '" << rLocalPath << "' "
"found device/inode " <<
dest_st.st_dev << "/" << dest_st.st_ino);
// Store inode number in map so directories are tracked
// in case they're renamed
{
BackupClientInodeToIDMap &idMap(
rParams.mrContext.GetNewIDMap());
idMap.AddToMap(dest_st.st_ino, mObjectID, ContainingDirectoryID,
ConvertVssPathToRealPath(rLocalPath, rBackupLocation));
}
// Add attributes to checksum
currentStateChecksum.Add(&dest_st.st_mode,
sizeof(dest_st.st_mode));
currentStateChecksum.Add(&dest_st.st_uid,
sizeof(dest_st.st_uid));
currentStateChecksum.Add(&dest_st.st_gid,
sizeof(dest_st.st_gid));
// Inode to be paranoid about things moving around
currentStateChecksum.Add(&dest_st.st_ino,
sizeof(dest_st.st_ino));
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
currentStateChecksum.Add(&dest_st.st_flags,
sizeof(dest_st.st_flags));
#endif
StreamableMemBlock xattr;
BackupClientFileAttributes::FillExtendedAttr(xattr,
rLocalPath.c_str());
currentStateChecksum.Add(xattr.GetBuffer(), xattr.GetSize());
}
// Read directory entries, building arrays of names
// First, need to read the contents of the directory.
std::vector<std::string> dirs;
std::vector<std::string> files;
bool downloadDirectoryRecordBecauseOfFutureFiles = false;
// BLOCK
{
// read the contents...
DIR *dirHandle = 0;
try
{
std::string nonVssDirPath = ConvertVssPathToRealPath(rLocalPath,
rBackupLocation);
rNotifier.NotifyScanDirectory(this, nonVssDirPath);
dirHandle = ::opendir(rLocalPath.c_str());
if(dirHandle == 0)
{
// Report the error (logs and eventual email to administrator)
if (errno == EACCES)
{
rNotifier.NotifyDirListFailed(this,
nonVssDirPath,
"Access denied");
}
else
{
rNotifier.NotifyDirListFailed(this,
nonVssDirPath,
strerror(errno));
}
// Report the error (logs and eventual email
// to administrator)
SetErrorWhenReadingFilesystemObject(rParams,
nonVssDirPath);
// Ignore this directory for now.
return;
}
struct dirent *en = 0;
int num_entries_found = 0;
while((en = ::readdir(dirHandle)) != 0)
{
num_entries_found++;
rParams.mrContext.DoKeepAlive();
if(rParams.mpBackgroundTask)
{
rParams.mpBackgroundTask->RunBackgroundTask(
BackgroundTask::Scanning_Dirs,
num_entries_found, 0);
}
if (!SyncDirectoryEntry(rParams, rNotifier,
rBackupLocation, rLocalPath,
currentStateChecksum, en, dest_st, dirs,
files, downloadDirectoryRecordBecauseOfFutureFiles))
{
// This entry is not to be backed up.
continue;
}
}
if(::closedir(dirHandle) != 0)
{
THROW_EXCEPTION(CommonException, OSFileError)
}
dirHandle = 0;
}
catch(...)
{
if(dirHandle != 0)
{
::closedir(dirHandle);
}
throw;
}
}
// Finish off the checksum, and compare with the one currently stored
bool checksumDifferent = true;
currentStateChecksum.Finish();
if(mInitialSyncDone && currentStateChecksum.DigestMatches(mStateChecksum))
{
// The checksum is the same, and there was one to compare with
checksumDifferent = false;
}
// Pointer to potentially downloaded store directory info
std::auto_ptr<BackupStoreDirectory> apDirOnStore;
try
{
// Want to get the directory listing?
if(ThisDirHasJustBeenCreated)
{
// Avoid sending another command to the server when we know it's empty
apDirOnStore.reset(new BackupStoreDirectory(mObjectID,
ContainingDirectoryID));
}
// Consider asking the store for it
else if(!mInitialSyncDone || checksumDifferent ||
downloadDirectoryRecordBecauseOfFutureFiles)
{
apDirOnStore = FetchDirectoryListing(rParams);
}
// Make sure the attributes are up to date -- if there's space
// on the server and this directory has not just been created
// (because it's attributes will be correct in this case) and
// the checksum is different, implying they *MIGHT* be
// different.
if((!ThisDirHasJustBeenCreated) && checksumDifferent &&
!rParams.mrContext.StorageLimitExceeded())
{
UpdateAttributes(rParams, apDirOnStore.get(), rLocalPath);
}
// Create the list of pointers to directory entries
std::vector<BackupStoreDirectory::Entry *> entriesLeftOver;
if(apDirOnStore.get())
{
entriesLeftOver.resize(apDirOnStore->GetNumberOfEntries(), 0);
BackupStoreDirectory::Iterator i(*apDirOnStore);
// Copy in pointers to all the entries
for(unsigned int l = 0; l < apDirOnStore->GetNumberOfEntries(); ++l)
{
entriesLeftOver[l] = i.Next();
}
}
// Do the directory reading
bool updateCompleteSuccess = UpdateItems(rParams, rLocalPath,
rRemotePath, rBackupLocation, apDirOnStore.get(),
entriesLeftOver, files, dirs);
// LAST THING! (think exception safety)
// Store the new checksum -- don't fetch things unnecessarily
// in the future But... only if 1) the storage limit isn't
// exceeded -- make sure things are done again if the directory
// is modified later and 2) All the objects within the
// directory were stored successfully.
if(!rParams.mrContext.StorageLimitExceeded() &&
updateCompleteSuccess)
{
currentStateChecksum.CopyDigestTo(mStateChecksum);
}
}
catch(...)
{
// Bad things have happened -- clean up
// Set things so that we get a full go at stuff later
::memset(mStateChecksum, 0, sizeof(mStateChecksum));
throw;
}
// Flag things as having happened.
mInitialSyncDone = true;
mSyncDone = true;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::SyncDirectorEntry(
// BackupClientDirectoryRecord::SyncParams &,
// int64_t, const std::string &,
// const std::string &, bool)
// Purpose: Recursively synchronise a local directory
// with the server.
// Created: 2003/10/08
//
// --------------------------------------------------------------------------
bool BackupClientDirectoryRecord::SyncDirectoryEntry(
BackupClientDirectoryRecord::SyncParams &rParams,
ProgressNotifier& rNotifier,
const Location& rBackupLocation,
const std::string &rDirLocalPath,
MD5Digest& currentStateChecksum,
struct dirent *en,
EMU_STRUCT_STAT dir_st,
std::vector<std::string>& rDirs,
std::vector<std::string>& rFiles,
bool& rDownloadDirectoryRecordBecauseOfFutureFiles)
{
std::string entry_name = en->d_name;
if(entry_name == "." || entry_name == "..")
{
// ignore parent directory entries
return false;
}
// Stat file to get info
std::string filename = MakeFullPath(rDirLocalPath, entry_name);
std::string realFileName = ConvertVssPathToRealPath(filename,
rBackupLocation);
EMU_STRUCT_STAT file_st;
#ifdef WIN32
// Don't stat the file just yet, to ensure that users can exclude
// unreadable files to suppress warnings that they are not accessible.
int type;
if (en->d_type == DT_DIR)
{
type = S_IFDIR;
}
else
{
type = S_IFREG;
}
#else // !WIN32
if(EMU_LSTAT(filename.c_str(), &file_st) != 0)
{
// We don't know whether it's a file or a directory, so check
// both. This only affects whether a warning message is
// displayed; the file is not backed up in either case.
if(!(rParams.mrContext.ExcludeFile(filename)) &&
!(rParams.mrContext.ExcludeDir(filename)))
{
// Report the error (logs and eventual email to
// administrator)
rNotifier.NotifyFileStatFailed(this, filename,
strerror(errno));
// FIXME move to NotifyFileStatFailed()
SetErrorWhenReadingFilesystemObject(rParams, filename);
}
// Ignore this entry for now.
return false;
}
BOX_TRACE("Stat entry '" << filename << "' found device/inode " <<
file_st.st_dev << "/" << file_st.st_ino);
// Workaround for apparent btrfs bug, where symlinks appear to be on
// a different filesystem than their containing directory, thanks to
// Toke Hoiland-Jorgensen.
int type = file_st.st_mode & S_IFMT;
if(type == S_IFDIR && file_st.st_dev != dir_st.st_dev)
{
if(!(rParams.mrContext.ExcludeDir(filename)))
{
rNotifier.NotifyMountPointSkipped(this, filename);
}
return false;
}
#endif
if(type == S_IFREG || type == S_IFLNK)
{
// File or symbolic link
// Exclude it?
if(rParams.mrContext.ExcludeFile(realFileName))
{
rNotifier.NotifyFileExcluded(this, realFileName);
// Next item!
return false;
}
}
else if(type == S_IFDIR)
{
// Directory
// Exclude it?
if(rParams.mrContext.ExcludeDir(realFileName))
{
rNotifier.NotifyDirExcluded(this, realFileName);
// Next item!
return false;
}
#ifdef WIN32
// exclude reparse points, as Application Data points to the
// parent directory under Vista and later, and causes an
// infinite loop:
// http://social.msdn.microsoft.com/forums/en-US/windowscompatibility/thread/05d14368-25dd-41c8-bdba-5590bf762a68/
if (en->win_attrs & FILE_ATTRIBUTE_REPARSE_POINT)
{
rNotifier.NotifyMountPointSkipped(this, realFileName);
return false;
}
#endif // WIN32
}
else // not a file or directory, what is it?
{
if (type == S_IFSOCK
#ifndef WIN32
|| type == S_IFIFO
#endif // !WIN32
)
{
// removed notification for these types
// see Debian bug 479145, no objections
}
else if(rParams.mrContext.ExcludeFile(realFileName))
{
rNotifier.NotifyFileExcluded(this, realFileName);
}
else
{
rNotifier.NotifyUnsupportedFileType(this, realFileName);
SetErrorWhenReadingFilesystemObject(rParams,
realFileName);
}
return false;
}
// The object should be backed up (file, symlink or dir, not excluded).
// So make the information for adding to the checksum.
#ifdef WIN32
// We didn't stat the file before, but now we need the information.
if(emu_stat(filename.c_str(), &file_st) != 0)
{
rNotifier.NotifyFileStatFailed(this,
ConvertVssPathToRealPath(filename, rBackupLocation),
strerror(errno));
// Report the error (logs and eventual email to administrator)
SetErrorWhenReadingFilesystemObject(rParams, filename);
// Ignore this entry for now.
return false;
}
if(file_st.st_dev != dir_st.st_dev)
{
rNotifier.NotifyMountPointSkipped(this,
ConvertVssPathToRealPath(filename, rBackupLocation));
return false;
}
#endif
// Basic structure for checksum info
struct {
box_time_t mModificationTime;
box_time_t mAttributeModificationTime;
int64_t mSize;
// And then the name follows
} checksum_info;
// Be paranoid about structure packing
::memset(&checksum_info, 0, sizeof(checksum_info));
checksum_info.mModificationTime = FileModificationTime(file_st);
checksum_info.mAttributeModificationTime = FileAttrModificationTime(file_st);
checksum_info.mSize = file_st.st_size;
currentStateChecksum.Add(&checksum_info, sizeof(checksum_info));
currentStateChecksum.Add(en->d_name, strlen(en->d_name));
// If the file has been modified madly into the future, download the
// directory record anyway to ensure that it doesn't get uploaded
// every single time the disc is scanned.
if(checksum_info.mModificationTime > rParams.mUploadAfterThisTimeInTheFuture)
{
rDownloadDirectoryRecordBecauseOfFutureFiles = true;
// Log that this has happened
if(!rParams.mHaveLoggedWarningAboutFutureFileTimes)
{
rNotifier.NotifyFileModifiedInFuture(this,
ConvertVssPathToRealPath(filename, rBackupLocation));
rParams.mHaveLoggedWarningAboutFutureFileTimes = true;
}
}
// We've decided to back it up, so add to file or directory list.
if(type == S_IFREG || type == S_IFLNK)
{
rFiles.push_back(entry_name);
}
else if(type == S_IFDIR)
{
rDirs.push_back(entry_name);
}
return true;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::FetchDirectoryListing(
// BackupClientDirectoryRecord::SyncParams &)
// Purpose: Fetch the directory listing of this directory from
// the store.
// Created: 2003/10/09
//
// --------------------------------------------------------------------------
std::auto_ptr<BackupStoreDirectory>
BackupClientDirectoryRecord::FetchDirectoryListing(
BackupClientDirectoryRecord::SyncParams &rParams)
{
std::auto_ptr<BackupStoreDirectory> apDir;
// Get connection to store
BackupProtocolCallable &connection(rParams.mrContext.GetConnection());
// Query the directory
std::auto_ptr<BackupProtocolSuccess> dirreply(connection.QueryListDirectory(
mObjectID,
// both files and directories
BackupProtocolListDirectory::Flags_INCLUDE_EVERYTHING,
// exclude old/deleted stuff
BackupProtocolListDirectory::Flags_Deleted |
BackupProtocolListDirectory::Flags_OldVersion,
true /* want attributes */));
// Retrieve the directory from the stream following
apDir.reset(new BackupStoreDirectory(connection.ReceiveStream(),
connection.GetTimeout()));
return apDir;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::UpdateAttributes(
// BackupClientDirectoryRecord::SyncParams &,
// const std::string &)
// Purpose: Sets the attributes of the directory on the store,
// if necessary.
// Created: 2003/10/09
//
// --------------------------------------------------------------------------
void BackupClientDirectoryRecord::UpdateAttributes(
BackupClientDirectoryRecord::SyncParams &rParams,
BackupStoreDirectory *pDirOnStore,
const std::string &rLocalPath)
{
// Get attributes for the directory
BackupClientFileAttributes attr;
box_time_t attrModTime = 0;
attr.ReadAttributes(rLocalPath.c_str(), true /* directories have zero mod times */,
0 /* no modification time */, &attrModTime);
// Assume attributes need updating, unless proved otherwise
bool updateAttr = true;
// Got a listing to compare with?
ASSERT(pDirOnStore == 0 || (pDirOnStore != 0 && pDirOnStore->HasAttributes()));
if(pDirOnStore != 0 && pDirOnStore->HasAttributes())
{
const StreamableMemBlock &storeAttrEnc(pDirOnStore->GetAttributes());
// Explict decryption
BackupClientFileAttributes storeAttr(storeAttrEnc);
// Compare the attributes
if(attr.Compare(storeAttr, true,
true /* ignore both modification times */))
{
// No update necessary
updateAttr = false;
}
}
// Update them?
if(updateAttr)
{
// Get connection to store
BackupProtocolCallable &connection(rParams.mrContext.GetConnection());
// Exception thrown if this doesn't work
std::auto_ptr<IOStream> attrStream(new MemBlockStream(attr));
connection.QueryChangeDirAttributes(mObjectID, attrModTime, attrStream);
}
}
std::string BackupClientDirectoryRecord::DecryptFilename(
BackupStoreDirectory::Entry *en,
const std::string& rRemoteDirectoryPath)
{
BackupStoreFilenameClear fn(en->GetName());
return DecryptFilename(fn, en->GetObjectID(), rRemoteDirectoryPath);
}
std::string BackupClientDirectoryRecord::DecryptFilename(
BackupStoreFilenameClear fn, int64_t filenameObjectID,
const std::string& rRemoteDirectoryPath)
{
std::string filenameClear;
try
{
filenameClear = fn.GetClearFilename();
}
catch(BoxException &e)
{
BOX_ERROR("Failed to decrypt filename for object " <<
BOX_FORMAT_OBJECTID(filenameObjectID) << " in "
"directory " << BOX_FORMAT_OBJECTID(mObjectID) <<
" (" << rRemoteDirectoryPath << ")");
throw;
}
return filenameClear;
}
// --------------------------------------------------------------------------
//
// Function
// Name: BackupClientDirectoryRecord::UpdateItems(BackupClientDirectoryRecord::SyncParams &, const std::string &, BackupStoreDirectory *, std::vector<BackupStoreDirectory::Entry *> &)
// Purpose: Update the items stored on the server. The rFiles vector will be erased after it's used to save space.
// Returns true if all items were updated successfully. (If not, the failures will have been logged).
// Created: 2003/10/09
//
// --------------------------------------------------------------------------
bool BackupClientDirectoryRecord::UpdateItems(
BackupClientDirectoryRecord::SyncParams &rParams,
const std::string &rLocalPath,
const std::string &rRemotePath,
const Location& rBackupLocation,
BackupStoreDirectory *pDirOnStore,
std::vector<BackupStoreDirectory::Entry *> &rEntriesLeftOver,
std::vector<std::string> &rFiles,
const std::vector<std::string> &rDirs)
{
BackupClientContext& rContext(rParams.mrContext);
ProgressNotifier& rNotifier(rContext.GetProgressNotifier());
bool allUpdatedSuccessfully = true;
// Decrypt all the directory entries.
// It would be nice to be able to just compare the encrypted versions, however this doesn't work
// in practise because there can be multiple encodings of the same filename using different
// methods (although each method will result in the same string for the same filename.) This
// happens when the server fixes a broken store, and gives plain text generated filenames.
// So if we didn't do things like this, then you wouldn't be able to recover from bad things
// happening with the server.
DecryptedEntriesMap_t decryptedEntries;
if(pDirOnStore != 0)
{
BackupStoreDirectory::Iterator i(*pDirOnStore);
BackupStoreDirectory::Entry *en = 0;
while((en = i.Next()) != 0)
{
std::string filenameClear;
try
{
filenameClear = DecryptFilename(en,
rRemotePath);
decryptedEntries[filenameClear] = en;
}
catch (CipherException &e)
{
BOX_ERROR("Failed to decrypt a filename, "
"pretending that the file doesn't "
"exist");
}
}
}
// Do files
for(std::vector<std::string>::const_iterator f = rFiles.begin();
f != rFiles.end(); ++f)
{
// Send keep-alive message if needed
rContext.DoKeepAlive();
// Filename of this file
std::string filename(MakeFullPath(rLocalPath, *f));
std::string nonVssFilePath = ConvertVssPathToRealPath(filename,
rBackupLocation);
// Get relevant info about file
box_time_t modTime = 0;
uint64_t attributesHash = 0;
int64_t fileSize = 0;
InodeRefType inodeNum = 0;
// BLOCK
{
// Stat the file
EMU_STRUCT_STAT st;
if(EMU_LSTAT(filename.c_str(), &st) != 0)
{
rNotifier.NotifyFileStatFailed(this, nonVssFilePath,
strerror(errno));
// Report the error (logs and
// eventual email to administrator)
SetErrorWhenReadingFilesystemObject(rParams, nonVssFilePath);
// Ignore this entry for now.
continue;
}
// Extract required data
modTime = FileModificationTime(st);
fileSize = st.st_size;
inodeNum = st.st_ino;
attributesHash = BackupClientFileAttributes::GenerateAttributeHash(st, filename, *f);
}
// See if it's in the listing (if we have one)
BackupStoreFilenameClear storeFilename(*f);
BackupStoreDirectory::Entry *en = 0;
int64_t latestObjectID = 0;
if(pDirOnStore != 0)
{
DecryptedEntriesMap_t::iterator i(decryptedEntries.find(*f));
if(i != decryptedEntries.end())
{
en = i->second;
latestObjectID = en->GetObjectID();
}
}
// Check that the entry which might have been found is in fact a file
if((en != 0) && !(en->IsFile()))
{
// Directory exists in the place of this file -- sort it out
RemoveDirectoryInPlaceOfFile(rParams, pDirOnStore,
en, *f);
en = 0;
}
// Check for renaming?
if(pDirOnStore != 0 && en == 0)
{
// We now know...
// 1) File has just been added
// 2) It's not in the store
// Do we know about the inode number?
const BackupClientInodeToIDMap &idMap(rContext.GetCurrentIDMap());
int64_t renameObjectID = 0, renameInDirectory = 0;
if(idMap.Lookup(inodeNum, renameObjectID, renameInDirectory))
{
// Look up on the server to get the name, to build the local filename
std::string localPotentialOldName;
bool isDir = false;
bool isCurrentVersion = false;
box_time_t srvModTime = 0, srvAttributesHash = 0;
BackupStoreFilenameClear oldLeafname;
if(rContext.FindFilename(renameObjectID, renameInDirectory,
localPotentialOldName, isDir, isCurrentVersion,
&srvModTime, &srvAttributesHash, &oldLeafname))
{
// Only interested if it's a file and the latest version
if(!isDir && isCurrentVersion)
{
// Check that the object we found in the ID map doesn't exist on disc
EMU_STRUCT_STAT st;
if(EMU_STAT(localPotentialOldName.c_str(), &st) != 0 && errno == ENOENT)
{
// Doesn't exist locally, but does exist on the server.
// Therefore we can safely rename it to this new file.
// Get the connection to the server
BackupProtocolCallable &connection(rContext.GetConnection());
// Only do this step if there is room on the server.
// This step will be repeated later when there is space available
if(!rContext.StorageLimitExceeded())
{
// Rename the existing files (ie include old versions) on the server
connection.QueryMoveObject(renameObjectID,
renameInDirectory,
mObjectID /* move to this directory */,
BackupProtocolMoveObject::Flags_MoveAllWithSameName |
BackupProtocolMoveObject::Flags_AllowMoveOverDeletedObject,
storeFilename);
// Stop the attempt to delete the file in the original location
BackupClientDeleteList &rdelList(rContext.GetDeleteList());
rdelList.StopFileDeletion(renameInDirectory, oldLeafname);
// Create new entry in the directory for it
// -- will be near enough what's actually on the server for the rest to work.
en = pDirOnStore->AddEntry(storeFilename,
srvModTime, renameObjectID,
0 /* size in blocks unknown, but not needed */,
BackupStoreDirectory::Entry::Flags_File,
srvAttributesHash);
// Store the object ID for the inode lookup map later
latestObjectID = renameObjectID;
}
}
}
}
}
}
// Is it in the mPendingEntries list?
box_time_t pendingFirstSeenTime = 0; // ie not seen
if(mpPendingEntries != 0)
{
std::map<std::string, box_time_t>::const_iterator i(mpPendingEntries->find(*f));
if(i != mpPendingEntries->end())
{
// found it -- set flag
pendingFirstSeenTime = i->second;
}
}
// If pDirOnStore == 0, then this must have been after an initial sync:
ASSERT(pDirOnStore != 0 || mInitialSyncDone);
// So, if pDirOnStore == 0, then we know that everything before syncPeriodStart
// is either on the server, or in the toupload list. If the directory had changed,
// we'd have got a directory listing.
//
// At this point, if (pDirOnStore == 0 && en == 0), we can assume it's on the server with a
// mod time < syncPeriodStart, or didn't exist before that time.
//
// But if en != 0, then we need to compare modification times to avoid uploading it again.
// Need to update?
//
// Condition for upload:
// modification time within sync period
// if it's been seen before but not uploaded, is the time from this first sight longer than the MaxUploadWait
// and if we know about it from a directory listing, that it hasn't got the same upload time as on the store
bool doUpload = false;
std::string decisionReason = "unknown";
// Only upload a file if the mod time locally is
// different to that on the server.
if (en == 0 || en->GetModificationTime() != modTime)
{
// Check the file modified within the acceptable time period we're checking
// If the file isn't on the server, the acceptable time starts at zero.
// Check pDirOnStore and en, because if we didn't download a directory listing,
// pDirOnStore will be zero, but we know it's on the server.
if (modTime < rParams.mSyncPeriodEnd)
{
if (pDirOnStore != 0 && en == 0)
{
doUpload = true;
decisionReason = "not on server";
}
else if (modTime >= rParams.mSyncPeriodStart)
{
doUpload = true;
decisionReason = "modified since last sync";
}
}
// However, just in case things are continually
// modified, we check the first seen time.
// The two compares of syncPeriodEnd and
// pendingFirstSeenTime are because the values
// are unsigned.
if (!doUpload &&
pendingFirstSeenTime != 0 &&
rParams.mSyncPeriodEnd > pendingFirstSeenTime &&
(rParams.mSyncPeriodEnd - pendingFirstSeenTime)
> rParams.mMaxUploadWait)
{
doUpload = true;
decisionReason = "continually modified";
}
// Then make sure that if files are added with a
// time less than the sync period start
// (which can easily happen on file server), it
// gets uploaded. The directory contents checksum