13#include "ui_importkeydialog.h"
15#include <QApplication>
17#include <QElapsedTimer>
22#include <QPlainTextEdit>
24#include <QRegularExpression>
33auto lineBreak() ->
const QRegularExpression & {
34 static const QRegularExpression regex(QStringLiteral(
"\\r?\\n"));
44 ui->importButton->setEnabled(
false);
60 for (qsizetype i = 0; i < text.size(); ++i) {
61 switch (text.at(i).unicode()) {
63 if (i + 1 < text.size() && text.at(i + 1) == QLatin1Char(
'\n')) {
68 case QChar::LineSeparator:
69 case QChar::ParagraphSeparator:
92 return QCoreApplication::translate(
94 "%1 is not laid out like an ASCII-armored key: it has a line of "
95 "more than %2 characters or more than %3 lines.")
101 const QString fileName = QFileDialog::getOpenFileName(
102 this, tr(
"Import GPG key"), QString(),
103 tr(
"ASCII-armored GPG key") +
" (*.asc);;" + tr(
"All files") +
" (*)");
105 if (fileName.isEmpty()) {
111 constexpr qint64 kMaxKeyFileBytes = 16LL * 1024 * 1024;
117 const QString target = QFileInfo(fileName).canonicalFilePath();
120 tr(
"Could not open file: %1").arg(fileName));
126 const bool tooLarge = file.size() > kMaxKeyFileBytes;
127 const QByteArray bytes =
128 tooLarge ? QByteArray() : file.read(kMaxKeyFileBytes + 1);
130 if (tooLarge || bytes.size() > kMaxKeyFileBytes) {
132 this, tr(
"Import key"),
133 tr(
"%1 is larger than a key file can be.").arg(fileName));
140 if (!bytes.trimmed().startsWith(
"-----BEGIN PGP")) {
143 QMessageBox::warning(
144 this, tr(
"Import key"),
145 tr(
"%1 does not look like an ASCII-armored GPG key. Convert it with "
146 "<code>gpg --armor --export</code> first, or paste the armored "
147 "block via <b>From clipboard</b>.")
148 .arg(fileName.toHtmlEscaped()));
152 const QString text = QString::fromUtf8(bytes);
158 ui->inputTextEdit->setPlainText(text);
162 const QClipboard *clipboard = QApplication::clipboard();
163 const QString text = clipboard->text();
164 if (text.isEmpty()) {
174 ui->inputTextEdit->setPlainText(text);
178 const QString input =
ui->inputTextEdit->toPlainText().trimmed();
179 if (input.isEmpty()) {
189 const bool hasInput = !
ui->inputTextEdit->toPlainText().trimmed().isEmpty();
190 ui->importButton->setEnabled(hasInput);
205 if (!
runGpg({QStringLiteral(
"--no-options"), QStringLiteral(
"--batch"),
206 QStringLiteral(
"--with-colons"),
207 QStringLiteral(
"--import-options"), QStringLiteral(
"show-only"),
208 QStringLiteral(
"--import")},
209 input, &listing, &listErr, timer)) {
214 showError(tr(
"This text holds a private key. QtPass imports public keys "
215 "only, so nothing was imported. Import the public key: "
216 "gpg --armor --export writes it."));
220 showError(tr(
"gpg found no key in this text, so nothing was imported."));
224 showError(tr(
"This text holds %n keys. QtPass imports one key at a time "
225 "and names it, so you can check its fingerprint: nothing "
226 "was imported. Import each key on its own.",
233 if (!
runGpg({QStringLiteral(
"--no-options"), QStringLiteral(
"--status-fd"),
234 QStringLiteral(
"1"), QStringLiteral(
"--import"),
235 QStringLiteral(
"--batch"), QStringLiteral(
"--yes")},
236 input, &stdOut, &stdErr, timer)) {
241 if (keyId.isEmpty()) {
245 if (keyId.isEmpty()) {
246 showError(tr(
"Could not parse imported key id from GPG output."));
256 QString *stdOut, QString *stdErr,
257 const QElapsedTimer &timer) ->
bool {
258 const QString gpgExe =
m_gpgExe.isEmpty() ? QStringLiteral(
"gpg") :
m_gpgExe;
264 nullptr,
static_cast<int>(left));
266 if (result != 0 && timer.elapsed() >=
m_timeoutMs) {
268 showError(tr(
"gpg did not finish the import within %n second(s) and was "
269 "stopped. Part of the key may be in your keyring already: "
270 "check it with gpg --list-keys before you use it.",
275 showError(tr(
"GPG import failed:\n%1").arg(*stdErr));
283 const QStringList lines = listing.split(lineBreak(), Qt::SkipEmptyParts);
284 for (
const QString &line : lines) {
285 if (line.startsWith(QLatin1String(
"pub:"))) {
287 }
else if (line.startsWith(QLatin1String(
"sec:"))) {
297 const QStringList lines = output.split(lineBreak(), Qt::SkipEmptyParts);
307 static const QRegularExpression importOk(QStringLiteral(
308 R
"(^\[GNUPG:\] IMPORT_OK \d+ ([0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$)"));
311 static const QRegularExpression imported(
312 QStringLiteral(R
"(^\[GNUPG:\] IMPORTED ([0-9A-Fa-f]{16})(?: |$))"));
315 static const QRegularExpression humanImported(QStringLiteral(
316 R
"(^gpg: key ([0-9A-Fa-f]{40}|[0-9A-Fa-f]{16}):.*imported)"));
324 for (
const QString &line : lines) {
325 const QRegularExpressionMatch match = importOk.match(line);
326 if (match.hasMatch()) {
327 return match.captured(1);
330 for (
const QString &line : lines) {
331 const QRegularExpressionMatch match = imported.match(line);
332 if (match.hasMatch()) {
333 return match.captured(1);
336 for (
const QString &line : lines) {
337 const QRegularExpressionMatch match = humanImported.match(line);
338 if (match.hasMatch()) {
339 return match.captured(1);
352 QMessageBox::information(
this, tr(
"Import key"),
353 tr(
"Public key %1 imported. Check its fingerprint "
354 "with its owner before encrypting to it: "
355 "importing a key says nothing about who holds "
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
static constexpr qsizetype kMaxKeyLines
Most lines fitsTheEditor() lets through: a 16 MiB key file in armor's 64-character lines.
static auto fitsTheEditor(QStringView text) -> bool
Whether text is laid out as armor can be, so the input field can show it at a bounded cost.
~ImportKeyDialog() override
Destroys the dialog and its generated UI.
static auto parseGpgImportOutput(const QString &output) -> QString
Parse GPG import output to extract a key id or fingerprint.
void showError(const QString &message)
Shows message in a plain-text warning box (gpg's stderr quotes user IDs, which must not be read as ma...
auto importedKeyId() const -> QString
Get the imported key id on success.
static auto keysInBlock(const QString &listing) -> BlockKeys
Count the keys in the listing of gpg --with-colons --import-options show-only --import.
int m_timeoutMs
Most milliseconds gpg may take to import (kImportTimeoutMs).
QString m_importedKeyId
Key id or fingerprint of the last successful import; empty until then. Read back through importedKeyI...
ImportKeyDialog(QString gpgExe, QWidget *parent=nullptr, int timeoutMs=kImportTimeoutMs)
Construct an ImportKeyDialog.
void on_fileButton_clicked()
"From file" button: picks a file, reads it as a regular file of at most 16 MiB, requires the -----BEG...
auto runGpg(const QStringList &args, const QString &input, QString *stdOut, QString *stdErr, const QElapsedTimer &timer) -> bool
Runs gpg with args on input within what is left of m_timeoutMs since timer started.
QString m_gpgExe
Path of the gpg binary to run; empty means plain gpg on PATH.
void on_pasteButton_clicked()
"From clipboard" button: replaces the input field with the clipboard text, unless the clipboard is em...
void showSuccess(const QString &keyId)
Shows the "imported, now verify the fingerprint" information box.
QScopedPointer< Ui::ImportKeyDialog > ui
Generated form (importkeydialog.ui); owned.
auto importFromString(const QString &input) -> bool
Lists the keys in input first, with nothing written, and refuses a block that holds a private key or ...
void on_importButton_clicked()
"Import" button: runs importFromString() on the trimmed input and closes the dialog with accept() on ...
static constexpr qsizetype kMaxKeyLine
Longest line fitsTheEditor() lets through, in characters.
void on_inputTextEdit_textChanged()
Enables the Import button only while the input field holds non-blank text.
static auto openRegularFile(const QString &path, QFile &file) -> bool
Open path for reading as the regular file it is, not as what a link under that name points to: the ob...
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
static auto notLaidOutLikeAKey(const QString &what) -> QString
The message for text that fails ImportKeyDialog::fitsTheEditor().
Dialog that imports an ASCII-armored GPG public key from a file or the clipboard by running gpg --imp...
void warning(QWidget *parent, const QString &title, const QString &text)
Show a warning in plain text.
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
How many keys an armored block holds, by kind.
int publicKeys
Public keys: pub records.
int secretKeys
Keys with their secret part: sec records.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...