QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
qtpass.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2018 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "qtpass.h"
9#include "executor.h"
10#include "imitatepass.h"
11#include "qtpasssettings.h"
12#include "settingsconstants.h"
13#include "util.h"
14#include <QApplication>
15#include <QDialog>
16#include <QLabel>
17#include <QPixmap>
18#include <QVBoxLayout>
19
20#include "qtpasslogging.h"
21
22QtPass::QtPass(QObject *parent) : QObject(parent), m_clipboard(this) {
23 // Both implementations are wired up: the active one can change through the
24 // configuration dialog, and reconnecting on every switch is not worth it.
27}
28
29QtPass::~QtPass() = default;
30
34
36
37 QString version = QtPassSettings::getVersion();
38
39 // Config updates
40 if (version.isEmpty()) {
41 qCDebug(lcQtPass) << "assuming fresh install";
43 if (s.autoclearSeconds < 5)
44 s.autoclearSeconds = 10;
45 if (s.autoclearPanelSeconds < 5)
47 s.usePwgen = !s.pwgenExecutable.isEmpty();
48 s.passTemplate = QStringLiteral("login\nurl\nOTP");
50 // A fresh profile already has the new useOtp default, so record the
51 // migration as done. Without this, turning OTP off during the first session
52 // would be undone by the migration branch on the next launch.
55 // Nothing chosen yet: the first-run wizard may suggest the backend and
56 // Git from what it finds, until it is finished.
58 true);
59 } else {
61 bool changed = false;
62 if (s.passTemplate.isEmpty()) {
63 s.passTemplate = QStringLiteral("login\nurl\nOTP");
64 changed = true;
65 }
66 // `useOtp` used to gate the Unix-only pass-otp extension and now gates
67 // built-in TOTP, so an existing profile's stored false is stale rather than
68 // a preference. The new default of true never reaches these users: the
69 // fresh-install branch above already persisted the key, and the serializer
70 // writes it unconditionally. Enable it once, remembered by its own key so a
71 // deliberate opt-out is not overridden on the next launch.
74 .toBool()) {
75 s.useOtp = true;
78 changed = true;
79 }
80 if (changed) {
82 }
83 }
84
86}
87
101
102void QtPass::reportError(int exitCode, const QString &error) {
103 if (error.isEmpty()) {
104 return;
105 }
106 const QString colour =
107 exitCode == 0 ? QStringLiteral("darkgray") : QStringLiteral("red");
109 error, QStringLiteral("<span style=\"color: %1;\">").arg(colour),
110 QStringLiteral("</span><br />")));
111}
112
113void QtPass::processErrorExit(int exitCode, const QString &error) {
114 reportError(exitCode, error);
115 emit operationFinished();
116}
117
118void QtPass::processFinished(const QString &output, const QString &errout) {
119 // A silent command (git push with nothing to push, say) has nothing to
120 // show; re-setting the browser's HTML for it would only reset its scroll.
121 if (!output.isEmpty()) {
122 emit outputReady(formatOutput(output));
123 }
124 reportError(0, errout);
125 emit operationFinished();
126}
127
128void QtPass::passStoreChanged(const QString &output, const QString &errout) {
129 processFinished(output, errout);
130 doGitPush();
131}
132
133void QtPass::finishedInsert(const QString &output, const QString &errout) {
134 processFinished(output, errout);
135 doGitPush();
136 emit entryInserted();
137}
138
139void QtPass::onKeyGenerationComplete(const QString &output,
140 const QString &errout) {
141 // The KeygenDialog listens to the same signal and closes itself.
142 emit statusMessage(tr("GPG key pair generated successfully"), 10000);
143 processFinished(output, errout);
144}
145
146auto QtPass::formatOutput(QString output, const QString &prefix,
147 const QString &postfix, bool links) -> QString {
148 // White space is kept below, so a "\r\n" must be one line end, and a lone
149 // "\r" stays a space inside its line, as before: as a block of its own it
150 // would slip past the display cap, which counts "\n" only. So do U+2029
151 // and the frame marks, which Qt also starts a block at.
152 output.replace(QStringLiteral("\r\n"), QStringLiteral("\n"));
153 output = Util::withoutOtherBlockBreaks(output);
154 // Kept white space can hang Qt's layout on a run of 65536 spaces.
155 output = Util::boundSpaceRuns(output);
156 // Escapes and links only launchable http(s) URLs; anything else stays
157 // plain text (the text browser opens external links on click).
158 output = links ? Util::linkifyUrls(output) : output.toHtmlEscaped();
159 output.replace(QStringLiteral("\n"), "<br />");
160 // As stored: rich text otherwise shows, and Select All + Copy hand back,
161 // "a b" as "a b", drops indentation and turns a tab into a space (#210).
162 // Long lines still wrap.
163 return prefix + QStringLiteral("<span style=\"white-space: pre-wrap;\">") +
164 output + QStringLiteral("</span>") + postfix;
165}
166
169 return;
170 }
171 // After a re-encryption that did not finish: the push would publish the
172 // recipients change with entries still for the previous recipients.
173 if (Pass *pass = QtPassSettings::getPass();
174 pass != nullptr && pass->autoPushHeld()) {
175 emit statusMessage(tr("Not pushing automatically: the last "
176 "re-encryption did not finish. Re-encrypt again, "
177 "or push by hand."),
178 10000);
179 return;
180 }
181 emit pushRequested();
182}
183
184void QtPass::showTextAsQRCode(const QString &text) {
186 const QString qrExe = s.qrencodeExecutable.isEmpty()
187 ? QStringLiteral("/usr/bin/qrencode")
189 QProcess qrencode;
191 qrencode.start(qrExe, QStringList() << "-o-"
192 << "-tPNG");
193 // A missing or non-executable binary never "finishes": exitStatus() stays
194 // NormalExit and exitCode() 0, which used to fall through to an empty popup.
195 if (!qrencode.waitForStarted()) {
196 emit statusMessage(tr("Could not start qrencode: %1").arg(qrExe), 2000);
197 return;
198 }
199 qrencode.write(text.toUtf8());
200 qrencode.closeWriteChannel();
201 // A hung qrencode also leaves exitStatus()/exitCode() at their defaults.
202 if (!qrencode.waitForFinished()) {
203 qrencode.kill();
204 emit statusMessage(tr("qrencode did not finish in time"), 2000);
205 return;
206 }
207 QByteArray output(qrencode.readAllStandardOutput());
208
209 const bool crashed = qrencode.exitStatus() != QProcess::NormalExit;
210 // exitCode() is meaningless after a crash, so only consult it otherwise.
211 const bool failed = !crashed && qrencode.exitCode() != 0;
212 if (crashed || failed) {
213 QString error(qrencode.readAllStandardError());
214 if (error.trimmed().isEmpty()) {
215 error = crashed
216 ? tr("qrencode crashed")
217 : tr("qrencode exited with code %1").arg(qrencode.exitCode());
218 }
219 emit statusMessage(error, 2000);
220 } else {
221 QPixmap image;
222 image.loadFromData(output, "PNG");
224 m_qrPopup->exec();
225 }
226}
227
229 if (m_qrPopup) {
230 m_qrPopup->close();
231 }
232}
233
234QDialog *QtPass::createQRCodePopup(const QPixmap &image) {
235 auto *popup = new QDialog(nullptr, Qt::Popup | Qt::FramelessWindowHint);
236 popup->setAttribute(Qt::WA_DeleteOnClose);
237 auto *layout = new QVBoxLayout;
238 auto *popupLabel = new QLabel();
239 layout->addWidget(popupLabel);
240 popupLabel->setPixmap(image);
241 popupLabel->setScaledContents(true);
242 popupLabel->show();
243 popup->setLayout(layout);
244 popup->move(QCursor::pos());
245 return popup;
246}
static void detachFromTerminal(QProcess &process)
Make process start its child without a controlling terminal.
Definition executor.cpp:192
Abstract base class for password store operations.
Definition pass.h:77
void finishedInsert(const QString &out, const QString &err)
An Insert() succeeded: the entry is in the store and, with Git in use, committed.
void finishedGenerateGPGKeys(const QString &out, const QString &err)
GenerateGPGKeys() succeeded; the new key pair is in the keyring.
void finishedCopy(const QString &out, const QString &err)
A Copy() succeeded; the copy exists beside the original.
void finishedMove(const QString &out, const QString &err)
A Move() succeeded; the entry or folder is under its new name.
void finishedGitPull(const QString &out, const QString &err)
git pull succeeded; entries may have changed on disk.
void finishedGitPush(const QString &out, const QString &err)
git push succeeded.
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
void finishedGitInit(const QString &out, const QString &err)
git init in the store succeeded; the store is a repository now and the tree is re-read.
void finishedInit(const QString &out, const QString &err)
An Init() succeeded: the folder's .gpg-id holds the new recipient list.
void finishedRemove(const QString &out, const QString &err)
A Remove() succeeded; the entry or folder is gone from the store.
void operationFinished()
A backend operation is over, successfully or not; the interface can be enabled again.
void statusMessage(const QString &message, int timeout)
A short message for the status bar.
ClipboardManager m_clipboard
The clipboard handling for this application instance, exposed through clipboard(); parented to this o...
Definition qtpass.h:128
static auto formatOutput(QString output, const QString &prefix=QString(), const QString &postfix=QString(), bool links=true) -> QString
Turn a process' plain-text output into the HTML the text browser shows: http(s) URLs become links,...
Definition qtpass.cpp:146
void entryInserted()
An entry was written; the view of the current entry is stale.
void processFinished(const QString &output, const QString &errout)
Slot for Pass::finishedGitPull / finishedGitPush and the common tail of the other slots: emit the std...
Definition qtpass.cpp:118
void pushRequested()
The store changed and the settings ask for an automatic push.
void connectPassSignalHandlers(Pass *pass)
Connect the completion signals of one backend to the slots that turn them into output,...
Definition qtpass.cpp:88
void outputReady(const QString &html)
Formatted output (see formatOutput()) or an error rendered in colour, ready for the text browser.
void finishedInsert(const QString &output, const QString &errout)
Slot for Pass::finishedInsert: like passStoreChanged(), then emit entryInserted() so the window refre...
Definition qtpass.cpp:133
void reportError(int exitCode, const QString &error)
Show a process' stderr in colour through outputReady(): red for a failure, dark grey for the chatter ...
Definition qtpass.cpp:102
void onKeyGenerationComplete(const QString &output, const QString &errout)
Slot for Pass::finishedGenerateGPGKeys: a status message followed by processFinished()....
Definition qtpass.cpp:139
void passStoreChanged(const QString &output, const QString &errout)
Slot for the backend signals that change the store on disk (git init, remove, init,...
Definition qtpass.cpp:128
void init()
Resolve the password store and the executables and migrate the settings of an older version (fresh-in...
Definition qtpass.cpp:31
QtPass(QObject *parent=nullptr)
Construct the glue and connect it to both pass backends.
Definition qtpass.cpp:22
void closeQRCode()
Close the QR code popup showTextAsQRCode() has open, if any: the autoclear of the panel takes the cod...
Definition qtpass.cpp:228
void doGitPush()
Emit pushRequested() when the settings ask for automatic push.
Definition qtpass.cpp:167
static QDialog * createQRCodePopup(const QPixmap &image)
Create a frameless popup dialog, placed at the cursor, showing the given QR code. Split out of showTe...
Definition qtpass.cpp:234
~QtPass() override
Destroy the QtPass instance and clean up signal connections.
QPointer< QDialog > m_qrPopup
The QR code popup while showTextAsQRCode() has it open.
Definition qtpass.h:130
void processErrorExit(int exitCode, const QString &error)
Slot for Pass::processErrorExit: report the error in red and emit operationFinished().
Definition qtpass.cpp:113
void showTextAsQRCode(const QString &text)
Render text as a QR code with qrencode and show it in a popup at the cursor; failures are reported th...
Definition qtpass.cpp:184
static auto getInstance() -> QtPassSettings *
Get the singleton instance.
static void setPassStore(const QString &passStore)
Save password store path.
static auto getPass() -> Pass *
Get currently active pass backend instance.
static auto getPassStore(const QString &defaultValue=QVariant().toString()) -> QString
Get password store directory path.
static auto getVersion(const QString &defaultValue=QVariant().toString()) -> QString
Get saved application version.
static void initExecutables()
Initialize executable paths by auto-detecting them.
static auto load() -> AppSettings
Load all flat settings into an AppSettings value object.
static void setVersion(const QString &version)
Save application version.
static auto getRealPass() -> RealPass *
Get real pass backend instance.
static auto getImitatePass() -> ImitatePass *
Get imitate pass backend instance.
static void save(const AppSettings &settings)
Persist an AppSettings value object to the singleton store.
static auto isAutoPush(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether automatic push is enabled.
static const QString firstRunPending
Set on a fresh install until QtPass is first set up: the first-run wizard finished,...
static const QString otpMigratedToNative
Marker that the one-time useOtp migration has run.
static auto withoutOtherBlockBreaks(QString text) -> QString
text with every block break other than a line feed (isOtherBlockBreak()) shown as a space,...
Definition util.cpp:967
static auto findPasswordStore() -> QString
Locate the password store directory.
Definition util.cpp:81
static auto boundSpaceRuns(const QString &text) -> QString
text with every run of white space other than tabs and line feeds cut to kMaxSpaceRun characters,...
Definition util.cpp:1029
static auto linkifyUrls(const QString &text, bool *linked=nullptr) -> QString
Turn plain text into HTML with clickable links for safe web URLs.
Definition util.cpp:914
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
ImitatePass, the backend that does what pass does by running gpg and git itself.
QtPass: UI-neutral glue that turns backend completion signals into formatted output,...
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
Names of the keys QtPass stores its settings under.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
QString qrencodeExecutable
Path to the qrencode executable.
Definition appsettings.h:68
QString pwgenExecutable
Path to the pwgen executable.
Definition appsettings.h:67
bool useOtp
Enable native TOTP (OTP) support.
int autoclearPanelSeconds
Panel autoclear delay (seconds).
Definition appsettings.h:82
int autoclearSeconds
Clipboard autoclear delay (seconds).
Definition appsettings.h:80
QString passTemplate
Newline-separated template field names.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...