discoveryphase.h 10 KB

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