-
Notifications
You must be signed in to change notification settings - Fork 17
/
testbbackupd.cpp
4017 lines (3354 loc) · 114 KB
/
testbbackupd.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: testbbackupd.cpp
// Purpose: test backup daemon (and associated client bits)
// Created: 2003/10/07
//
// --------------------------------------------------------------------------
#include "Box.h"
// do not include MinGW's dirent.h on Win32,
// as we override some of it in lib/win32.
#ifndef WIN32
#include <dirent.h>
#endif
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <string.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_XATTR_H
#include <cerrno>
#include <sys/xattr.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef WIN32
#include <process.h>
#endif
#include <map>
#ifdef HAVE_SYSCALL
#include <sys/syscall.h>
#endif
#include "BackupClientCryptoKeys.h"
#include "BackupClientContext.h"
#include "BackupClientFileAttributes.h"
#include "BackupClientInodeToIDMap.h"
#include "BackupClientRestore.h"
#include "BackupDaemon.h"
#include "BackupDaemonConfigVerify.h"
#include "BackupProtocol.h"
#include "BackupQueries.h"
#include "BackupStoreAccounts.h"
#include "BackupStoreConstants.h"
#include "BackupStoreContext.h"
#include "BackupStoreDaemon.h"
#include "BackupStoreDirectory.h"
#include "BackupStoreException.h"
#include "BackupStoreConfigVerify.h"
#include "BackupStoreFileEncodeStream.h"
#include "BoxPortsAndFiles.h"
#include "BoxTime.h"
#include "BoxTimeToUnix.h"
#include "CollectInBufferStream.h"
#include "CommonException.h"
#include "Configuration.h"
#include "FileModificationTime.h"
#include "FileStream.h"
#include "IOStreamGetLine.h"
#include "LocalProcessStream.h"
#include "MemBlockStream.h"
#include "RaidFileController.h"
#include "SSLLib.h"
#include "ServerControl.h"
#include "Socket.h"
#include "SocketStreamTLS.h"
#include "StoreTestUtils.h"
#include "TLSContext.h"
#include "Test.h"
#include "Timer.h"
#include "Utils.h"
#include "MemLeakFindOn.h"
// ENOATTR may be defined in a separate header file which we may not have
#ifndef ENOATTR
#define ENOATTR ENODATA
#endif
// two cycles and a bit
#define TIME_TO_WAIT_FOR_BACKUP_OPERATION 12
#define SHORT_TIMEOUT 5000
#define BACKUP_ERROR_DELAY_SHORTENED 10
#define DEFAULT_BBACKUPD_CONFIG_FILE "testfiles/bbackupd.conf"
void wait_for_backup_operation(const char* message)
{
wait_for_operation(TIME_TO_WAIT_FOR_BACKUP_OPERATION, message);
}
#ifdef HAVE_SYS_XATTR_H
bool readxattr_into_map(const char *filename, std::map<std::string,std::string> &rOutput)
{
rOutput.clear();
ssize_t xattrNamesBufferSize = llistxattr(filename, NULL, 0);
if(xattrNamesBufferSize < 0)
{
#if HAVE_DECL_ENOTSUP
if(errno == ENOTSUP)
{
// Pretend that it worked, leaving an empty map, so
// that the rest of the attribute comparison will
// proceed as normal.
return true;
}
#endif // HAVE_DECL_ENOTSUP
return false;
}
else if(xattrNamesBufferSize > 0)
{
// There is some data there to look at
char *xattrNamesBuffer = (char*)malloc(xattrNamesBufferSize + 4);
if(xattrNamesBuffer == NULL) return false;
char *xattrDataBuffer = 0;
int xattrDataBufferSize = 0;
// note: will leak these buffers if a read error occurs. (test code, so doesn't matter)
ssize_t ns = llistxattr(filename, xattrNamesBuffer, xattrNamesBufferSize);
if(ns < 0)
{
return false;
}
else if(ns > 0)
{
// Read all the attribute values
const char *xattrName = xattrNamesBuffer;
while(xattrName < (xattrNamesBuffer + ns))
{
// Store size of name
int xattrNameSize = strlen(xattrName);
bool ok = true;
ssize_t dataSize = lgetxattr(filename, xattrName, NULL, 0);
if(dataSize < 0)
{
if(errno == ENOATTR)
{
// Deleted from under us
ok = false;
}
else
{
return false;
}
}
else if(dataSize == 0)
{
// something must have removed all the data from under us
ok = false;
}
else
{
// Make sure there's enough space in the buffer to get the attribute
if(xattrDataBuffer == 0)
{
xattrDataBuffer = (char*)malloc(dataSize + 4);
xattrDataBufferSize = dataSize + 4;
}
else if(xattrDataBufferSize < (dataSize + 4))
{
char *resized = (char*)realloc(xattrDataBuffer, dataSize + 4);
if(resized == NULL) return false;
xattrDataBuffer = resized;
xattrDataBufferSize = dataSize + 4;
}
}
// Read the data!
dataSize = 0;
if(ok)
{
dataSize = lgetxattr(filename, xattrName, xattrDataBuffer,
xattrDataBufferSize - 1 /*for terminator*/);
if(dataSize < 0)
{
if(errno == ENOATTR)
{
// Deleted from under us
ok = false;
}
else
{
return false;
}
}
else if(dataSize == 0)
{
// something must have deleted this from under us
ok = false;
}
else
{
// Terminate the data
xattrDataBuffer[dataSize] = '\0';
}
// Got the data in the buffer
}
// Store in map
if(ok)
{
rOutput[std::string(xattrName)] = std::string(xattrDataBuffer, dataSize);
}
// Next attribute
xattrName += xattrNameSize + 1;
}
}
if(xattrNamesBuffer != 0) ::free(xattrNamesBuffer);
if(xattrDataBuffer != 0) ::free(xattrDataBuffer);
}
return true;
}
static FILE *xattrTestDataHandle = 0;
bool write_xattr_test(const char *filename, const char *attrName, unsigned int length, bool *pNotSupported = 0)
{
if(xattrTestDataHandle == 0)
{
xattrTestDataHandle = ::fopen("testfiles/test3.tgz", "rb"); // largest test file
}
if(xattrTestDataHandle == 0)
{
return false;
}
else
{
char data[1024];
if(length > sizeof(data)) length = sizeof(data);
if(::fread(data, length, 1, xattrTestDataHandle) != 1)
{
return false;
}
if(::lsetxattr(filename, attrName, data, length, 0) != 0)
{
if(pNotSupported != 0)
{
*pNotSupported = (errno == ENOTSUP);
}
return false;
}
}
return true;
}
void finish_with_write_xattr_test()
{
if(xattrTestDataHandle != 0)
{
::fclose(xattrTestDataHandle);
}
}
#endif // HAVE_SYS_XATTR_H
bool attrmatch(const char *f1, const char *f2)
{
EMU_STRUCT_STAT s1, s2;
TEST_THAT(EMU_LSTAT(f1, &s1) == 0);
TEST_THAT(EMU_LSTAT(f2, &s2) == 0);
#ifdef HAVE_SYS_XATTR_H
{
std::map<std::string,std::string> xattr1, xattr2;
if(!readxattr_into_map(f1, xattr1)
|| !readxattr_into_map(f2, xattr2))
{
return false;
}
if(!(xattr1 == xattr2))
{
return false;
}
}
#endif // HAVE_SYS_XATTR_H
// if link, just make sure other file is a link too, and that the link to names match
if((s1.st_mode & S_IFMT) == S_IFLNK)
{
#ifdef WIN32
TEST_FAIL_WITH_MESSAGE("No symlinks on win32!")
#else
if((s2.st_mode & S_IFMT) != S_IFLNK) return false;
char p1[PATH_MAX], p2[PATH_MAX];
int p1l = ::readlink(f1, p1, PATH_MAX);
int p2l = ::readlink(f2, p2, PATH_MAX);
TEST_THAT(p1l != -1 && p2l != -1);
// terminate strings properly
p1[p1l] = '\0';
p2[p2l] = '\0';
return strcmp(p1, p2) == 0;
#endif
}
// modification times
if(FileModificationTime(s1) != FileModificationTime(s2))
{
return false;
}
// compare the rest
return (s1.st_mode == s2.st_mode && s1.st_uid == s2.st_uid && s1.st_gid == s2.st_gid);
}
bool unpack_files(const std::string& archive_file,
const std::string& destination_dir = "testfiles",
const std::string& tar_options = "")
{
BOX_INFO("Unpacking test fixture archive into " << destination_dir
<< ": " << archive_file);
#ifdef _MSC_VER // No tar, use 7zip.
// 7za only extracts the tgz file to a tar file, which we have to extract in a
// separate step.
std::string cmd = std::string("7za x testfiles/") + archive_file + ".tgz -aos "
"-otestfiles >nul:";
TEST_LINE_OR(::system(cmd.c_str()) == 0, cmd, return false);
cmd = std::string("7za x testfiles/") + archive_file + ".tar -aos "
"-o" + destination_dir + " -x!.\\TestDir1\\symlink? -x!.\\test2 >nul:";
#elif defined WIN32 // Cygwin + MinGW, we can use real tar.
std::string cmd("tar xz");
cmd += tar_options + " -f testfiles/" + archive_file + ".tgz " +
"-C " + destination_dir;
#else // Unixish, but Solaris tar doesn't like decompressing gzip files.
std::string cmd("gzip -d < testfiles/");
cmd += archive_file + ".tgz | ( cd " + destination_dir + " && tar xf" +
tar_options + " -)";
#endif
TEST_LINE_OR(::system(cmd.c_str()) == 0, cmd, return false);
return true;
}
Daemon* spDaemon = NULL;
bool configure_bbackupd(BackupDaemon& bbackupd, const std::string& config_file)
{
// Stop bbackupd initialisation from changing the console logging level
// and the program name tag.
Logger& console(Logging::GetConsole());
Logger::LevelGuard undo_log_level_change(console, console.GetLevel());
Logging::Tagger undo_program_name_change;
std::vector<std::string> args;
size_t last_arg_start = 0;
for (size_t pos = 0; pos <= bbackupd_args.size(); pos++)
{
char c;
if (pos == bbackupd_args.size())
{
c = ' '; // finish last argument
}
else
{
c = bbackupd_args[pos];
}
if (c == ' ')
{
if (last_arg_start < pos)
{
std::string last_arg =
bbackupd_args.substr(last_arg_start,
pos - last_arg_start);
args.push_back(last_arg);
}
last_arg_start = pos + 1;
}
}
MemoryBlockGuard<const char **> argv_buffer(sizeof(const char*) * (args.size() + 1));
const char **argv = argv_buffer;
argv_buffer[0] = "bbackupd";
for (size_t i = 0; i < args.size(); i++)
{
argv_buffer[i + 1] = args[i].c_str();
}
TEST_EQUAL_LINE(0, bbackupd.ProcessOptions(args.size() + 1, argv),
"processing command-line options");
bbackupd.Configure(config_file);
bbackupd.InitCrypto();
return true;
}
bool kill_running_daemons()
{
bool success = true;
if(FileExists("testfiles/bbstored.pid"))
{
TEST_THAT_OR(KillServer("testfiles/bbstored.pid", true), success = false);
}
if(FileExists("testfiles/bbackupd.pid"))
{
TEST_THAT_OR(KillServer("testfiles/bbackupd.pid", true), success = false);
}
return success;
}
bool prepare_test_with_client_daemon(BackupDaemon& bbackupd, bool do_unpack_files = true,
bool do_start_bbstored = true)
{
Timers::Cleanup(false); // don't throw exception if not initialised
Timers::Init();
if (do_start_bbstored)
{
TEST_THAT_OR(StartServer(), FAIL);
}
if (do_unpack_files)
{
TEST_THAT_OR(unpack_files("test_base"), FAIL);
// Older versions of GNU tar fail to set the timestamps on
// symlinks, which makes them appear too recent to be backed
// up immediately, causing test_bbackupd_uploads_files() for
// example to fail. So restore the timestamps manually.
// http://lists.gnu.org/archive/html/bug-tar/2009-08/msg00007.html
// http://git.savannah.gnu.org/cgit/tar.git/plain/NEWS?id=release_1_24
#ifdef HAVE_UTIMENSAT
const struct timespec times[2] = {
{1065707200, 0},
{1065707200, 0},
};
const char * filenames[] = {
"testfiles/TestDir1/symlink1",
"testfiles/TestDir1/symlink2",
"testfiles/TestDir1/symlink3",
NULL,
};
for (int i = 0; filenames[i] != NULL; i++)
{
TEST_THAT_OR(utimensat(AT_FDCWD, filenames[i],
times, AT_SYMLINK_NOFOLLOW) == 0,
BOX_LOG_SYS_ERROR("Failed to change "
"timestamp on symlink: " <<
filenames[i]));
}
#endif
}
TEST_THAT_OR(configure_bbackupd(bbackupd, "testfiles/bbackupd.conf"),
FAIL);
spDaemon = &bbackupd;
return true;
}
//! Simplifies calling setUp() with the current function name in each test.
#define SETUP_TEST_BBACKUPD() \
SETUP(); \
TEST_THAT(bbackupd_pid == 0 || StopClient()); \
TEST_THAT(bbstored_pid == 0 || StopServer()); \
TEST_THAT(kill_running_daemons()); \
TEST_THAT(create_account(10000, 20000));
#define SETUP_WITHOUT_FILES() \
SETUP_TEST_BBACKUPD(); \
BackupDaemon bbackupd; \
TEST_THAT_OR(prepare_test_with_client_daemon(bbackupd, false), FAIL); \
TEST_THAT_OR(::mkdir("testfiles/TestDir1", 0755) == 0, FAIL);
#define SETUP_WITH_BBSTORED() \
SETUP_TEST_BBACKUPD(); \
BackupDaemon bbackupd; \
TEST_THAT_OR(prepare_test_with_client_daemon(bbackupd), FAIL);
#define TEARDOWN_TEST_BBACKUPD() \
TEST_THAT(bbackupd_pid == 0 || StopClient()); \
TEST_THAT(bbstored_pid == 0 || StopServer()); \
TEST_THAT(kill_running_daemons()); \
TEARDOWN();
bool test_basics()
{
SETUP_TEST_BBACKUPD();
TEST_THAT_OR(unpack_files("test_base"), FAIL);
// Read attributes from files
BackupClientFileAttributes t1;
t1.ReadAttributes("testfiles/test1");
TEST_THAT(!t1.IsSymLink());
#ifndef WIN32
BackupClientFileAttributes t2;
t2.ReadAttributes("testfiles/test2");
TEST_THAT(t2.IsSymLink());
// Check that it's actually been encrypted (search for symlink name encoded in it)
void *te = ::memchr(t2.GetBuffer(), 't', t2.GetSize() - 3);
TEST_THAT(te == 0 || ::memcmp(te, "test", 4) != 0);
#endif
BackupClientFileAttributes t3;
{
Logger::LevelGuard(Logging::GetConsole(), Log::ERROR);
TEST_CHECK_THROWS(t3.ReadAttributes("doesn't exist"),
CommonException, OSFileError);
}
// Create some more files
FILE *f = fopen("testfiles/test1_n", "w");
fclose(f);
f = fopen("testfiles/test2_n", "w");
fclose(f);
// Apply attributes to these new files
t1.WriteAttributes("testfiles/test1_n");
#ifdef WIN32
// We can't apply symlink attributes on Win32, so use a normal file's
// attributes instead.
t1.WriteAttributes("testfiles/test2_n");
#else
t2.WriteAttributes("testfiles/test2_n");
#endif
#ifndef WIN32
{
Logger::LevelGuard(Logging::GetConsole(), Log::ERROR);
TEST_CHECK_THROWS(t1.WriteAttributes("testfiles/test1_nXX"),
CommonException, OSFileError);
TEST_CHECK_THROWS(t3.WriteAttributes("doesn't exist"),
BackupStoreException, AttributesNotLoaded);
}
// Test that attributes are vaguely similar
TEST_THAT(attrmatch("testfiles/test1", "testfiles/test1_n"));
TEST_THAT(attrmatch("testfiles/test2", "testfiles/test2_n"));
#endif
// Check encryption, and recovery from encryption
// First, check that two attributes taken from the same thing have different encrypted values (think IV)
BackupClientFileAttributes t1b;
t1b.ReadAttributes("testfiles/test1");
TEST_THAT(::memcmp(t1.GetBuffer(), t1b.GetBuffer(), t1.GetSize()) != 0);
// But that comparing them works OK.
TEST_THAT(t1 == t1b);
// Then store them both to a stream
CollectInBufferStream stream;
t1.WriteToStream(stream);
t1b.WriteToStream(stream);
// Read them back again
stream.SetForReading();
BackupClientFileAttributes t1_r, t1b_r;
t1_r.ReadFromStream(stream, 1000);
t1b_r.ReadFromStream(stream, 1000);
TEST_THAT(::memcmp(t1_r.GetBuffer(), t1b_r.GetBuffer(), t1_r.GetSize()) != 0);
TEST_THAT(t1_r == t1b_r);
TEST_THAT(t1 == t1_r);
TEST_THAT(t1b == t1b_r);
TEST_THAT(t1_r == t1b);
TEST_THAT(t1b_r == t1);
#ifdef HAVE_SYS_XATTR_H
// Write some attributes to the file, checking for ENOTSUP
bool xattrNotSupported = false;
if(!write_xattr_test("testfiles/test1", "user.attr_1", 1000, &xattrNotSupported) && xattrNotSupported)
{
::printf("***********\nYour platform supports xattr, but your filesystem does not.\nSkipping tests.\n***********\n");
}
else
{
BackupClientFileAttributes x1, x2, x3, x4;
// Write more attributes
TEST_THAT(write_xattr_test("testfiles/test1", "user.attr_2", 947));
TEST_THAT(write_xattr_test("testfiles/test1", "user.sadfohij39998.3hj", 123));
// Read file attributes
x1.ReadAttributes("testfiles/test1");
// Write file attributes
FILE *f = fopen("testfiles/test1_nx", "w");
fclose(f);
x1.WriteAttributes("testfiles/test1_nx");
// Compare to see if xattr copied
TEST_THAT(attrmatch("testfiles/test1", "testfiles/test1_nx"));
// Add more attributes to a file
x2.ReadAttributes("testfiles/test1");
TEST_THAT(write_xattr_test("testfiles/test1", "user.328989sj..sdf", 23));
// Read them again, and check that the Compare() function detects that they're different
x3.ReadAttributes("testfiles/test1");
TEST_THAT(x1.Compare(x2, true, true));
TEST_THAT(!x1.Compare(x3, true, true));
// Change the value of one of them, leaving the size the same.
TEST_THAT(write_xattr_test("testfiles/test1", "user.328989sj..sdf", 23));
x4.ReadAttributes("testfiles/test1");
TEST_THAT(!x1.Compare(x4, true, true));
}
finish_with_write_xattr_test();
#endif // HAVE_SYS_XATTR_H
TEARDOWN_TEST_BBACKUPD();
}
int64_t GetDirID(BackupProtocolCallable &protocol, const char *name, int64_t InDirectory)
{
protocol.QueryListDirectory(
InDirectory,
BackupProtocolListDirectory::Flags_Dir,
BackupProtocolListDirectory::Flags_EXCLUDE_NOTHING,
true /* want attributes */);
// Retrieve the directory from the stream following
BackupStoreDirectory dir;
std::auto_ptr<IOStream> dirstream(protocol.ReceiveStream());
dir.ReadFromStream(*dirstream, protocol.GetTimeout());
BackupStoreDirectory::Iterator i(dir);
BackupStoreDirectory::Entry *en = 0;
int64_t dirid = 0;
BackupStoreFilenameClear dirname(name);
while((en = i.Next()) != 0)
{
if(en->GetName() == dirname)
{
dirid = en->GetObjectID();
}
}
return dirid;
}
void terminate_on_alarm(int sigraised)
{
abort();
}
#ifndef WIN32
void do_interrupted_restore(const TLSContext &context, int64_t restoredirid)
{
int pid = 0;
switch((pid = fork()))
{
case 0:
// child process
{
// connect and log in
SocketStreamTLS* pConn = new SocketStreamTLS;
std::auto_ptr<SocketStream> apConn(pConn);
pConn->Open(context, Socket::TypeINET, "localhost", 22011);
BackupProtocolClient protocol(apConn);
protocol.QueryVersion(BACKUP_STORE_SERVER_VERSION);
std::auto_ptr<BackupProtocolLoginConfirmed>
loginConf(protocol.QueryLogin(0x01234567,
BackupProtocolLogin::Flags_ReadOnly));
// Test the restoration
TEST_THAT(BackupClientRestore(protocol, restoredirid,
"testfiles/restore-interrupt", /* remote */
"testfiles/restore-interrupt", /* local */
true /* print progress dots */,
false /* restore deleted */,
false /* undelete after */,
false /* resume */,
false /* keep going */) == Restore_Complete);
// Log out
protocol.QueryFinished();
}
exit(0);
break;
case -1:
{
printf("Fork failed\n");
exit(1);
}
default:
{
// Wait until a resume file is written, then terminate the child
while(true)
{
// Test for existence of the result file
int64_t resumesize = 0;
if(FileExists("testfiles/restore-interrupt.boxbackupresume", &resumesize) && resumesize > 16)
{
// It's done something. Terminate it.
::kill(pid, SIGTERM);
break;
}
// Process finished?
int status = 0;
if(waitpid(pid, &status, WNOHANG) != 0)
{
// child has finished anyway.
return;
}
// Give up timeslot so as not to hog the processor
::sleep(0);
}
// Just wait until the child has completed
int status = 0;
waitpid(pid, &status, 0);
}
}
}
#endif // !WIN32
#ifdef WIN32
bool set_file_time(const char* filename, FILETIME creationTime,
FILETIME lastModTime, FILETIME lastAccessTime)
{
HANDLE handle = openfile(filename, O_RDWR, 0);
TEST_THAT(handle != INVALID_HANDLE_VALUE);
if (handle == INVALID_HANDLE_VALUE) return false;
BOOL success = SetFileTime(handle, &creationTime, &lastAccessTime,
&lastModTime);
TEST_THAT(success);
TEST_THAT(CloseHandle(handle));
return success;
}
#endif
int64_t SearchDir(BackupStoreDirectory& rDir,
const std::string& rChildName)
{
BackupStoreDirectory::Iterator i(rDir);
BackupStoreFilenameClear child(rChildName);
BackupStoreDirectory::Entry *en = i.FindMatchingClearName(child);
if (en == 0) return 0;
int64_t id = en->GetObjectID();
TEST_THAT(id > 0);
TEST_THAT(id != BackupProtocolListDirectory::RootDirectory);
return id;
}
std::auto_ptr<BackupStoreDirectory> ReadDirectory
(
BackupProtocolCallable& rClient,
int64_t id = BackupProtocolListDirectory::RootDirectory
)
{
std::auto_ptr<BackupProtocolSuccess> dirreply(
rClient.QueryListDirectory(id, false, 0, false));
std::auto_ptr<BackupStoreDirectory> apDir(
new BackupStoreDirectory(rClient.ReceiveStream(), SHORT_TIMEOUT));
return apDir;
}
int start_internal_daemon()
{
// ensure that no child processes end up running tests!
int own_pid = getpid();
BOX_TRACE("Test PID is " << own_pid);
// this is a quick hack to allow passing some options to the daemon
const char* argv[] = {
"dummy",
bbackupd_args.c_str(),
};
BackupDaemon daemon;
spDaemon = &daemon; // to propagate into child
int result;
if (bbackupd_args.size() > 0)
{
result = daemon.Main("testfiles/bbackupd.conf", 2, argv);
}
else
{
result = daemon.Main("testfiles/bbackupd.conf", 1, argv);
}
spDaemon = NULL; // to ensure not used by parent
TEST_EQUAL_LINE(0, result, "Daemon exit code");
// ensure that no child processes end up running tests!
if (getpid() != own_pid)
{
// abort!
BOX_INFO("Daemon child finished, exiting now.");
_exit(0);
}
TEST_THAT(TestFileExists("testfiles/bbackupd.pid"));
printf("Waiting for backup daemon to start: ");
int pid = -1;
for (int i = 0; i < 30; i++)
{
printf(".");
fflush(stdout);
safe_sleep(1);
if (TestFileExists("testfiles/bbackupd.pid"))
{
pid = ReadPidFile("testfiles/bbackupd.pid");
}
if (pid > 0)
{
break;
}
}
printf(" done.\n");
fflush(stdout);
TEST_THAT(pid > 0);
spDaemon = &daemon;
return pid;
}
bool stop_internal_daemon(int pid)
{
bool killed_server = KillServer(pid, false);
TEST_THAT(killed_server);
return killed_server;
}
bool test_entry_deleted(BackupStoreDirectory& rDir,
const std::string& rName)
{
BackupStoreDirectory::Iterator i(rDir);
BackupStoreDirectory::Entry *en = i.FindMatchingClearName(
BackupStoreFilenameClear(rName));
TEST_THAT_OR(en != 0, return false);
int16_t flags = en->GetFlags();
TEST_LINE(flags && BackupStoreDirectory::Entry::Flags_Deleted,
rName + " should have been deleted");
return flags && BackupStoreDirectory::Entry::Flags_Deleted;
}
bool compare(BackupQueries::ReturnCode::Type expected_status,
const std::string& bbackupquery_options = "",
const std::string& compare_options = "-acQ")
{
std::string cmd = BBACKUPQUERY;
cmd += " ";
cmd += (expected_status == BackupQueries::ReturnCode::Compare_Same)
? "-Wwarning" : "-Werror";
cmd += " -c testfiles/bbackupd.conf ";
cmd += " " + bbackupquery_options;
cmd += " \"compare " + compare_options + "\" quit";
int returnValue = ::system(cmd.c_str());
int expected_system_result = (int) expected_status;
#ifndef WIN32
expected_system_result <<= 8;
#endif
TEST_EQUAL_LINE(expected_system_result, returnValue, "compare return value");
TestRemoteProcessMemLeaks("bbackupquery.memleaks");
return (returnValue == expected_system_result);
}
bool compare_local(BackupQueries::ReturnCode::Type expected_status,
BackupProtocolCallable& client,
const std::string& compare_options = "acQ")
{
std::auto_ptr<Configuration> config =
load_config_file(DEFAULT_BBACKUPD_CONFIG_FILE, BackupDaemonConfigVerify);
TEST_THAT_OR(config.get(), return false);
BackupQueries bbackupquery(client, *config, false);
std::vector<std::string> args;
bool opts[256] = {};
for (std::string::const_iterator i = compare_options.begin();
i != compare_options.end(); i++)
{
opts[(unsigned char)*i] = true;
}
bbackupquery.CommandCompare(args, opts);
TEST_EQUAL_OR(expected_status, bbackupquery.GetReturnCode(),
return false);
return true;
}
bool bbackupquery(const std::string& arguments,
const std::string& memleaks_file = "bbackupquery.memleaks")
{
std::string cmd = BBACKUPQUERY;
cmd += " -c testfiles/bbackupd.conf " + arguments + " quit";
int returnValue = ::system(cmd.c_str());
#ifndef WIN32
returnValue >>= 8;
#endif
TestRemoteProcessMemLeaks(memleaks_file.c_str());
TEST_EQUAL(returnValue, BackupQueries::ReturnCode::Command_OK);
return (returnValue == BackupQueries::ReturnCode::Command_OK);
}
bool restore(const std::string& location, const std::string& dest_dir)
{
std::string cmd = "\"restore " + location + " " + dest_dir + "\"";
TEST_THAT_OR(bbackupquery(cmd), FAIL);
return true;
}
bool touch_and_wait(const std::string& filename)
{
int fd = open(filename.c_str(), O_CREAT | O_WRONLY, 0755);
TEST_THAT(fd > 0);
if (fd <= 0) return false;
// write again, to update the file's timestamp
int write_result = write(fd, "z", 1);
TEST_EQUAL_LINE(1, write_result, "Buffer write");
if (write_result != 1) return false;
TEST_THAT(close(fd) == 0);
// wait long enough to put file into sync window
wait_for_operation(5, "locally modified file to "
"mature for sync");
return true;
}
TLSContext sTlsContext;
#define TEST_COMPARE(...) \
TEST_THAT(compare(BackupQueries::ReturnCode::__VA_ARGS__));
#define TEST_COMPARE_LOCAL(...) \
TEST_THAT(compare_local(BackupQueries::ReturnCode::__VA_ARGS__));
bool search_for_file(const std::string& filename)
{
std::auto_ptr<BackupProtocolCallable> client =
connect_and_login(sTlsContext, BackupProtocolLogin::Flags_ReadOnly);
std::auto_ptr<BackupStoreDirectory> dir = ReadDirectory(*client);
int64_t testDirId = SearchDir(*dir, filename);
client->QueryFinished();
return (testDirId != 0);
}
class MockClientContext : public BackupClientContext
{
public:
BackupProtocolCallable& mrClient;
int mNumKeepAlivesPolled;
int mKeepAliveTime;
MockClientContext
(
LocationResolver &rResolver,
TLSContext &rTLSContext,
const std::string &rHostname,
int32_t Port,
uint32_t AccountNumber,
bool ExtendedLogging,
bool ExtendedLogToFile,
std::string ExtendedLogFile,
ProgressNotifier &rProgressNotifier,
bool TcpNiceMode,
BackupProtocolCallable& rClient
)
: BackupClientContext(rResolver, rTLSContext,
rHostname, Port, AccountNumber, ExtendedLogging,
ExtendedLogToFile, ExtendedLogFile,
rProgressNotifier, TcpNiceMode),
mrClient(rClient),