discoveryphase.h 10 KB

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