/
backupExecuter.cpp
executable file
·2392 lines (2091 loc) · 70.1 KB
/
backupExecuter.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
#include "backupExecuter.h"
#include "backupMain.h"
#include "Utilities.h"
#include "crc32.h"
#include <QSettings>
#include <QFileDialog>
#include <QTextBrowser>
#include <QCalendarWidget>
#include <QDesktopWidget>
#include <QThread>
#include <QWidget>
#include <QMenu>
#define BUFF_SIZE (5*1024*1024)
QString backupExecuter::nullStr = "";
QFile backupExecuter::fileObj;
static const unsigned long header = 'VISL';
static const unsigned long magic = 'BKUP';
QString getConfigurationsPath(QString const &organization, QString const &application)
{
QString path = QDir::homePath()+"/"+organization+"/"+application+"/";
QDir dir(path);
if( dir.mkpath(path) )
return path;
else
return "";
}
class waitHelper : public QThread
{
public:
void Sleep(int msecs) { msleep(msecs); }
};
class fullMessage : public QMessageBox
{
public:
fullMessage( QWidget *parent, QString const &path )
: QMessageBox(QMessageBox::NoIcon,"destination drive full","destination drive is full.\n\nPlease remove some files.",QMessageBox::Cancel,parent)
, m_path(path)
{
QApplication::alert(this);
setIconPixmap(QApplication::style()->standardPixmap(QStyle::SP_DriveHDIcon));
startTimer(60000);
}
protected:
virtual void timerEvent ( QTimerEvent */* event*/ )
{
accept();
}
private:
QString m_path;
};
class mediaMessage : public QMessageBox
{
public:
mediaMessage( QWidget *parent, QString const &path )
: QMessageBox(QMessageBox::NoIcon,"removable media not found","'"+path+"' not found.\n\nPlease insert removable media containing this path.",QMessageBox::Cancel,parent)
, m_path(path)
{
QApplication::alert(this);
setIconPixmap(QApplication::style()->standardPixmap(QStyle::SP_DriveHDIcon));
startTimer(2000);
}
QString getPath()
{
return m_path;
}
protected:
virtual void timerEvent ( QTimerEvent */* event*/ )
{
bool tryMultiple = false;
int deviceNo = 3;
do
{
if( m_path.length()>=2 )
{
if( m_path.at(1)==':' )
m_path[1] = 'A'+deviceNo;
QDir dir(m_path);
if( dir.exists() )
accept();
if( m_path.at(1)==':' )
tryMultiple = (deviceNo<10);
}
} while(tryMultiple);
}
private:
QString m_path;
};
static waitHelper m_waiter;
static quint32 crcDataVersion;
backupExecuter::backupExecuter(backupConfigData &configData)
: m_config(configData)
, log(NULL)
, m_bringToFront(false)
, m_isBatch(false)
, m_running(false)
, m_error(false)
, m_dirsCreated(false)
, m_closed(false)
, m_background(false)
, m_diskFull(false)
, m_runUnattended(false)
, dircount(0)
, files_to_copy(0)
, kbytes_to_copy(0)
, lastVerifiedK(0)
, verifiedK(0)
, checksumsChanged(false)
, m_engine(new backupEngine(*this))
{
setObjectName("backupExecuter");
setupUi(this);
setWindowTitle("Backup Configuration '"+m_config.m_sName+"'");
connect(qApp->desktop(),SIGNAL(resized(int)),this,SLOT(screenResizedSlot(int)));
//loadData();
QSettings settings;
int titleheight = settings.value("WindowTitlebarHeight").toInt();
int framewidth = settings.value("WindowFramewidth").toInt();
int w = width();
int h = minimumSizeHint().height();
QRect screen = qApp->desktop()->availableGeometry();
setGeometry(screen.x()+screen.width()/2-w/2-framewidth,screen.y()+screen.height()/2-(h+titleheight)/2,w,h);
startTimer(100);
}
QDataStream &operator<<(QDataStream &out, const struct crcInfo &src)
{
out << src.crc << (quint64)src.lastScan;
return out;
}
QDataStream &operator>>(QDataStream &in, struct crcInfo &dst)
{
quint64 timestamp;
in >> dst.crc;
if( crcDataVersion&0x80000000 )
{
in >> timestamp;
dst.lastScan = timestamp;
}
return in;
}
backupExecuter::~backupExecuter()
{
m_engine->processEventsAndWait();
delete m_engine;
}
void backupExecuter::screenResizedSlot( int /*screen*/ )
{
changeVisibility();
}
void backupExecuter::loadData()
{
crcSummary.clear();
QString summaryFile = backupDirStruct::getChecksumSummaryFile(m_config.m_sDst);
QFile crcfile(summaryFile);
if( QFile::exists(summaryFile) )
{
crcfile.open(QIODevice::ReadOnly);
QDataStream str(&crcfile);
str >> crcDataVersion;
if( crcDataVersion&0x80000000 )
str >> lastVerifiedK;
else
lastVerifiedK = crcDataVersion;
str >> crcSummary;
crcfile.close();
}
else
lastVerifiedK = 0;
QString tocSummaryFile = backupDirStruct::getTocSummaryFile(m_config.m_sDst);
m_dirs.readFromFile(tocSummaryFile);
}
void backupExecuter::saveData()
{
bool isOk = true;
if( checksumsChanged )
{
QString summaryFile = backupDirStruct::getChecksumSummaryFile(m_config.m_sDst);
QFile crcfile(summaryFile);
crcfile.open(QIODevice::WriteOnly | QIODevice::Truncate);
QDataStream str(&crcfile);
str << 0x80000000;
str << lastVerifiedK;
str << crcSummary;
isOk = (crcfile.error()==QFileDevice::NoError);
crcfile.close();
}
checksumsChanged = false;
if( isOk && m_dirs.tocHasChanged() )
{
QString tocSummaryFile = backupDirStruct::getTocSummaryFile(m_config.m_sDst);
isOk = m_dirs.writeToFile(tocSummaryFile);
}
if( !isOk )
{
QString str = "++++ destination drive is full. Could not update the TOC data!\r\n";
stream << str; errstream.append(str);
m_diskFull = true;
}
}
void backupExecuter::changeVisibility()
{
if( m_config.m_bBackground )
{
progresslabel->hide();
if( m_isBatch )
{
actualfile->hide();
cancelButt->hide();
m_engine->setToolTipText(QString("Automatic Backup V")+BACKUP_STR_VERSION+" running.\nProcessing Configuration '"+m_config.m_sName+"'");
}
else
{
actualfile->setFixedWidth(450);
actualfile->setAlignment(Qt::AlignRight);
}
// give the layouts time to process size chages
qApp->processEvents(QEventLoop::ExcludeUserInputEvents,10000);
int height = minimumSizeHint().height();
int width = minimumSizeHint().width();
setWindowOnScreen(this,width,height);
}
else
{
resize( width(), 0 ); // dialog wil be as small as possible
setWindowTitle("Processing Configuration '"+m_config.m_sName+"'");
}
}
void backupExecuter::startBatchProcessing()
{
startingAction();
m_isBatch = true;
changeVisibility();
}
void backupExecuter::stopBatchProcessing()
{
m_isBatch = false;
stoppingAction();
}
QString const &backupExecuter::defaultAt( QStringList const &list, int ix )
{
if( (ix<0) || (ix>=list.count()) )
return nullStr;
else
return list.at(ix);
}
QFile *backupExecuter::openFile( QString const &filename, bool readOnly )
{
const char *organization = "config-valentins-qtsolutions";
const char *application = "backup";
QString inifile = getConfigurationsPath(organization,application)+"settings.ini";
QSettings settings(inifile,QSettings::IniFormat);
QString path = "";
if( settings.contains("LogFile") )
{
path = settings.value("LogFile").toString();
if( !path.endsWith("/") ) path.append("/");
}
else
{
path = getConfigurationsPath(organization,application);
settings.setValue("LogFile",path);
}
//path = settings.value("LogFile","").toString();
//if( path.isEmpty() ) settings.setValue("LogFile",path = "./backup.log");
if( fileObj.isOpen() ) fileObj.close();
fileObj.setFileName(path + (filename.isNull() ? "backup.log" : filename));
if( fileObj.size()>2000000 ) fileObj.remove();
if( fileObj.open(readOnly ? QIODevice::ReadOnly : QIODevice::ReadWrite|QIODevice::Append) )
return &fileObj;
else
{
fileObj.setFileName(QString());
return &fileObj;
}
}
void backupExecuter::displayResult( QWidget *parent, QString const &text, QString const windowTitle )
{
QDialog d(parent);
QVBoxLayout *l = new QVBoxLayout(&d);
QTextEdit *ed = new QTextEdit(&d);
QPushButton *ok = new QPushButton(&d);
l->addWidget(ed);
l->addWidget(ok);
ed->setFont(QFont("Courier"));
ed->setLineWrapMode(QTextEdit::NoWrap);
ed->setWordWrapMode(QTextOption::NoWrap);
ed->setReadOnly(true);
ed->setText(text);
ok->setText("OK");
ok->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Fixed);
connect(ok,SIGNAL(clicked()),&d,SLOT(accept()));
d.setWindowTitle(windowTitle);
d.resize(800,600);
d.exec();
}
void backupExecuter::setWindowOnScreen(QWidget *widget,int width,int height)
{
QSettings settings;
QString position = settings.value("BackupWindowPosition","ll").toString();
int titleheight = (widget->objectName()=="backupExecuter") ? settings.value("WindowTitlebarHeight").toInt() : 0;
int framewidth = (widget->objectName()=="backupExecuter") ? settings.value("WindowFramewidth").toInt() : 0;
QRect screen = qApp->desktop()->availableGeometry();
if( position=="ll" )
widget->setGeometry(screen.x(),screen.y()+screen.height()-height,width,height); // lower left (the default)
else if( position=="ur" )
widget->setGeometry(screen.x()+screen.width()-width-framewidth,screen.y()+titleheight,width,height); // upper right
else if( position=="ul" )
widget->setGeometry(screen.x(),screen.y()+titleheight,width,height); // upper left
else if( position=="lr" )
widget->setGeometry(screen.x()+screen.width()-width-framewidth,screen.y()+screen.height()-height,width,height); // lower right
}
QDateTime backupExecuter::getLimitDate(QWidget *parent,const QDateTime &startingDate)
{
QDateTime result;
QDialog d(parent);
QVBoxLayout vert(&d);
QHBoxLayout hor(&d);
QCalendarWidget w(&d);
QPushButton cancel("Cancel");
QPushButton prevy("<<");
QPushButton prevm("<");
QPushButton nextm(">");
QPushButton nexty(">>");
QPushButton butt("OK");
vert.addWidget(&w);
hor.addWidget(&cancel);
hor.addWidget(&prevy);
hor.addWidget(&prevm);
hor.addWidget(&nextm);
hor.addWidget(&nexty);
hor.addWidget(&butt);
vert.addLayout(&hor);
w.setSelectedDate(startingDate.date());
d.connect(&cancel,SIGNAL(clicked()),&d,SLOT(reject()));
d.connect(&prevy,SIGNAL(clicked()),&w,SLOT(showPreviousYear()));
d.connect(&prevm,SIGNAL(clicked()),&w,SLOT(showPreviousMonth()));
d.connect(&nextm,SIGNAL(clicked()),&w,SLOT(showNextMonth()));
d.connect(&nexty,SIGNAL(clicked()),&w,SLOT(showNextYear()));
d.connect(&butt,SIGNAL(clicked()),&d,SLOT(accept()));
d.setWindowTitle("find files older than");
d.resize(d.sizeHint());
if( d.exec()==QDialog::Accepted )
{
result = QDateTime(w.selectedDate());
}
else
{
result = QDateTime();
}
return result;
}
void backupExecuter::processProgressMaximum(int maximum)
{
progressbar->setMaximum(maximum);
}
void backupExecuter::processProgressValue(int value)
{
progressbar->setValue(value);
}
void backupExecuter::processProgressText(QString const &text)
{
QFontMetrics metrics(progresslabel->font());
if( !text.isEmpty() )
{
QString messagetext = text;
while( progresslabel->width()<metrics.width(messagetext) )
{
int len = messagetext.length() - 4;
messagetext = text.left(len/2)+"..."+messagetext.right(len/2);
}
progresslabel->setText(messagetext);
}
else
progresslabel->setText(text);
}
void backupExecuter::processFileNameText(QString const &text)
{
QFontMetrics metrics(actualfile->font());
if( !text.isEmpty() )
{
QString messagetext = text;
while( actualfile->width()<metrics.width(messagetext) )
{
int len = messagetext.length() - 4;
messagetext = text.left(len/2)+"..."+messagetext.right(len/2);
}
actualfile->setText(messagetext);
}
else
actualfile->setText(text);
}
void backupExecuter::startingAction()
{
if( m_isBatch ) return;
m_running=true;
m_error=false;
m_dirsCreated = false;
cancelButt->setText("Cancel");
if( m_config.m_bVerbose || m_config.m_bVerboseMaint )
{
if( buff.open(QIODevice::Truncate|QIODevice::WriteOnly) )
stream.setDevice(&buff);
}
else
{
log = openFile(QString());
if( log->fileName()!=QString() )
stream.setDevice(log);
else if( m_config.m_bAuto )
stream << "++++ problem found in backup: directory doesn't exist: couldn't open log file " << "\r\n";
else
QMessageBox::warning(this,"backup problems","couldn't open log file 'backup.log'");
}
QString str = "================ backup '" + m_config.m_sName + "' starting on " + QDateTime::currentDateTime().toString() + " ================\r\n";
stream << str; errstream.append(str);
QStringList incexcl = m_config.m_sFlt.remove("+").split("-");
QString includingsstr = defaultAt(incexcl,0);
QString excludingsstr = defaultAt(incexcl,1);
QStringList includings = includingsstr.remove(")").split("(");
QStringList excludings = excludingsstr.remove(")").split("(");
dirincludes = defaultAt(includings,0).split( ";", QString::SkipEmptyParts );
fileincludes = defaultAt(includings,1).split( ";", QString::SkipEmptyParts );
direxcludes = defaultAt(excludings,0).split( ";", QString::SkipEmptyParts );
fileexcludes = defaultAt(excludings,1).split( ";", QString::SkipEmptyParts );
stream << "regarding directory names containing '" << defaultAt(includings,0) << "' but not '" << defaultAt(excludings,0) << "'\r\n";
stream << "regarding file names containing '" << defaultAt(includings,1) << "' but not'" << defaultAt(excludings,1) << "'\r\n";
directories.clear();
filelist.clear();
files_to_copy = 0;
kbytes_to_copy = 0;
dircount = 1;
startTime = QDateTime::currentDateTime();
}
void backupExecuter::stoppingAction()
{
QString str = "================ backup '" + m_config.m_sName + "' ending on " + QDateTime::currentDateTime().toString() + " ================\r\n";
stream << str;
if( m_config.m_bVerbose || m_config.m_bVerboseMaint )
{
buff.close();
displayResult(this,QString(buff.buffer()));
}
else
{
if( m_error )
{
if( m_runUnattended )
{
QString str = "#### problem(s) found in backup: one or more files couldn't be copied to destination.\r\n";
stream << str;
QFile *fp = openFile("errors");
if( fp->fileName()!=QString() )
{
fp->write(errstream.toLatin1().data());
fp->close();
}
}
else
{
if( m_diskFull )
{
fullMessage msg(this,m_config.m_sDst);
msg.exec();
}
else
{
QApplication::alert(this);
QMessageBox::warning(this,"backup problems","problems occured during backup.\nPlease refer to 'backup.log' for details.");
displayResult(this,errstream,"backup errors");
}
}
m_error = false;
errstream = "";
}
log->close();
}
m_running=false;
if( m_isBatch ) return;
stream.setDevice(0);
m_engine->setProgressText("");
m_engine->setFileNameText("");
cancelButt->setText("OK");
}
bool backupExecuter::updateAutoBackupTime()
{
stream << "updating backup time of automatic item '"+m_config.m_sName+"'\r\n";
QFile tst(getAutobackupCheckFile(""));
bool wasFound = tst.exists();
if( tst.open(QIODevice::WriteOnly) )
{
QTextStream stream(&tst);
stream << QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
tst.close();
}
else
stream << "++++ couldn't create automatic test item\r\n";
return wasFound;
}
bool backupExecuter::updateAutoVerifyTime()
{
stream << "updating verify time of automatic item '"+m_config.m_sName+"'\r\n";
QFile tst(getAutobackupCheckFile("_chk"));
bool wasFound = tst.exists();
if( tst.open(QIODevice::WriteOnly) )
{
QTextStream stream(&tst);
stream << QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
tst.close();
}
else
stream << "++++ couldn't create automatic test item\r\n";
return wasFound;
}
void backupExecuter::checkTimeout()
{
if( m_config.m_bsuspend )
{
static int times[] = { 10,15,30,60,90,120,150,180,210,240 };
int maxtime = times[m_config.m_iTimeout]*60;
if( startTime.secsTo(QDateTime::currentDateTime())>maxtime )
{
stream << "---> suspending backup due to given timeout\r\n";
cancel();
}
}
}
void backupExecuter::findDirectories( QString const &start )
{
if( start.isEmpty() )
{
m_engine->setProgressText("Finding Directories...");
m_engine->setProgressMaximum(m_dirs.size());
directories.append(m_config.m_sSrc+"/");
findDirectories(m_config.m_sSrc+"/");
}
else
{
QDir dir(start);
dir.setFilter( QDir::AllDirs | QDir::Dirs | QDir::NoSymLinks );
dir.setNameFilters(QStringList("*"));
if( !dir.exists() )
{
m_error = true;
QString str = "++++ problem found in backup: given source directory doesn't exist: '" + start + "'\r\n";
stream << str; errstream.append(str);
return;
}
const QFileInfoList &list = dir.entryInfoList();
QFileInfoList::const_iterator it = list.begin();
QFileInfo fi;
while ( m_running && (it!=list.end()) )
{
checkTimeout();
fi = *it;
QString actual = fi.fileName();
if( actual!="." && actual!=".." )
{
QString path = start+actual;
// bool passed = true;
// bool stepinto = true;
// if( !dirincludes.isEmpty() )
// passed = false;
// for ( QStringList::Iterator it2 = dirincludes.begin(); it2 != dirincludes.end(); ++it2 )
// {
// if( (*it2).isEmpty() || path.contains(*it2) )
// passed = true;
// }
// for ( QStringList::Iterator it3 = direxcludes.begin(); passed && it3 != direxcludes.end(); ++it3 )
// {
// if( !(*it3).isEmpty() && path.contains(*it3) )
// {
// passed = false;
// stepinto = false;
// }
// }
bool passed = allowedByExcludes(path,true,false);
if( passed )
{
if( m_config.m_bVerbose )
stream << "checking directory " << path << "\r\n";
}
else
{
stream << " skipping directory " << path << "\r\n";
}
if( passed )
{
dircount++;
if( dircount>progressbar->maximum() )
m_engine->setProgressMaximum(0); // show busy indicator
else
m_engine->setProgressValue(dircount);
m_engine->setFileNameText(path);
directories.append(path);
findDirectories(path+"/");
}
}
++it;
}
}
}
void backupExecuter::analyzeDirectories()
{
if( !m_running ) return;
int i = 0;
unsigned totalcount = 0;
unsigned long totaldirkbytes = 0;
m_engine->setProgressText("Scanning Directories...");
m_engine->setProgressMaximum(dircount);
for ( QStringList::Iterator it=directories.begin(); m_running && it!=directories.end(); ++it,i++ )
{
checkTimeout();
if( m_isBatch )
m_engine->setToolTipText(QString("Automatic Backup V")+BACKUP_STR_VERSION+" running.\nProcessing Directory '"+*it+"'");
m_engine->setFileNameText(*it);
m_engine->setProgressValue(i);
if( m_config.m_bBackground )
m_waiter.Sleep(20);
QString srcpath = *it;
QDir dir(srcpath);
dir.setFilter( QDir::Files | QDir::NoSymLinks );
dir.setNameFilters(QStringList("*"));
if( !dir.exists() )
{
m_error = true;
QString str = "++++ problem found in backup: source directory doesn't exist: '"+srcpath+"'\r\n";
stream << str; errstream.append(str);
continue;
}
const QFileInfoList &list = dir.entryInfoList();
QFileInfoList::const_iterator it2=list.begin();
QFileInfo srcFile;
unsigned count = 0;
unsigned long dirkbytes = 0;
bool destinationExists = false;
while ( m_running && (it2!=list.end()) )
{
checkTimeout();
if( m_config.m_bBackground )
m_waiter.Sleep(20);
srcFile = *it2;
QString actualName = srcFile.fileName();
QString fullName = srcFile.absoluteFilePath();
bool copy = false;
if( isAutoBackupCreatedFile(actualName) )
{
copy = false;
}
else if( !srcFile.isSymLink() && actualName!="." && actualName!=".." )
{
if( allowedByExcludes(fullName,false,true) )
{
if( !destinationExists )
{
bool justCreated = false;
destinationExists = ensureDirExists(srcpath,m_config.m_sSrc,m_config.m_sDst,justCreated);
if( destinationExists )
copy = justCreated;
else
{
m_error = true;
QString str = "++++ problem found in backup: destination directory could not be created for: '"+srcpath+"'\r\n";
stream << str; errstream.append(str);
++it2;
continue;
}
}
if( !copy )
{
QString filePath = srcFile.dir().absolutePath();
QString fileName = srcFile.fileName();
qint64 modify = srcFile.lastModified().toMSecsSinceEpoch();
m_engine->setFileNameText(filePath+"/"+fileName);
QString relPath = filePath.mid(m_config.m_sSrc.length()+1);
if( m_dirs.exists(relPath,fileName) )
{
qint64 lastm = m_dirs.lastModified(relPath,fileName);
if( modify>lastm )
// file is newer than in TOC
copy = true;
}
else
{
// file not found in TOC, add to list for later check and copy
copy = true;
}
}
if( !copy )
stream << " no changes in " << fullName << "\r\n";
}
else
stream << " skipping file " << fullName << "\r\n";
}
if( copy )
{
qint64 filesize = srcFile.size();
QString relName = fullName.mid(m_config.m_sSrc.length());
filelist.append(relName);
files_to_copy++;
kbytes_to_copy += (filesize/1024);
count++;
dirkbytes += (filesize/1024);
}
++it2;
}
if( count>0 )
{
stream << "---> " << count << " updated files with " << dirkbytes << " Kbytes found in " << srcpath << "\r\n";
totalcount += count;
totaldirkbytes += dirkbytes;
}
}
if( totalcount>0 )
{
stream << "====> " << totalcount << " changed files with " << totaldirkbytes << " Kbytes\r\n";
}
}
bool backupExecuter::allowedByExcludes(QString const &fullPath, bool checkDirectoriesFilter, bool checkFilesFilter)
{
bool passed = true;
if( checkDirectoriesFilter )
{
if( !dirincludes.isEmpty() )
passed = false;
int separator = fullPath.lastIndexOf("/");
QString path = separator>=0 ? fullPath.mid(separator+1) : fullPath;
for ( QStringList::Iterator it2 = dirincludes.begin(); it2 != dirincludes.end(); ++it2 )
{
QString regexp = QRegularExpression::wildcardToRegularExpression(*it2);
if( (*it2).isEmpty() || path.indexOf(QRegularExpression(regexp))>=0 )
passed = true;
}
for ( QStringList::Iterator it3 = direxcludes.begin(); passed && it3 != direxcludes.end(); ++it3 )
{
QString regexp = QRegularExpression::wildcardToRegularExpression(*it3);
if( !(*it3).isEmpty() && path.indexOf(QRegularExpression(regexp))>=0 )
//if( !(*it3).isEmpty() && fullPath.contains(*it3) )
{
passed = false;
}
}
}
if( checkFilesFilter )
{
if( passed )
{
int separator = fullPath.lastIndexOf("/");
QString filename = separator>=0 ? fullPath.mid(separator+1) : fullPath;
// second, check files filter
if( !fileincludes.isEmpty() )
passed = false;
for ( QStringList::Iterator it3 = fileincludes.begin(); it3 != fileincludes.end(); ++it3 )
{
QString regexp = QRegularExpression::wildcardToRegularExpression(*it3);
if( (*it3).isEmpty() || filename.indexOf(QRegularExpression(regexp))>=0 )
passed = true;
}
for ( QStringList::Iterator it4 = fileexcludes.begin(); passed && it4 != fileexcludes.end(); ++it4 )
{
QString regexp = QRegularExpression::wildcardToRegularExpression(*it4);
if( !(*it4).isEmpty() && filename.indexOf(QRegularExpression(regexp))>=0 )
passed = false;
}
}
}
return passed;
}
bool backupExecuter::ensureDirExists( QString const &fullPath, QString const &srcBase, QString const &dstBase, bool &hasbeenCreated)
{
bool result = true;
hasbeenCreated = false;
QString relpath = fullPath.mid(srcBase.length());
QString dstpath = relpath.prepend(dstBase);
QDir dst(dstpath);
if( !dst.exists() )
{
if( m_config.m_bVerboseMaint )
stream << dst.absolutePath() << " not found in destination, would be created\r\n";
else
{
stream << dst.absolutePath() << " not found in destination, so creating it\r\n";
if( dst.mkpath(dstpath) )
hasbeenCreated = true;
else
{
result = false;
m_error = true;
QString str = "++++ can't create directory '"+dst.absolutePath()+"'!\r\n";
stream << str; errstream.append(str);
}
}
}
return result;
}
void backupExecuter::copySelectedFiles()
{
QString srcFile;
QString dstFile;
char *buffer = NULL;
unsigned int copiedFiles = 0;
unsigned long copiedk = 0;
Crc32 crcsum;
if( !m_running ) return;
const int buffsize = 5*1024*1024;
buffer = new char[buffsize];
m_engine->setProgressMaximum(kbytes_to_copy);
QString prefix = backupDirStruct::createFileNamePrefix(m_config.m_bKeep,false);
QTime startTime = QTime::currentTime();
for ( QStringList::Iterator it2=filelist.begin(); m_running && it2!=filelist.end(); ++it2 )
{
checkTimeout();
static quint64 lastmsecs = 0;
quint64 msecs = QDateTime::currentDateTime().toMSecsSinceEpoch();
if( (msecs-lastmsecs)>100 )
{
m_engine->setProgressText("processing "+QString::number(copiedFiles)+" of "+QString::number(files_to_copy)+" files ("+QString::number(copiedk/1024L)+" of "+QString::number(kbytes_to_copy/1024L)+" MB done)...");
m_engine->setFileNameText(*it2);
m_engine->setProgressValue(copiedk);
lastmsecs = msecs;
}
copiedFiles++;
//m_engine->setProgressText("processing "+QString::number(copiedFiles)+" of "+QString::number(files_to_copy)+" files...");
if( !m_running )
break;
QString relName = *it2;
srcFile = m_config.m_sSrc + relName;
dstFile = m_config.m_sDst + (prefix.isEmpty() ? relName : backupDirStruct::addFilenamePrefix(relName,prefix));
QFileInfo srcInfo(srcFile);
QString filePath = srcInfo.dir().absolutePath();
QString relPath = filePath.mid(m_config.m_sSrc.length()+1);
QString fileName = srcInfo.fileName();
qint64 modify = srcInfo.lastModified().toMSecsSinceEpoch();
if( m_config.m_bKeep )
{
QStringList toBeDeleted;
m_dirs.keepFiles(relPath,fileName,m_config.m_iVersions-1,toBeDeleted);
QStringList::iterator it = toBeDeleted.begin();
while (it!=toBeDeleted.end())
{
QString fullName = m_config.m_sDst + "/" + *it;
QFile::remove(fullName);
++it;
}
}
crcsum.initInstance(0);
QFile src(srcFile);
bool opened = false;
if( src.open(QIODevice::ReadOnly) )
{
QFile dst(dstFile);
if( QFile::exists(dstFile+".partial") )
{
QFile dst2(dstFile+".partial");
qint64 pos = dst2.size();
src.seek(pos);
copiedk += (pos/1024);
//crcsum.initfromfile()
dst2.rename(dstFile);
opened = dst.open(QIODevice::Append|QIODevice::WriteOnly);
stream << "* found part of destination file " << dstFile << " (" << pos << " bytes), continuing with copy\r\n";
}
else if( QFile::exists(dstFile) )
{
QFileInfo dstInfo(dstFile);
if( (srcInfo.size()!=dstInfo.size())
|| (srcInfo.lastModified().toSecsSinceEpoch()!=dstInfo.lastModified().toSecsSinceEpoch())
)
{
dst.setPermissions(dst.permissions() |