discoveryphase.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * Copyright (C) by Olivier Goffart <ogoffart@woboq.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  11. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * for more details.
  13. */
  14. #pragma once
  15. #include <QObject>
  16. #include <QElapsedTimer>
  17. #include <QStringList>
  18. #include <csync.h>
  19. #include <QMap>
  20. #include <QSet>
  21. #include "networkjobs.h"
  22. #include <QMutex>
  23. #include <QWaitCondition>
  24. #include <QRunnable>
  25. #include <deque>
  26. #include "syncoptions.h"
  27. #include "syncfileitem.h"
  28. class ExcludedFiles;
  29. namespace OCC {
  30. namespace LocalDiscoveryEnums {
  31. OCSYNC_EXPORT Q_NAMESPACE
  32. enum class LocalDiscoveryStyle {
  33. FilesystemOnly, //< read all local data from the filesystem
  34. DatabaseAndFilesystem, //< read from the db, except for listed paths
  35. };
  36. Q_ENUM_NS(LocalDiscoveryStyle)
  37. }
  38. using OCC::LocalDiscoveryEnums::LocalDiscoveryStyle;
  39. class Account;
  40. class SyncJournalDb;
  41. class ProcessDirectoryJob;
  42. enum class ErrorCategory;
  43. /**
  44. * Represent all the meta-data about a file in the server
  45. */
  46. struct RemoteInfo
  47. {
  48. /** FileName of the entry (this does not contains any directory or path, just the plain name */
  49. QString name;
  50. QByteArray etag;
  51. QByteArray fileId;
  52. QByteArray checksumHeader;
  53. OCC::RemotePermissions remotePerm;
  54. time_t modtime = 0;
  55. int64_t size = 0;
  56. int64_t sizeOfFolder = 0;
  57. bool isDirectory = false;
  58. bool _isE2eEncrypted = false;
  59. bool isFileDropDetected = false;
  60. QString e2eMangledName;
  61. bool sharedByMe = false;
  62. [[nodiscard]] bool isValid() const { return !name.isNull(); }
  63. [[nodiscard]] bool isE2eEncrypted() const { return _isE2eEncrypted; }
  64. QString directDownloadUrl;
  65. QString directDownloadCookies;
  66. SyncFileItem::LockStatus locked = SyncFileItem::LockStatus::UnlockedItem;
  67. QString lockOwnerDisplayName;
  68. QString lockOwnerId;
  69. SyncFileItem::LockOwnerType lockOwnerType = SyncFileItem::LockOwnerType::UserLock;
  70. QString lockEditorApp;
  71. qint64 lockTime = 0;
  72. qint64 lockTimeout = 0;
  73. };
  74. struct LocalInfo
  75. {
  76. /** FileName of the entry (this does not contains any directory or path, just the plain name */
  77. QString name;
  78. QString caseClashConflictingName;
  79. time_t modtime = 0;
  80. int64_t size = 0;
  81. uint64_t inode = 0;
  82. ItemType type = ItemTypeSkip;
  83. bool isDirectory = false;
  84. bool isHidden = false;
  85. bool isVirtualFile = false;
  86. bool isSymLink = false;
  87. [[nodiscard]] bool isValid() const { return !name.isNull(); }
  88. };
  89. /**
  90. * @brief Run list on a local directory and process the results for Discovery
  91. *
  92. * @ingroup libsync
  93. */
  94. class DiscoverySingleLocalDirectoryJob : public QObject, public QRunnable
  95. {
  96. Q_OBJECT
  97. public:
  98. explicit DiscoverySingleLocalDirectoryJob(const AccountPtr &account, const QString &localPath, OCC::Vfs *vfs, QObject *parent = nullptr);
  99. void run() override;
  100. signals:
  101. void finished(QVector<OCC::LocalInfo> result);
  102. void finishedFatalError(QString errorString);
  103. void finishedNonFatalError(QString errorString);
  104. void itemDiscovered(OCC::SyncFileItemPtr item);
  105. void childIgnored(bool b);
  106. private slots:
  107. private:
  108. QString _localPath;
  109. AccountPtr _account;
  110. OCC::Vfs* _vfs;
  111. public:
  112. };
  113. /**
  114. * @brief Run a PROPFIND on a directory and process the results for Discovery
  115. *
  116. * @ingroup libsync
  117. */
  118. class DiscoverySingleDirectoryJob : public QObject
  119. {
  120. Q_OBJECT
  121. public:
  122. explicit DiscoverySingleDirectoryJob(const AccountPtr &account, const QString &path, QObject *parent = nullptr);
  123. // Specify that this is the root and we need to check the data-fingerprint
  124. void setIsRootPath() { _isRootPath = true; }
  125. void start();
  126. void abort();
  127. [[nodiscard]] bool isFileDropDetected() const;
  128. [[nodiscard]] bool encryptedMetadataNeedUpdate() const;
  129. // This is not actually a network job, it is just a job
  130. signals:
  131. void firstDirectoryPermissions(OCC::RemotePermissions);
  132. void etag(const QByteArray &, const QDateTime &time);
  133. void finished(const OCC::HttpResult<QVector<OCC::RemoteInfo>> &result);
  134. private slots:
  135. void directoryListingIteratedSlot(const QString &, const QMap<QString, QString> &);
  136. void lsJobFinishedWithoutErrorSlot();
  137. void lsJobFinishedWithErrorSlot(QNetworkReply *);
  138. void fetchE2eMetadata();
  139. void metadataReceived(const QJsonDocument &json, int statusCode);
  140. void metadataError(const QByteArray& fileId, int httpReturnCode);
  141. private:
  142. [[nodiscard]] bool isE2eEncrypted() const { return _isE2eEncrypted != SyncFileItem::EncryptionStatus::NotEncrypted; }
  143. QVector<RemoteInfo> _results;
  144. QString _subPath;
  145. QByteArray _firstEtag;
  146. QByteArray _fileId;
  147. QByteArray _localFileId;
  148. AccountPtr _account;
  149. // The first result is for the directory itself and need to be ignored.
  150. // This flag is true if it was already ignored.
  151. bool _ignoredFirst = false;
  152. // Set to true if this is the root path and we need to check the data-fingerprint
  153. bool _isRootPath = false;
  154. // If this directory is an external storage (The first item has 'M' in its permission)
  155. bool _isExternalStorage = false;
  156. // If this directory is e2ee
  157. SyncFileItem::EncryptionStatus _isE2eEncrypted = SyncFileItem::EncryptionStatus::NotEncrypted;
  158. bool _isFileDropDetected = false;
  159. bool _encryptedMetadataNeedUpdate = false;
  160. // If set, the discovery will finish with an error
  161. int64_t _size = 0;
  162. QString _error;
  163. QPointer<LsColJob> _lsColJob;
  164. public:
  165. QByteArray _dataFingerprint;
  166. };
  167. class DiscoveryPhase : public QObject
  168. {
  169. Q_OBJECT
  170. friend class ProcessDirectoryJob;
  171. QPointer<ProcessDirectoryJob> _currentRootJob;
  172. /** Maps the db-path of a deleted item to its SyncFileItem.
  173. *
  174. * If it turns out the item was renamed after all, the instruction
  175. * can be changed. See findAndCancelDeletedJob(). Note that
  176. * itemDiscovered() will already have been emitted for the item.
  177. */
  178. QMap<QString, SyncFileItemPtr> _deletedItem;
  179. QVector<QString> _directoryNamesToRestoreOnPropagation;
  180. /** Maps the db-path of a deleted folder to its queued job.
  181. *
  182. * If a folder is deleted and must be recursed into, its job isn't
  183. * executed immediately. Instead it's queued here and only run
  184. * once the rest of the discovery has finished and we are certain
  185. * that the folder wasn't just renamed. This avoids running the
  186. * discovery on contents in the old location of renamed folders.
  187. *
  188. * See findAndCancelDeletedJob().
  189. */
  190. QMap<QString, ProcessDirectoryJob *> _queuedDeletedDirectories;
  191. // map source (original path) -> destinations (current server or local path)
  192. QMap<QString, QString> _renamedItemsRemote;
  193. QMap<QString, QString> _renamedItemsLocal;
  194. // set of paths that should not be removed even though they are removed locally:
  195. // there was a move to an invalid destination and now the source should be restored
  196. //
  197. // This applies recursively to subdirectories.
  198. // All entries should have a trailing slash (even files), so lookup with
  199. // lowerBound() is reliable.
  200. //
  201. // The value of this map doesn't matter.
  202. QMap<QString, bool> _forbiddenDeletes;
  203. /** Returns whether the db-path has been renamed locally or on the remote.
  204. *
  205. * Useful for avoiding processing of items that have already been claimed in
  206. * a rename (would otherwise be discovered as deletions).
  207. */
  208. [[nodiscard]] bool isRenamed(const QString &p) const { return _renamedItemsLocal.contains(p) || _renamedItemsRemote.contains(p); }
  209. int _currentlyActiveJobs = 0;
  210. // both must contain a sorted list
  211. QStringList _selectiveSyncBlackList;
  212. QStringList _selectiveSyncWhiteList;
  213. void scheduleMoreJobs();
  214. [[nodiscard]] bool isInSelectiveSyncBlackList(const QString &path) const;
  215. // Check if the new folder should be deselected or not.
  216. // May be async. "Return" via the callback, true if the item is blacklisted
  217. void checkSelectiveSyncNewFolder(const QString &path, RemotePermissions rp,
  218. std::function<void(bool)> callback);
  219. /** Given an original path, return the target path obtained when renaming is done.
  220. *
  221. * Note that it only considers parent directory renames. So if A/B got renamed to C/D,
  222. * checking A/B/file would yield C/D/file, but checking A/B would yield A/B.
  223. */
  224. [[nodiscard]] QString adjustRenamedPath(const QString &original, SyncFileItem::Direction) const;
  225. /** If the db-path is scheduled for deletion, abort it.
  226. *
  227. * Check if there is already a job to delete that item:
  228. * If that's not the case, return { false, QByteArray() }.
  229. * If there is such a job, cancel that job and return true and the old etag.
  230. *
  231. * Used when having detected a rename: The rename source may have been
  232. * discovered before and would have looked like a delete.
  233. *
  234. * See _deletedItem and _queuedDeletedDirectories.
  235. */
  236. QPair<bool, QByteArray> findAndCancelDeletedJob(const QString &originalPath);
  237. void enqueueDirectoryToDelete(const QString &path, ProcessDirectoryJob* const directoryJob);
  238. public:
  239. // input
  240. QString _localDir; // absolute path to the local directory. ends with '/'
  241. QString _remoteFolder; // remote folder, ends with '/'
  242. SyncJournalDb *_statedb = nullptr;
  243. AccountPtr _account;
  244. SyncOptions _syncOptions;
  245. ExcludedFiles *_excludes = nullptr;
  246. QRegularExpression _invalidFilenameRx; // FIXME: maybe move in ExcludedFiles
  247. QStringList _serverBlacklistedFiles; // The blacklist from the capabilities
  248. QStringList _leadingAndTrailingSpacesFilesAllowed;
  249. bool _ignoreHiddenFiles = false;
  250. std::function<bool(const QString &)> _shouldDiscoverLocaly;
  251. void startJob(ProcessDirectoryJob *);
  252. void setSelectiveSyncBlackList(const QStringList &list);
  253. void setSelectiveSyncWhiteList(const QStringList &list);
  254. // output
  255. QByteArray _dataFingerprint;
  256. bool _anotherSyncNeeded = false;
  257. QHash<QString, long long> _filesNeedingScheduledSync;
  258. QVector<QString> _filesUnscheduleSync;
  259. QStringList _listExclusiveFiles;
  260. signals:
  261. void fatalError(const QString &errorString, const OCC::ErrorCategory errorCategory);
  262. void itemDiscovered(const OCC::SyncFileItemPtr &item);
  263. void finished();
  264. // A new folder was discovered and was not synced because of the confirmation feature
  265. void newBigFolder(const QString &folder, bool isExternal);
  266. /** For excluded items that don't show up in itemDiscovered()
  267. *
  268. * The path is relative to the sync folder, similar to item->_file
  269. */
  270. void silentlyExcluded(const QString &folderPath);
  271. void addErrorToGui(const SyncFileItem::Status status, const QString &errorMessage, const QString &subject, const OCC::ErrorCategory category);
  272. };
  273. /// Implementation of DiscoveryPhase::adjustRenamedPath
  274. QString adjustRenamedPath(const QMap<QString, QString> &renamedItems, const QString &original);
  275. }