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 ClipboardManager and the per-platform clipboard hints that
6 : : * keep secrets out of clipboard histories.
7 : : */
8 : : #include "clipboardmanager.h"
9 : : #include "qtpasssettings.h"
10 : : #include "util.h"
11 : : #include <QApplication>
12 : : #include <QClipboard>
13 : : #include <QMimeData>
14 : : #include <utility>
15 : : #include <vector>
16 : :
17 : 242 : ClipboardManager::ClipboardManager(QObject *parent) : QObject(parent) {
18 : 242 : setAutoclearTimer();
19 : 242 : m_clearTimer.setSingleShot(true);
20 : 242 : connect(&m_clearTimer, &QTimer::timeout, this, &ClipboardManager::clear);
21 : 242 : connect(QApplication::instance(), &QApplication::aboutToQuit, this,
22 : 242 : &ClipboardManager::clear);
23 : 242 : }
24 : :
25 : 249 : void ClipboardManager::setAutoclearTimer() {
26 : 498 : m_clearTimer.setInterval(MS_PER_SECOND *
27 [ + + ]: 498 : QtPassSettings::getAutoclearSeconds());
28 : 249 : }
29 : :
30 : : namespace {
31 : : /**
32 : : * @brief Whether @p data carries a mark password managers (QtPass included)
33 : : * put on a secret, on any platform.
34 : : *
35 : : * Matched within each format name: Qt shows another program's clipboard
36 : : * format wrapped (application/x-qt-windows-mime;value="...", or a
37 : : * com.trolltech.anymime name on macOS), not under the bare name.
38 : : * @param data The clipboard's current content, or null.
39 : : * @return true for a marked secret.
40 : : */
41 : 10 : auto markedSecret(const QMimeData *data) -> bool {
42 [ + - ]: 10 : if (data == nullptr) {
43 : : return false;
44 : : }
45 : 10 : const QStringList formats = data->formats();
46 [ + + ]: 20 : for (const QString &format : formats) {
47 [ + - ]: 88 : for (const char *mark :
48 : : {"passwordManagerHint", "nspasteboard-concealed-type",
49 : : "nspasteboard.ConcealedType",
50 [ + + ]: 55 : "ExcludeClipboardContentFromMonitorProcessing"}) {
51 [ + + ]: 45 : if (format.contains(QLatin1String(mark), Qt::CaseInsensitive)) {
52 : : return true;
53 : : }
54 : : }
55 : : }
56 : : return false;
57 : : }
58 : :
59 : : /**
60 : : * @brief Whether one text holds the other, in time linear in both lengths.
61 : : *
62 : : * Knuth-Morris-Pratt: QString::contains() can take the product of the two
63 : : * lengths ("baaa..." in "aaaa..."), and both texts come from an entry.
64 : : * @param a One text.
65 : : * @param b The other text.
66 : : * @return True when the shorter one occurs in the longer one.
67 : : */
68 : 52 : auto oneHoldsTheOther(const QString &a, const QString &b) -> bool {
69 [ + + ]: 52 : const QString &longer = a.size() >= b.size() ? a : b;
70 [ + + ]: 52 : const QString &part = a.size() >= b.size() ? b : a;
71 : : const qsizetype m = part.size();
72 [ + - ]: 52 : if (m == 0) {
73 : : return true;
74 : : }
75 : : // fallback[i]: length of the longest proper prefix of part[0..i] that
76 : : // also ends there, so a mismatch resumes there instead of from the start.
77 : 52 : std::vector<qsizetype> fallback(static_cast<size_t>(m), 0);
78 [ + + ]: 200792 : for (qsizetype i = 1, k = 0; i < m; ++i) {
79 [ + + + - ]: 200741 : while (k > 0 && part.at(i) != part.at(k)) {
80 : 1 : k = fallback[static_cast<size_t>(k - 1)];
81 : : }
82 [ + + ]: 200740 : if (part.at(i) == part.at(k)) {
83 : 1 : ++k;
84 : : }
85 : 200740 : fallback[static_cast<size_t>(i)] = k;
86 : : }
87 [ + + ]: 400854 : for (qsizetype i = 0, k = 0; i < longer.size(); ++i) {
88 [ + + + + ]: 400853 : while (k > 0 && longer.at(i) != part.at(k)) {
89 : 40 : k = fallback[static_cast<size_t>(k - 1)];
90 : : }
91 [ + + ]: 400813 : if (longer.at(i) == part.at(k)) {
92 : 443 : ++k;
93 : : }
94 [ + + ]: 400813 : if (k == m) {
95 : : return true;
96 : : }
97 : : }
98 : : return false;
99 : : }
100 : : } // namespace
101 : :
102 : 34 : void ClipboardManager::copyIfAlways(const QString &text,
103 : : const QString &p_output) {
104 : 34 : const AppSettings s = QtPassSettings::load();
105 : : // Only "always copy" mode actually places text on the clipboard here; in
106 : : // on-demand mode the copy happens later from the field's copy button.
107 : : // Crucially, do not touch m_clippedText otherwise — it tracks what is
108 : : // currently on the clipboard so the autoclear timer knows what to clear.
109 : : // Overwriting it when merely showing another entry left a previously copied
110 : : // password on the clipboard past its autoclear window (#1607).
111 [ + + + + ]: 34 : if (s.clipBoardType == Enums::CLIPBOARD_ALWAYS && !p_output.isEmpty()) {
112 : 4 : copyText(text);
113 : : }
114 : 34 : }
115 : :
116 : 45 : void ClipboardManager::copyText(const QString &text) {
117 : 45 : const AppSettings s = QtPassSettings::load();
118 : 45 : QClipboard *clip = QApplication::clipboard();
119 : :
120 : : QClipboard::Mode mode = QClipboard::Clipboard;
121 [ - + - - : 45 : if (s.useSelection && clip->supportsSelection()) {
- ]
122 : : mode = QClipboard::Selection;
123 : : }
124 : :
125 : : // What was there before the first secret, to put back when autoclear
126 : : // runs (as pass -c does). Text only, as pass keeps it: rich content comes
127 : : // back as its plain text. Where Qt cannot read the clipboard without focus
128 : : // (some Wayland compositors, a copy from the tray), "before" reads as
129 : : // nothing and autoclear clears instead: the safe way round.
130 [ + + + + ]: 45 : if (s.useAutoclear && s.restoreClipboard) {
131 : 19 : saveWhatWasThere(clip, mode, text);
132 : : }
133 : 45 : forgetIfSaved(text);
134 : 45 : clip->setMimeData(buildClipboardMimeData(text), mode);
135 : :
136 : : // The text copied before may still be in the other buffer (a PIN copied to
137 : : // the clipboard, then selected, so also in the X11 selection): replacing
138 : : // it here would leave it there past autoclear.
139 [ + + - + ]: 14 : if (!m_clippedText.isEmpty() && m_clippedText != text &&
140 [ + + + - ]: 55 : !m_otherCopies.contains(m_clippedText) &&
141 [ + - + ]: 50 : (clip->text(QClipboard::Clipboard) == m_clippedText ||
142 [ + + + - : 50 : clip->text(QClipboard::Selection) == m_clippedText)) {
- ]
143 : 0 : m_otherCopies.append(m_clippedText);
144 : : }
145 : 45 : m_clippedText = text;
146 : 45 : emit statusMessage(tr("Copied to clipboard"));
147 [ + + ]: 45 : if (s.useAutoclear) {
148 : 25 : m_clearTimer.start();
149 : : }
150 : 45 : }
151 : :
152 : 19 : void ClipboardManager::saveWhatWasThere(QClipboard *clip, QClipboard::Mode mode,
153 : : const QString &text) {
154 : 19 : std::optional<QString> &previous =
155 : : mode == QClipboard::Selection ? m_previousSelection : m_previousClipboard;
156 : 19 : const QString now = clip->text(mode);
157 : : // Taken once per window, at the first copy, whatever is there: a text
158 : : // of ours, or the very text being copied, is saved as nothing (restoring
159 : : // it would leave a secret on the clipboard for good), and a later copy
160 : : // in the window cannot take a snapshot instead.
161 [ + + ]: 19 : if (!previous) {
162 : : // Another password manager's secret is marked as one; put back as
163 : : // plain text it would lose that mark (and go into clipboard history)
164 : : // and nobody would clear it again.
165 [ + + + - ]: 22 : const bool safe = now != text && now != m_clippedText &&
166 [ + + + + ]: 33 : !m_otherCopies.contains(now) &&
167 [ + + ]: 10 : !markedSecret(clip->mimeData(mode));
168 : 26 : previous = safe ? now : QString();
169 : : }
170 : 19 : }
171 : :
172 : 114 : void ClipboardManager::forgetIfSaved(const QString &text) {
173 : : // The saved text is copied as a secret now: putting it back would leave
174 : : // that secret on the clipboard. Emptied, not dropped, so no later copy
175 : : // takes a new snapshot in this window either; clear() then clears.
176 [ + + ]: 249 : for (std::optional<QString> *previous :
177 [ + + ]: 342 : {&m_previousClipboard, &m_previousSelection}) {
178 [ + + + + ]: 228 : if (*previous && **previous == text) {
179 : 4 : *previous = QString();
180 : : }
181 : : }
182 : 114 : }
183 : :
184 : 69 : void ClipboardManager::trackCopied(const QString &text) {
185 [ + - ]: 69 : if (text.isEmpty()) {
186 : : return;
187 : : }
188 : 69 : forgetIfSaved(text);
189 : : // Kept beside m_clippedText, not instead of it: replacing it would leave a
190 : : // password copied earlier on the clipboard past its autoclear (#1607).
191 [ + - + - ]: 69 : if (text != m_clippedText && !m_otherCopies.contains(text)) {
192 : : // A mouse selection reports itself on every change while it grows or
193 : : // shrinks (the X11 primary selection); only where it ends counts, or a
194 : : // passing "a" would stay tracked and autoclear could take someone
195 : : // else's "a" later.
196 : : // An earlier copy still on the clipboard proper (Ctrl+C) stays tracked.
197 : : // A step holds the one before or lies in it (a word double-clicked,
198 : : // then Ctrl+A); oneHoldsTheOther() asks that in linear time.
199 : : const QString &last =
200 [ + + ]: 69 : m_otherCopies.isEmpty() ? QString() : m_otherCopies.last();
201 [ + + + + : 63 : if (!last.isEmpty() && oneHoldsTheOther(text, last) &&
+ ]
202 [ + + + + : 159 : QApplication::clipboard()->text(QClipboard::Clipboard) != last &&
+ - + + ]
203 [ + + + + : 79 : QApplication::clipboard()->text(QClipboard::Selection) != last) {
- - ]
204 : 10 : m_otherCopies.last() = text;
205 : : } else {
206 : 59 : makeRoomInOtherCopies();
207 : : m_otherCopies.append(text);
208 : : }
209 : : }
210 : : // Not pushed back: a selection reports itself on every change, and a drag
211 : : // too, so restarting here gave a password copied earlier a new full
212 : : // period each time. The first deadline clears everything tracked.
213 [ + + + + : 127 : if (QtPassSettings::load().useAutoclear && !m_clearTimer.isActive()) {
+ + + ]
214 : 11 : m_clearTimer.start();
215 : : }
216 : : }
217 : :
218 : 59 : void ClipboardManager::makeRoomInOtherCopies() {
219 : : constexpr qsizetype kMaxOtherCopies = 16;
220 [ + + ]: 59 : if (m_otherCopies.size() >= kMaxOtherCopies) {
221 : : // Make room, but never by forgetting a text that is still on the
222 : : // clipboard or in the selection: it would then outlive autoclear.
223 : : // At most two are, so the oldest of the rest can always go.
224 : : const QString onClipboard =
225 : 25 : QApplication::clipboard()->text(QClipboard::Clipboard);
226 : : const QString inSelection =
227 : 25 : QApplication::clipboard()->text(QClipboard::Selection);
228 [ + - ]: 50 : for (qsizetype i = 0; i < m_otherCopies.size(); ++i) {
229 [ + + + - ]: 50 : if (m_otherCopies.at(i) != onClipboard &&
230 : : m_otherCopies.at(i) != inSelection) {
231 : 25 : m_otherCopies.removeAt(i);
232 : : break;
233 : : }
234 : : }
235 : : }
236 : 59 : }
237 : :
238 : 61 : void ClipboardManager::clear() {
239 : : // A clear before the deadline (a deselect) ends this window: a copy
240 : : // tracked after it starts a full one, not the rest of the old one.
241 : 61 : m_clearTimer.stop();
242 : : // Whatever happens below, the saved text is forgotten: it is the user's,
243 : : // and no later autoclear may put it back.
244 : : const std::optional<QString> previousClipboard =
245 : 61 : std::exchange(m_previousClipboard, std::nullopt);
246 : : const std::optional<QString> previousSelection =
247 : 61 : std::exchange(m_previousSelection, std::nullopt);
248 [ + + + + ]: 61 : if (m_clippedText.isEmpty() && m_otherCopies.isEmpty()) {
249 : : // Nothing of ours is out there. The old code compared the empty tracker
250 : : // with an empty selection, "cleared" that and said so on every deselect.
251 : : return;
252 : : }
253 : 66 : const auto ours = [this](const QString &text) {
254 [ + + + + ]: 66 : return !text.isEmpty() &&
255 [ + + + + ]: 33 : (text == m_clippedText || m_otherCopies.contains(text));
256 : 33 : };
257 : 33 : QClipboard *clipboard = QApplication::clipboard();
258 : 33 : const bool restore = QtPassSettings::load().restoreClipboard;
259 : 33 : bool cleared = false;
260 : 33 : bool restored = false;
261 : : // Ours still there: the text from before comes back if there was one and
262 : : // what is there is copyText()'s own copy, otherwise it is cleared. A copy
263 : : // from a shown field (trackCopied()) is cleared on purpose, not restored
264 : : // over: it can come long after copyText(), when "before" is stale, and the
265 : : // user chose that copy themselves. Something else copied meanwhile is left
266 : : // alone. The setting is read now: switched off during the window, the
267 : : // saved text was still held until here, and is dropped unused.
268 : 66 : const auto putBack = [&](QClipboard::Mode mode,
269 : : const std::optional<QString> &previous) {
270 : 66 : const QString now = clipboard->text(mode);
271 [ + + ]: 66 : if (!ours(now)) {
272 : : return;
273 : : }
274 [ + + + + : 23 : if (restore && previous && !previous->isEmpty() && now == m_clippedText) {
+ + + + ]
275 : 3 : clipboard->setText(*previous, mode);
276 : 3 : restored = true;
277 : 3 : return;
278 : : }
279 : 20 : clipboard->clear(mode);
280 [ - + ]: 20 : if (mode == QClipboard::Selection) {
281 : 0 : clipboard->setText(QString(""), QClipboard::Selection);
282 : : }
283 : 20 : cleared = true;
284 : 33 : };
285 : 33 : putBack(QClipboard::Selection, previousSelection);
286 : 33 : putBack(QClipboard::Clipboard, previousClipboard);
287 [ + + + ]: 66 : emit statusMessage(restored ? tr("Clipboard restored")
288 [ + + ]: 30 : : cleared ? tr("Clipboard cleared")
289 : : : tr("Clipboard not cleared"));
290 : 33 : m_clippedText.clear();
291 : 33 : m_otherCopies.clear();
292 : : }
293 : :
294 : 67 : auto buildClipboardMimeData(const QString &text) -> QMimeData * {
295 : 67 : auto *mimeData = new QMimeData();
296 : 67 : mimeData->setText(text);
297 : : // The KDE hint (what wl-copy --sensitive sets) keeps the secret out of
298 : : // Klipper, CopyQ and cliphist history, on the BSDs as well as on Linux.
299 : : #if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
300 : 134 : mimeData->setData("x-kde-passwordManagerHint", QByteArray("secret"));
301 : : #endif
302 : : #ifdef Q_OS_MAC
303 : : mimeData->setData("application/x-nspasteboard-concealed-type", QByteArray());
304 : : #endif
305 : : #ifdef Q_OS_WIN
306 : : mimeData->setData("ExcludeClipboardContentFromMonitorProcessing",
307 : : dwordBytes(1));
308 : : mimeData->setData("CanIncludeInClipboardHistory", dwordBytes(0));
309 : : mimeData->setData("CanUploadToCloudClipboard", dwordBytes(0));
310 : : #endif
311 : 67 : return mimeData;
312 : : }
|