-
Notifications
You must be signed in to change notification settings - Fork 969
Expand file tree
/
Copy pathsyncjournaldb.cpp
More file actions
3326 lines (2828 loc) · 116 KB
/
Copy pathsyncjournaldb.cpp
File metadata and controls
3326 lines (2828 loc) · 116 KB
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
/*
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2014 ownCloud GmbH
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include <QCryptographicHash>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLoggingCategory>
#include <QStringList>
#include <QElapsedTimer>
#include <QUrl>
#include <QDir>
#include <sqlite3.h>
#include <cstring>
#include "common/syncjournaldb.h"
#include "version.h"
#include "filesystembase.h"
#include "common/asserts.h"
#include "common/checksums.h"
#include "common/preparedsqlquerymanager.h"
#include "common/c_jhash.h"
// SQL expression to check whether path.startswith(prefix + '/')
// Note: '/' + 1 == '0'
#define IS_PREFIX_PATH_OF(prefix, path) \
"(" path " > (" prefix "||'/') AND " path " < (" prefix "||'0'))"
#define IS_PREFIX_PATH_OR_EQUAL(prefix, path) \
"(" path " == " prefix " OR " IS_PREFIX_PATH_OF(prefix, path) ")"
static constexpr auto MAJOR_VERSION_3 = 3;
static constexpr auto MINOR_VERSION_16 = 16;
using namespace Qt::StringLiterals;
namespace OCC {
Q_LOGGING_CATEGORY(lcDb, "nextcloud.sync.database", QtInfoMsg)
#define GET_FILE_RECORD_QUERY \
"SELECT path, inode, modtime, type, md5, fileid, remotePerm, filesize," \
" ignoredChildrenRemote, contentchecksumtype.name || ':' || contentChecksum, e2eMangledName, isE2eEncrypted, e2eCertificateFingerprint, " \
" lock, lockOwnerDisplayName, lockOwnerId, lockType, lockOwnerEditor, lockTime, lockTimeout, lockToken, isShared, lastShareStateFetchedTimestmap, " \
" sharedByMe, isLivePhoto, livePhotoFile, quotaBytesUsed, quotaBytesAvailable" \
" FROM metadata" \
" LEFT JOIN checksumtype as contentchecksumtype ON metadata.contentChecksumTypeId == contentchecksumtype.id"
static void fillFileRecordFromGetQuery(SyncJournalFileRecord &rec, SqlQuery &query)
{
rec._path = query.baValue(0);
rec._inode = query.int64Value(1);
rec._modtime = query.int64Value(2);
rec._type = static_cast<ItemType>(query.intValue(3));
rec._etag = query.baValue(4);
rec._fileId = query.baValue(5);
rec._remotePerm = RemotePermissions::fromDbValue(query.baValue(6));
rec._fileSize = query.int64Value(7);
rec._serverHasIgnoredFiles = (query.intValue(8) > 0);
rec._checksumHeader = query.baValue(9);
rec._e2eMangledName = query.baValue(10);
rec._e2eEncryptionStatus = static_cast<SyncJournalFileRecord::EncryptionStatus>(query.intValue(11));
rec._lockstate._locked = query.intValue(13) > 0;
rec._lockstate._lockOwnerDisplayName = query.stringValue(14);
rec._lockstate._lockOwnerId = query.stringValue(15);
rec._lockstate._lockOwnerType = query.int64Value(16);
rec._lockstate._lockEditorApp = query.stringValue(17);
rec._lockstate._lockTime = query.int64Value(18);
rec._lockstate._lockTimeout = query.int64Value(19);
rec._lockstate._lockToken = query.stringValue(20);
rec._isShared = query.intValue(21) > 0;
rec._lastShareStateFetchedTimestamp = query.int64Value(22);
rec._sharedByMe = query.intValue(23) > 0;
rec._isLivePhoto = query.intValue(24) > 0;
rec._livePhotoFile = query.stringValue(25);
rec._folderQuota.bytesUsed = query.int64Value(26);
rec._folderQuota.bytesAvailable = query.int64Value(27);
}
static QByteArray defaultJournalMode(const QString &dbPath)
{
#if defined(Q_OS_WIN)
// See #2693: Some exFAT file systems seem unable to cope with the
// WAL journaling mode. They work fine with DELETE.
QString fileSystem = FileSystem::fileSystemForPath(dbPath);
qCInfo(lcDb) << "Detected filesystem" << fileSystem << "for" << dbPath;
if (fileSystem.contains(QLatin1String("FAT"))) {
qCInfo(lcDb) << "Filesystem contains FAT - using DELETE journal mode";
return "DELETE";
}
#elif defined(Q_OS_MACOS)
if (dbPath.startsWith(QLatin1String("/Volumes/"))) {
qCInfo(lcDb) << "Mounted sync dir, do not use WAL for" << dbPath;
return "DELETE";
}
#else
Q_UNUSED(dbPath)
#endif
return "WAL";
}
SyncJournalDb::SyncJournalDb(const QString &dbFilePath, QObject *parent)
: QObject(parent)
, _dbFile(dbFilePath)
{
// Allow forcing the journal mode for debugging
static QByteArray envJournalMode = qgetenv("OWNCLOUD_SQLITE_JOURNAL_MODE");
_journalMode = envJournalMode;
if (_journalMode.isEmpty()) {
_journalMode = defaultJournalMode(_dbFile);
}
}
QString SyncJournalDb::makeDbName(const QString &localPath,
const QUrl &remoteUrl,
const QString &remotePath,
const QString &user)
{
QString journalPath = QStringLiteral(".sync_");
QString key = QStringLiteral("%1@%2:%3").arg(user, remoteUrl.toString(), remotePath);
QByteArray ba = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
journalPath += QString::fromLatin1(ba.left(6).toHex()) + QStringLiteral(".db");
// If it exists already, the path is clearly usable
QFile file(QDir(localPath).filePath(journalPath));
if (file.exists()) {
return journalPath;
}
// Try to create a file there
if (file.open(QIODevice::ReadWrite)) {
// Ok, all good.
file.close();
file.remove();
return journalPath;
}
// Error during creation, just keep the original and throw errors later
qCWarning(lcDb) << "Could not find a writable database path" << file.fileName() << file.errorString();
return journalPath;
}
bool SyncJournalDb::maybeMigrateDb(const QString &localPath, const QString &absoluteJournalPath)
{
const QString oldDbName = localPath + QLatin1String(".csync_journal.db");
if (!FileSystem::fileExists(oldDbName)) {
return true;
}
const QString oldDbNameShm = oldDbName + QStringLiteral("-shm");
const QString oldDbNameWal = oldDbName + QStringLiteral("-wal");
const QString newDbName = absoluteJournalPath;
const QString newDbNameShm = newDbName + QStringLiteral("-shm");
const QString newDbNameWal = newDbName + QStringLiteral("-wal");
// Whenever there is an old db file, migrate it to the new db path.
// This is done to make switching from older versions to newer versions
// work correctly even if the user had previously used a new version
// and therefore already has an (outdated) new-style db file.
QString error;
if (FileSystem::fileExists(newDbName)) {
if (!FileSystem::remove(newDbName, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db file" << newDbName
<< "due to" << error;
return false;
}
}
if (FileSystem::fileExists(newDbNameWal)) {
if (!FileSystem::remove(newDbNameWal, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db WAL file" << newDbNameWal
<< "due to" << error;
return false;
}
}
if (FileSystem::fileExists(newDbNameShm)) {
if (!FileSystem::remove(newDbNameShm, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db SHM file" << newDbNameShm
<< "due to" << error;
return false;
}
}
if (!FileSystem::rename(oldDbName, newDbName, &error)) {
qCWarning(lcDb) << "Database migration: could not rename" << oldDbName
<< "to" << newDbName << ":" << error;
return false;
}
if (!FileSystem::rename(oldDbNameWal, newDbNameWal, &error)) {
qCWarning(lcDb) << "Database migration: could not rename" << oldDbNameWal
<< "to" << newDbNameWal << ":" << error;
return false;
}
if (!FileSystem::rename(oldDbNameShm, newDbNameShm, &error)) {
qCWarning(lcDb) << "Database migration: could not rename" << oldDbNameShm
<< "to" << newDbNameShm << ":" << error;
return false;
}
qCInfo(lcDb) << "Journal successfully migrated from" << oldDbName << "to" << newDbName;
return true;
}
bool SyncJournalDb::findPathInSelectiveSyncList(const QStringList &list, const QString &path)
{
Q_ASSERT(std::is_sorted(list.cbegin(), list.cend()));
if (list.size() == 1 && list.first() == QStringLiteral("/")) {
// Special case for the case "/" is there, it matches everything
return true;
}
const QString pathSlash = path + QLatin1Char('/');
// Since the list is sorted, we can do a binary search.
// If the path is a prefix of another item or right after in the lexical order.
auto it = std::lower_bound(list.cbegin(), list.cend(), pathSlash);
if (it != list.cend() && *it == pathSlash) {
return true;
}
if (it == list.cbegin()) {
return false;
}
--it;
Q_ASSERT(it->endsWith(QLatin1Char('/'))); // Folder::setSelectiveSyncBlackList makes sure of that
return pathSlash.startsWith(*it);
}
bool SyncJournalDb::exists()
{
QMutexLocker locker(&_mutex);
return (!_dbFile.isEmpty() && QFile::exists(_dbFile));
}
QString SyncJournalDb::databaseFilePath() const
{
return _dbFile;
}
// Note that this does not change the size of the -wal file, but it is supposed to make
// the normal .db faster since the changes from the wal will be incorporated into it.
// Then the next sync (and the SocketAPI) will have a faster access.
void SyncJournalDb::walCheckpoint()
{
QElapsedTimer t;
t.start();
SqlQuery pragma1(_db);
pragma1.prepare("PRAGMA wal_checkpoint(FULL);");
if (pragma1.exec()) {
qCDebug(lcDb) << "took" << t.elapsed() << "msec";
}
}
void SyncJournalDb::startTransaction()
{
if (_transaction == 0) {
if (!_db.transaction()) {
qCWarning(lcDb) << "ERROR starting transaction:" << _db.error();
return;
}
_transaction = 1;
} else {
qCDebug(lcDb) << "Database Transaction is running, not starting another one!";
}
}
void SyncJournalDb::commitTransaction()
{
if (_transaction == 1) {
if (!_db.commit()) {
qCWarning(lcDb) << "ERROR committing to the database:" << _db.error();
return;
}
_transaction = 0;
} else {
qCDebug(lcDb) << "No database Transaction to commit";
}
}
bool SyncJournalDb::sqlFail(const QString &log, const SqlQuery &query)
{
commitTransaction();
qCWarning(lcDb) << "SQL Error" << log << query.error();
_db.close();
ASSERT(false);
return false;
}
bool SyncJournalDb::checkConnect()
{
if (autotestFailCounter >= 0) {
if (!autotestFailCounter--) {
qCInfo(lcDb) << "Error Simulated";
return false;
}
}
if (_db.isOpen()) {
// Unfortunately the sqlite isOpen check can return true even when the underlying storage
// has become unavailable - and then some operations may cause crashes. See #6049
if (!QFile::exists(_dbFile)) {
qCWarning(lcDb) << "Database open, but file" << _dbFile << "does not exist";
close();
return false;
}
return true;
}
if (_dbFile.isEmpty()) {
qCWarning(lcDb) << "Database filename" << _dbFile << "is empty";
return false;
}
// The database file is created by this call (SQLITE_OPEN_CREATE)
if (!_db.openOrCreateReadWrite(_dbFile)) {
QString error = _db.error();
qCWarning(lcDb) << "Error opening the db:" << error;
return false;
}
if (!QFile::exists(_dbFile)) {
qCWarning(lcDb) << "Database file" << _dbFile << "does not exist";
return false;
}
SqlQuery pragma1(_db);
pragma1.prepare("SELECT sqlite_version();");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("SELECT sqlite_version()"), pragma1);
} else {
pragma1.next();
qCInfo(lcDb) << "sqlite3 version" << pragma1.stringValue(0);
}
// Set locking mode to avoid issues with WAL on Windows
static QByteArray locking_mode_env = qgetenv("OWNCLOUD_SQLITE_LOCKING_MODE");
if (locking_mode_env.isEmpty())
locking_mode_env = "EXCLUSIVE";
pragma1.prepare("PRAGMA locking_mode=" + locking_mode_env + ";");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("Set PRAGMA locking_mode"), pragma1);
} else {
pragma1.next();
qCInfo(lcDb) << "sqlite3 locking_mode=" << pragma1.stringValue(0);
}
pragma1.prepare("PRAGMA journal_mode=" + _journalMode + ";");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("Set PRAGMA journal_mode"), pragma1);
} else {
pragma1.next();
qCInfo(lcDb) << "sqlite3 journal_mode=" << pragma1.stringValue(0);
}
// For debugging purposes, allow temp_store to be set
static QByteArray env_temp_store = qgetenv("OWNCLOUD_SQLITE_TEMP_STORE");
if (!env_temp_store.isEmpty()) {
pragma1.prepare("PRAGMA temp_store = " + env_temp_store + ";");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("Set PRAGMA temp_store"), pragma1);
}
qCInfo(lcDb) << "sqlite3 with temp_store =" << env_temp_store;
}
// With WAL journal the NORMAL sync mode is safe from corruption,
// otherwise use the standard FULL mode.
QByteArray synchronousMode = "FULL";
if (QString::fromUtf8(_journalMode).compare(QStringLiteral("wal"), Qt::CaseInsensitive) == 0)
synchronousMode = "NORMAL";
pragma1.prepare("PRAGMA synchronous = " + synchronousMode + ";");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("Set PRAGMA synchronous"), pragma1);
} else {
qCInfo(lcDb) << "sqlite3 synchronous=" << synchronousMode;
}
pragma1.prepare("PRAGMA case_sensitive_like = ON;");
if (!pragma1.exec()) {
return sqlFail(QStringLiteral("Set PRAGMA case_sensitivity"), pragma1);
}
sqlite3_create_function(_db.sqliteDb(), "parent_hash", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
[] (sqlite3_context *ctx,int, sqlite3_value **argv) {
auto text = reinterpret_cast<const char*>(sqlite3_value_text(argv[0]));
const char *end = std::strrchr(text, '/');
if (!end) end = text;
sqlite3_result_int64(ctx, c_jhash64(reinterpret_cast<const uint8_t*>(text),
end - text, 0));
}, nullptr, nullptr);
/* Because insert is so slow, we do everything in a transaction, and only need one call to commit */
startTransaction();
SqlQuery createQuery(_db);
createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
"phash INTEGER(8),"
"pathlen INTEGER,"
"path VARCHAR(4096),"
"inode INTEGER,"
"uid INTEGER,"
"gid INTEGER,"
"mode INTEGER,"
"modtime INTEGER(8),"
"type INTEGER,"
"md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */
// updateDatabaseStructure() will add
// fileid
// remotePerm
// filesize
// ignoredChildrenRemote
// contentChecksum
// contentChecksumTypeId
"PRIMARY KEY(phash)"
");");
#ifndef SQLITE_IOERR_SHMMAP
// Requires sqlite >= 3.7.7 but old CentOS6 has sqlite-3.6.20
// Definition taken from https://sqlite.org/c3ref/c_abort_rollback.html
#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
#endif
if (!createQuery.exec()) {
// In certain situations the io error can be avoided by switching
// to the DELETE journal mode, see #5723
if (_journalMode != "DELETE"
&& createQuery.errorId() == SQLITE_IOERR
&& sqlite3_extended_errcode(_db.sqliteDb()) == SQLITE_IOERR_SHMMAP) {
qCWarning(lcDb) << "IO error SHMMAP on table creation, attempting with DELETE journal mode";
_journalMode = "DELETE";
commitTransaction();
_db.close();
return checkConnect();
}
return sqlFail(QStringLiteral("Create table metadata"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS key_value_store(key VARCHAR(4096), value VARCHAR(4096), PRIMARY KEY(key));");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table key_value_store"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
"path VARCHAR(4096),"
"tmpfile VARCHAR(4096),"
"etag VARCHAR(32),"
"errorcount INTEGER,"
"PRIMARY KEY(path)"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table downloadinfo"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
"path VARCHAR(4096),"
"chunk INTEGER,"
"transferid INTEGER,"
"errorcount INTEGER,"
"size INTEGER(8),"
"modtime INTEGER(8),"
"contentChecksum TEXT,"
"PRIMARY KEY(path)"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table uploadinfo"), createQuery);
}
// create the blacklist table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist ("
"path VARCHAR(4096),"
"lastTryEtag VARCHAR[32],"
"lastTryModtime INTEGER[8],"
"retrycount INTEGER,"
"errorstring VARCHAR[4096],"
"PRIMARY KEY(path)"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table blacklist"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS async_poll("
"path VARCHAR(4096),"
"modtime INTEGER(8),"
"filesize BIGINT,"
"pollpath VARCHAR(4096));");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table async_poll"), createQuery);
}
// create the selectivesync table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS selectivesync ("
"path VARCHAR(4096),"
"type INTEGER"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table selectivesync"), createQuery);
}
// create the checksumtype table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS checksumtype("
"id INTEGER PRIMARY KEY,"
"name TEXT UNIQUE"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table checksumtype"), createQuery);
}
// create the datafingerprint table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS datafingerprint("
"fingerprint TEXT UNIQUE"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table datafingerprint"), createQuery);
}
// create the flags table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS flags ("
"path TEXT PRIMARY KEY,"
"pinState INTEGER"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table flags"), createQuery);
}
// create the conflicts table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS conflicts("
"path TEXT PRIMARY KEY,"
"baseFileId TEXT,"
"baseEtag TEXT,"
"baseModtime INTEGER"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table conflicts"), createQuery);
}
// create the caseconflicts table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS caseconflicts("
"path TEXT PRIMARY KEY,"
"baseFileId TEXT,"
"baseEtag TEXT,"
"baseModtime INTEGER,"
"basePath TEXT UNIQUE"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table caseconflicts"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS version("
"major INTEGER(8),"
"minor INTEGER(8),"
"patch INTEGER(8),"
"custom VARCHAR(256)"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table version"), createQuery);
}
// create the e2EeLockedFolders table.
createQuery.prepare(
"CREATE TABLE IF NOT EXISTS e2EeLockedFolders("
"folderId VARCHAR(128) PRIMARY KEY,"
"token VARCHAR(4096)"
");");
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Create table e2EeLockedFolders"), createQuery);
}
bool forceRemoteDiscovery = false;
SqlQuery versionQuery("SELECT major, minor, patch FROM version;", _db);
if (!versionQuery.next().hasData) {
forceRemoteDiscovery = true;
createQuery.prepare("INSERT INTO version VALUES (?1, ?2, ?3, ?4);");
createQuery.bindValue(1, MIRALL_VERSION_MAJOR);
createQuery.bindValue(2, MIRALL_VERSION_MINOR);
createQuery.bindValue(3, MIRALL_VERSION_PATCH);
createQuery.bindValue(4, static_cast<qulonglong>(MIRALL_VERSION_BUILD));
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Update version"), createQuery);
}
} else {
int major = versionQuery.intValue(0);
int minor = versionQuery.intValue(1);
int patch = versionQuery.intValue(2);
if (major == 1 && minor == 8 && (patch == 0 || patch == 1)) {
qCInfo(lcDb) << "possibleUpgradeFromMirall_1_8_0_or_1 detected!";
forceRemoteDiscovery = true;
}
// There was a bug in versions <2.3.0 that could lead to stale
// local files and a remote discovery will fix them.
// See #5190 #5242.
if (major == 2 && minor < 3) {
qCInfo(lcDb) << "upgrade form client < 2.3.0 detected! forcing remote discovery";
forceRemoteDiscovery = true;
}
// Not comparing the BUILD id here, correct?
if (!(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH)) {
createQuery.prepare("UPDATE version SET major=?1, minor=?2, patch =?3, custom=?4 "
"WHERE major=?5 AND minor=?6 AND patch=?7;");
createQuery.bindValue(1, MIRALL_VERSION_MAJOR);
createQuery.bindValue(2, MIRALL_VERSION_MINOR);
createQuery.bindValue(3, MIRALL_VERSION_PATCH);
createQuery.bindValue(4, static_cast<qulonglong>(MIRALL_VERSION_BUILD));
createQuery.bindValue(5, major);
createQuery.bindValue(6, minor);
createQuery.bindValue(7, patch);
if (!createQuery.exec()) {
return sqlFail(QStringLiteral("Update version"), createQuery);
}
if (major < MAJOR_VERSION_3 || (major == MAJOR_VERSION_3 && minor <= MINOR_VERSION_16)) {
const auto fixEncryptionResult = ensureCorrectEncryptionStatus();
if (!fixEncryptionResult) {
qCWarning(lcDb) << "Failed to update the encryption status";
}
}
}
}
commitInternal(QStringLiteral("checkConnect"));
bool rc = updateDatabaseStructure();
if (!rc) {
qCWarning(lcDb) << "Failed to update the database structure!";
}
/*
* If we are upgrading from a client version older than 1.5,
* we cannot read from the database because we need to fetch the files id and etags.
*
* If 1.8.0 caused missing data in the local tree, so we also don't read from DB
* to get back the files that were gone.
* In 1.8.1 we had a fix to re-get the data, but this one here is better
*/
if (forceRemoteDiscovery) {
forceRemoteDiscoveryNextSyncLocked();
}
const auto deleteDownloadInfo = _queryManager.get(PreparedSqlQueryManager::DeleteDownloadInfoQuery, QByteArrayLiteral("DELETE FROM downloadinfo WHERE path=?1"), _db);
if (!deleteDownloadInfo) {
qCWarning(lcDb) << "database error:" << deleteDownloadInfo->error();
return sqlFail(QStringLiteral("prepare _deleteDownloadInfoQuery"), *deleteDownloadInfo);
}
const auto deleteUploadInfoQuery = _queryManager.get(PreparedSqlQueryManager::DeleteUploadInfoQuery, QByteArrayLiteral("DELETE FROM uploadinfo WHERE path=?1"), _db);
if (!deleteUploadInfoQuery) {
qCWarning(lcDb) << "database error:" << deleteUploadInfoQuery->error();
return sqlFail(QStringLiteral("prepare _deleteUploadInfoQuery"), *deleteUploadInfoQuery);
}
QByteArray sql("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget, errorCategory, requestId "
"FROM blacklist WHERE path=?1");
if (Utility::fsCasePreserving()) {
// if the file system is case preserving we have to check the blacklist
// case insensitively
sql += " COLLATE NOCASE";
}
const auto getErrorBlacklistQuery = _queryManager.get(PreparedSqlQueryManager::GetErrorBlacklistQuery, sql, _db);
if (!getErrorBlacklistQuery) {
qCWarning(lcDb) << "database error:" << getErrorBlacklistQuery->error();
return sqlFail(QStringLiteral("prepare _getErrorBlacklistQuery"), *getErrorBlacklistQuery);
}
// don't start a new transaction now
commitInternal(QStringLiteral("checkConnect End"), false);
// This avoid reading from the DB if we already know it is empty
// thereby speeding up the initial discovery significantly.
_metadataTableIsEmpty = (getFileRecordCount() == 0);
// Hide 'em all!
FileSystem::setFileHidden(databaseFilePath(), true);
FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-wal"), true);
FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-shm"), true);
FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-journal"), true);
return rc;
}
void SyncJournalDb::close()
{
QMutexLocker locker(&_mutex);
qCInfo(lcDb) << "Closing DB" << _dbFile;
commitTransaction();
_db.close();
clearEtagStorageFilter();
_selectiveSyncListCache.clear();
_metadataTableIsEmpty = false;
}
bool SyncJournalDb::updateDatabaseStructure()
{
if (!updateMetadataTableStructure())
return false;
if (!updateErrorBlacklistTableStructure())
return false;
return true;
}
bool SyncJournalDb::hasDefaultValue(const QString &columnName)
{
SqlQuery query(_db);
const auto selectDefault = QStringLiteral("SELECT dflt_value FROM pragma_table_info('metadata') WHERE name = '%1';").arg(columnName);
query.prepare(selectDefault.toLatin1());
if (!query.exec()) {
sqlFail(QStringLiteral("check default value for: %1").arg(columnName), query);
return false;
}
if (const auto result = query.next();!result.ok || !result.hasData) {
qCWarning(lcDb) << "database error:" << query.error();
return false;
}
return !query.nullValue(0);
}
bool SyncJournalDb::removeColumn(const QString &columnName)
{
SqlQuery query(_db);
const auto request = QStringLiteral("ALTER TABLE metadata DROP COLUMN %1;").arg(columnName);
query.prepare(request.toLatin1());
if (!query.exec()) {
sqlFail(QStringLiteral("update metadata structure: drop %1 column").arg(columnName), query);
return false;
}
commitInternal(QStringLiteral("update database structure: drop %1 column").arg(columnName));
return true;
}
bool SyncJournalDb::updateMetadataTableStructure()
{
auto columns = tableColumns("metadata");
bool re = true;
// check if the file_id column is there and create it if not
if (columns.isEmpty()) {
return false;
}
const auto columnExists = [&columns] (const QString &columnName) -> bool {
return columns.indexOf(columnName.toLatin1()) > -1;
};
const auto addColumn = [this, &re, &columnExists] (const QString &columnName, const QString &dataType, const bool withIndex = false, const QString defaultCommand = {}) {
if (!columnExists(columnName)) {
SqlQuery query(_db);
auto request = QStringLiteral("ALTER TABLE metadata ADD COLUMN %1 %2").arg(columnName).arg(dataType);
if (!defaultCommand.isEmpty()) {
request.append(QStringLiteral(" ") + defaultCommand);
}
request.append(QStringLiteral(";"));
query.prepare(request.toLatin1());
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: add %1 column").arg(columnName), query);
re = false;
}
if (withIndex) {
query.prepare(QStringLiteral("CREATE INDEX metadata_%1 ON metadata(%1);").arg(columnName).toLatin1());
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index %1").arg(columnName), query);
re = false;
}
}
commitInternal(QStringLiteral("update database structure: add %1 column").arg(columnName));
}
};
addColumn(QStringLiteral("fileid"), QStringLiteral("VARCHAR(128)"), true);
addColumn(QStringLiteral("remotePerm"), QStringLiteral("VARCHAR(128)"));
addColumn(QStringLiteral("filesize"), QStringLiteral("BIGINT"));
if (true) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_inode ON metadata(inode);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index inode"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add inode index"));
}
if (true) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_path ON metadata(path);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index path"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add path index"));
}
if (true) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_parent ON metadata(parent_hash(path));");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index parent"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add parent index"));
}
addColumn(QStringLiteral("ignoredChildrenRemote"), QStringLiteral("INT"));
addColumn(QStringLiteral("contentChecksum"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("contentChecksumTypeId"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("e2eMangledName"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("isE2eEncrypted"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("e2eCertificateFingerprint"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("isShared"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("lastShareStateFetchedTimestmap"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("sharedByMe"), QStringLiteral("INTEGER"));
auto uploadInfoColumns = tableColumns("uploadinfo");
if (uploadInfoColumns.isEmpty())
return false;
if (!uploadInfoColumns.contains("contentChecksum")) {
SqlQuery query(_db);
query.prepare("ALTER TABLE uploadinfo ADD COLUMN contentChecksum TEXT;");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: add contentChecksum column"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add contentChecksum col for uploadinfo"));
}
auto conflictsColumns = tableColumns("conflicts");
if (conflictsColumns.isEmpty())
return false;
if (!conflictsColumns.contains("basePath")) {
SqlQuery query(_db);
query.prepare("ALTER TABLE conflicts ADD COLUMN basePath TEXT;");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: add basePath column"), query);
re = false;
}
}
if (true) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_e2e_id ON metadata(e2eMangledName);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index e2eMangledName"), query);
re = false;
}
query.prepare("CREATE INDEX IF NOT EXISTS metadata_e2e_status ON metadata (path, phash, type, isE2eEncrypted)");
if (!query.exec()) {
sqlFail(QStringLiteral("updateMetadataTableStructure: create index metadata_e2e_status"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add e2eMangledName index"));
}
addColumn(QStringLiteral("lock"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("lockType"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("lockOwnerDisplayName"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("lockOwnerId"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("lockOwnerEditor"), QStringLiteral("TEXT"));
addColumn(QStringLiteral("lockTime"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("lockTimeout"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("lockToken"), QStringLiteral("TEXT"));
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS caseconflicts_basePath ON caseconflicts(basePath);");
if (!query.exec()) {
sqlFail(QStringLiteral("caseconflictsTableStructure: create index basePath"), query);
return re = false;
}
commitInternal(QStringLiteral("update database structure: add basePath index"));
addColumn(QStringLiteral("isLivePhoto"), QStringLiteral("INTEGER"));
addColumn(QStringLiteral("livePhotoFile"), QStringLiteral("TEXT"));
{
const auto quotaBytesUsed = QStringLiteral("quotaBytesUsed");
const auto quotaBytesAvailable = QStringLiteral("quotaBytesAvailable");
const auto defaultCommand = QStringLiteral("DEFAULT -1 NOT NULL");
const auto bigInt = QStringLiteral("BIGINT");
auto result = false;
if (columnExists(quotaBytesUsed) && !hasDefaultValue(quotaBytesUsed)) {
result = removeColumn(quotaBytesUsed);
}
if (columnExists(quotaBytesAvailable) && !hasDefaultValue(quotaBytesAvailable)) {
result = removeColumn(quotaBytesAvailable);
}
if (result) {
columns = tableColumns("metadata");
}
addColumn(quotaBytesUsed, bigInt, false, defaultCommand);
addColumn(quotaBytesAvailable, bigInt, false, defaultCommand);
}
return re;
}
bool SyncJournalDb::updateErrorBlacklistTableStructure()
{
auto columns = tableColumns("blacklist");
bool re = true;
if (columns.isEmpty()) {
return false;
}
if (columns.indexOf("lastTryTime") == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN lastTryTime INTEGER(8);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateBlacklistTableStructure: Add lastTryTime fileid"), query);
re = false;
}
query.prepare("ALTER TABLE blacklist ADD COLUMN ignoreDuration INTEGER(8);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateBlacklistTableStructure: Add ignoreDuration fileid"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add lastTryTime, ignoreDuration cols"));
}
if (columns.indexOf("renameTarget") == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN renameTarget VARCHAR(4096);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateBlacklistTableStructure: Add renameTarget"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add renameTarget col"));
}
if (columns.indexOf("errorCategory") == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN errorCategory INTEGER(8);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateBlacklistTableStructure: Add errorCategory"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add errorCategory col"));
}
if (columns.indexOf("requestId") == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN requestId VARCHAR(36);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateBlacklistTableStructure: Add requestId"), query);
re = false;
}
commitInternal(QStringLiteral("update database structure: add errorCategory col"));
}
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS blacklist_index ON blacklist(path collate nocase);");
if (!query.exec()) {
sqlFail(QStringLiteral("updateErrorBlacklistTableStructure: create index blacklit"), query);
re = false;
}
return re;
}
QVector<QByteArray> SyncJournalDb::tableColumns(const QByteArray &table)
{
QVector<QByteArray> columns;
if (!checkConnect()) {
return columns;
}
SqlQuery query("PRAGMA table_info('" + table + "');", _db);
if (!query.exec()) {
return columns;
}
while (query.next().hasData) {
columns.append(query.baValue(1));
}
qCDebug(lcDb) << "Columns in the current journal:" << columns;