Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements EntryRecord: a JSON file of hashed entry paths, written
6 : : * under a lock file as the generation record is.
7 : : */
8 : : #include "entryrecord.h"
9 : : #include "gpgidgeneration.h"
10 : : #include "qtpasslogging.h"
11 : :
12 : : #include <QDir>
13 : : #include <QFileInfo>
14 : : #include <QJsonDocument>
15 : : #include <QJsonObject>
16 : : #include <QLockFile>
17 : : #include <QMutex>
18 : : #include <QSaveFile>
19 : : #include <QSet>
20 : :
21 : : #include <optional>
22 : :
23 : : namespace {
24 : :
25 : : constexpr int kRecordFormat = 1;
26 : : /// More entries than any store holds: past it a seed stops rather than
27 : : /// fill the record with a runaway tree.
28 : : constexpr int kMaxSeeded = 200000;
29 : : constexpr int kLockTimeoutMs = 2000;
30 : :
31 : : /**
32 : : * @brief The record: hashed entry paths and hashed store roots seeded.
33 : : */
34 : 532 : struct Record {
35 : : QJsonObject entries; ///< Path hash to 1.
36 : : QJsonObject stores; ///< Store root hash to 1.
37 : : };
38 : :
39 : : /**
40 : : * @brief Read the record.
41 : : * @return It, empty when there is none yet; nothing when it cannot be read.
42 : : */
43 : 267 : auto load() -> std::optional<Record> {
44 : 267 : const QString path = EntryRecord::recordFile();
45 [ + + + ]: 267 : if (!QFileInfo::exists(path)) {
46 : 16 : return Record{};
47 : : }
48 : 259 : QFile file(path);
49 [ + - + ]: 259 : if (!file.open(QIODevice::ReadOnly)) {
50 : 0 : return std::nullopt;
51 : : }
52 : 259 : QJsonParseError parse{};
53 : 259 : const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &parse);
54 [ + + + - : 517 : if (parse.error != QJsonParseError::NoError || !doc.isObject() ||
+ + - ]
55 [ + + + + : 517 : doc.object().value(QLatin1String("format")).toInt() != kRecordFormat) {
+ + + -
- ]
56 : 1 : return std::nullopt;
57 : : }
58 : 774 : return Record{doc.object().value(QLatin1String("entries")).toObject(),
59 : 516 : doc.object().value(QLatin1String("stores")).toObject()};
60 : 259 : }
61 : :
62 : : /**
63 : : * @brief Write the record, owner-only, replacing it whole.
64 : : * @param record What to write.
65 : : * @return Whether it was written.
66 : : */
67 : 254 : auto save(const Record &record) -> bool {
68 : 254 : QJsonObject root;
69 : 254 : root.insert(QLatin1String("format"), kRecordFormat);
70 : 254 : root.insert(QLatin1String("entries"), record.entries);
71 : 254 : root.insert(QLatin1String("stores"), record.stores);
72 : 254 : QSaveFile file(EntryRecord::recordFile());
73 [ + + - ]: 254 : if (!file.open(QIODevice::WriteOnly)) {
74 : : return false;
75 : : }
76 : 254 : file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
77 : 254 : const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Compact);
78 [ + + - + : 254 : return file.write(bytes) == bytes.size() && file.commit();
- + ]
79 : 254 : }
80 : :
81 : : /**
82 : : * @brief Add the `*.gpg` entries in @p dir and its folders to @p found, up
83 : : * to @p limit. A name starting with "." is left out before the walk
84 : : * goes into it (.git, say, which QDir does not count as hidden on
85 : : * Windows), and so are links and junctions, as the tree shows them.
86 : : * @param dir A folder.
87 : : * @param limit At most this many entries in all.
88 : : * @param found Receives the entries' absolute paths.
89 : : */
90 : 66 : void collectEntries(const QString &dir, int limit, QStringList &found) {
91 : 132 : const QFileInfoList children = QDir(dir).entryInfoList(
92 : 66 : QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
93 [ + + ]: 226 : for (const QFileInfo &child : children) {
94 [ - + ]: 160 : if (found.size() >= limit) {
95 : : return;
96 : : }
97 : : // A junction is no link to Qt on Windows, so it is named here too.
98 [ + + + + : 320 : if (child.fileName().startsWith(QLatin1Char('.')) || child.isSymLink() ||
+ - + - +
+ + - - ]
99 : 110 : child.isJunction()) {
100 : 50 : continue;
101 : : }
102 [ + + + ]: 110 : if (child.isDir()) {
103 : 34 : collectEntries(child.absoluteFilePath(), limit, found);
104 [ + + + + ]: 93 : } else if (child.fileName().endsWith(QLatin1String(".gpg"),
105 : : Qt::CaseInsensitive)) {
106 : 144 : found << child.absoluteFilePath();
107 : : }
108 : : }
109 : : }
110 : :
111 : : /**
112 : : * @brief The entries @p path stands for: itself, or every `*.gpg` below it
113 : : * when it is a folder (collectEntries()).
114 : : * @param path An entry or a folder.
115 : : * @param limit At most this many.
116 : : * @return Their absolute paths.
117 : : */
118 : 269 : auto entriesOf(const QString &path, int limit) -> QStringList {
119 : 269 : const QFileInfo info(path);
120 [ + - + ]: 269 : if (info.isSymLink()) {
121 : 0 : return {};
122 : : }
123 [ + + + ]: 269 : if (!info.isDir()) {
124 : 440 : return {info.absoluteFilePath()};
125 : : }
126 : 49 : QStringList found;
127 : 49 : collectEntries(path, limit, found);
128 : : return found;
129 : 489 : }
130 : :
131 : : /**
132 : : * @brief Run @p change on the record under its lock and save it.
133 : : * @param change Edits the record; returns whether anything changed.
134 : : */
135 : 256 : template <typename Change> void update(Change change) {
136 : 256 : const QString path = EntryRecord::recordFile();
137 : 768 : QDir().mkpath(QFileInfo(path).absolutePath());
138 : 512 : QLockFile lock(path + QStringLiteral(".lock"));
139 [ + + + ]: 256 : if (!lock.tryLock(kLockTimeoutMs)) {
140 : 4 : qCWarning(lcQtPass) << "Entry record busy, not updated:" << path;
141 : 2 : return;
142 : : }
143 : 254 : std::optional<Record> record = load();
144 [ - + ]: 254 : if (!record) {
145 : 0 : qCWarning(lcQtPass) << "Entry record unreadable, not updated:" << path;
146 : : return;
147 : : }
148 [ + + - + : 254 : if (change(*record) && !save(*record)) {
+ - + ]
149 : 0 : qCWarning(lcQtPass) << "Entry record not written:" << path;
150 : : }
151 : 256 : }
152 : :
153 : : } // namespace
154 : :
155 : 794 : auto EntryRecord::recordFile() -> QString {
156 : 2382 : return QFileInfo(GpgIdGeneration::recordFile()).absolutePath() +
157 : 1588 : QStringLiteral("/QtPass-entries.json");
158 : : }
159 : :
160 : 13 : auto EntryRecord::known(const QString &entryFile) -> bool {
161 : 13 : const QString path = recordFile();
162 : 26 : QLockFile lock(path + QStringLiteral(".lock"));
163 [ + + - ]: 13 : if (!lock.tryLock(kLockTimeoutMs)) {
164 : : return false;
165 : : }
166 : 13 : const std::optional<Record> record = load();
167 [ + + + + : 25 : return record && record->entries.contains(GpgIdGeneration::key(entryFile));
+ + - - ]
168 : 13 : }
169 : :
170 : 312 : void EntryRecord::remember(const QStringList &paths) {
171 : 312 : QStringList entries;
172 [ + + ]: 543 : for (const QString &path : paths) {
173 : 462 : entries << entriesOf(path, kMaxSeeded);
174 : : }
175 [ + + ]: 312 : if (entries.isEmpty()) {
176 : : return;
177 : : }
178 : 216 : update([&entries](Record &record) {
179 [ + + ]: 445 : for (const QString &entry : std::as_const(entries)) {
180 : 458 : record.entries.insert(GpgIdGeneration::key(entry), 1);
181 : : }
182 : 216 : return true;
183 : : });
184 : : }
185 : :
186 : 49 : void EntryRecord::seedStore(const QString &storeRoot) {
187 [ + - + + : 98 : if (storeRoot.isEmpty() || !QFileInfo(storeRoot).isDir()) {
- + - ]
188 : 9 : return;
189 : : }
190 : 49 : const QString store = GpgIdGeneration::key(QDir::cleanPath(storeRoot));
191 : : // One try per store and run, the first open: a seed that could not be
192 : : // written (the record busy or unreadable) is not retried at a later
193 : : // init(), which may come after a pull and would take what the pull
194 : : // brought as saved. The store then stays unseeded, and an edit asks.
195 : : {
196 : 56 : static QMutex mutex;
197 : 56 : static QSet<QString> tried;
198 : : const QMutexLocker locker(&mutex);
199 [ + + ]: 49 : if (tried.contains(store)) {
200 : : return;
201 : : }
202 : 40 : tried.insert(store);
203 : 49 : }
204 : 40 : update([&storeRoot, &store](Record &record) {
205 [ + - ]: 38 : if (record.stores.contains(store)) {
206 : : return false;
207 : : }
208 : : // A store root may itself be a link (a synced folder): walked where it
209 : : // points; links below it are still left out.
210 : 38 : const QString root = QFileInfo(storeRoot).canonicalFilePath();
211 [ + + + + ]: 139 : for (const QString &entry : entriesOf(root, kMaxSeeded)) {
212 : 126 : record.entries.insert(GpgIdGeneration::key(entry), 1);
213 : : }
214 : 38 : record.stores.insert(store, 1);
215 : : return true;
216 : : });
217 : : }
|