diff --git a/src/ui/directoryserviceswidget.cpp b/src/ui/directoryserviceswidget.cpp index 1ac645101..48212c115 100644 --- a/src/ui/directoryserviceswidget.cpp +++ b/src/ui/directoryserviceswidget.cpp @@ -1,756 +1,756 @@ /* directoryserviceswidget.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klarävdalens Datakonsult AB Copyright (c) 2017 Bundesamnt für Sicherheit in der Informationstechnik Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "directoryserviceswidget.h" #include "ui_directoryserviceswidget.h" #include "kleo_ui_debug.h" #include #include #include #include #include #include #include #include #include #include using namespace Kleo; namespace { static QUrl defaultX509Service() { QUrl url; url.setScheme(QStringLiteral("ldap")); url.setHost(i18nc("default server name, keep it a valid domain name, ie. no spaces", "server")); return url; } static QUrl defaultOpenPGPService() { QUrl url; if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < "2.1.16") { url.setScheme(QStringLiteral("hkp")); url.setHost(QStringLiteral("keys.gnupg.net")); } else { url.setScheme(QStringLiteral("hkps")); url.setHost(QStringLiteral("hkps.pool.sks-keyservers.net")); } return url; } static bool is_ldap_scheme(const QUrl &url) { const QString scheme = url.scheme(); return QString::compare(scheme, QStringLiteral("ldap"), Qt::CaseInsensitive) == 0 || QString::compare(scheme, QStringLiteral("ldaps"), Qt::CaseInsensitive) == 0; } static const struct { const char label[6]; unsigned short port; DirectoryServicesWidget::Scheme base; } protocols[] = { { I18N_NOOP("hkp"), 11371, DirectoryServicesWidget::HKP }, { I18N_NOOP("http"), 80, DirectoryServicesWidget::HTTP }, { I18N_NOOP("https"), 443, DirectoryServicesWidget::HTTP }, { I18N_NOOP("ftp"), 21, DirectoryServicesWidget::FTP }, { I18N_NOOP("ftps"), 990, DirectoryServicesWidget::FTP }, { I18N_NOOP("ldap"), 389, DirectoryServicesWidget::LDAP }, { I18N_NOOP("ldaps"), 636, DirectoryServicesWidget::LDAP }, }; static const unsigned int numProtocols = sizeof protocols / sizeof * protocols; static unsigned short default_port(const QString &scheme) { for (unsigned int i = 0; i < numProtocols; ++i) if (QString::compare(scheme, QLatin1String(protocols[i].label), Qt::CaseInsensitive) == 0) { return protocols[i].port; } return 0; } static QString display_scheme(const QUrl &url) { if (url.scheme().isEmpty()) { return QStringLiteral("hkp"); } else { return url.scheme(); } } static QString display_host(const QUrl &url) { // work around "subkeys.pgp.net" being interpreted as a path, not host if (url.host().isEmpty()) { return url.path(); } else { return url.host(); } } static unsigned short display_port(const QUrl &url) { if (url.port() > 0) { return url.port(); } else { return default_port(display_scheme(url)); } } static QRect calculate_geometry(const QRect &cell, const QSize &sizeHint) { const int height = qMax(cell.height(), sizeHint.height()); return QRect(cell.left(), cell.top() - (height - cell.height()) / 2, cell.width(), height); } /* The Model contains a bit historic cruft because in the past it was * thought to be a good idea to combine openPGP and X509 in a single * table although while you can have multiple X509 Keyservers there can * only be one OpenPGP Keyserver. So the OpenPGP Keyserver is now a * single lineedit. */ class Model : public QAbstractTableModel { Q_OBJECT public: explicit Model(QObject *parent = nullptr) : QAbstractTableModel(parent), m_items(), m_x509ReadOnly(false), m_schemes(DirectoryServicesWidget::LDAP) { } void setX509ReadOnly(bool ro) { if (ro == m_x509ReadOnly) { return; } m_x509ReadOnly = ro; for (int row = 0, end = rowCount(); row != end; ++row) { Q_EMIT dataChanged(index(row, 0), index(row, NumColumns)); } } QModelIndex addX509Service(const QUrl &url, bool force = false) { const auto it = force ? m_items.end() : findExistingUrl(url); unsigned int row; if (it != m_items.end()) { // existing item: row = it - m_items.begin(); Q_EMIT dataChanged(index(row, 0), index(row, NumColumns)); } else { // append new item row = m_items.size(); beginInsertRows(QModelIndex(), row, row); m_items.push_back(url); endInsertRows(); } return index(row, firstEditableColumn(row)); } unsigned int numServices() const { return m_items.size(); } QUrl service(unsigned int row) const { return row < m_items.size() ? m_items[row] : QUrl(); } enum Columns { Host, Port, BaseDN, UserName, Password, NumColumns }; QModelIndex duplicateRow(unsigned int row) { if (row >= m_items.size()) { return QModelIndex(); } beginInsertRows(QModelIndex(), row + 1, row + 1); m_items.insert(m_items.begin() + row + 1, m_items[row]); endInsertRows(); return index(row + 1, 0); } void deleteRow(unsigned int row) { if (row >= m_items.size()) { return; } beginRemoveRows(QModelIndex(), row, row); m_items.erase(m_items.begin() + row); endInsertRows(); } void clear() { if (m_items.empty()) { return; } beginRemoveRows(QModelIndex(), 0, m_items.size() - 1); m_items.clear(); endRemoveRows(); } int columnCount(const QModelIndex & = QModelIndex()) const override { return NumColumns; } int rowCount(const QModelIndex & = QModelIndex()) const override { return m_items.size(); } QVariant data(const QModelIndex &idx, int role) const override; QVariant headerData(int section, Qt::Orientation o, int role) const override; Qt::ItemFlags flags(const QModelIndex &idx) const override; bool setData(const QModelIndex &idx, const QVariant &value, int role) override; private: bool doSetData(unsigned int row, unsigned int column, const QVariant &value, int role); static QString toolTipForColumn(int column); bool isLdapRow(unsigned int row) const; int firstEditableColumn(unsigned int) const { return Host; } private: std::vector m_items; bool m_x509ReadOnly : 1; DirectoryServicesWidget::Schemes m_schemes; private: std::vector::iterator findExistingUrl(const QUrl &url) { return std::find_if(m_items.begin(), m_items.end(), [&url](const QUrl &item) { const QUrl &lhs = url; const QUrl &rhs = item; return QString::compare(display_scheme(lhs), display_scheme(rhs), Qt::CaseInsensitive) == 0 && QString::compare(display_host(lhs), display_host(rhs), Qt::CaseInsensitive) == 0 && lhs.port() == rhs.port() && lhs.userName() == rhs.userName() // ... ignore password... && (!is_ldap_scheme(lhs) || lhs.query() == rhs.query()); }); } }; class Delegate : public QItemDelegate { Q_OBJECT public: explicit Delegate(QObject *parent = nullptr) : QItemDelegate(parent), m_schemes(DirectoryServicesWidget::LDAP) { } void setAllowedSchemes(const DirectoryServicesWidget::Schemes schemes) { m_schemes = schemes; } DirectoryServicesWidget::Schemes allowedSchemes() const { return m_schemes; } QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &idx) const override { switch (idx.column()) { case Model::Port: return createPortWidget(parent); } return QItemDelegate::createEditor(parent, option, idx); } void setEditorData(QWidget *editor, const QModelIndex &idx) const override { switch (idx.column()) { case Model::Port: setPortEditorData(qobject_cast(editor), idx.data(Qt::EditRole).toInt()); break; default: QItemDelegate::setEditorData(editor, idx); break; } } void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &idx) const override { switch (idx.column()) { case Model::Port: setPortModelData(qobject_cast(editor), model, idx); break; default: QItemDelegate::setModelData(editor, model, idx); break; } } void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override { if (index.column() == Model::Port) { editor->setGeometry(calculate_geometry(option.rect, editor->sizeHint())); } else { QItemDelegate::updateEditorGeometry(editor, option, index); } } private: QWidget *createPortWidget(QWidget *parent) const { QSpinBox *sb = new QSpinBox(parent); sb->setRange(1, USHRT_MAX); // valid port numbers return sb; } void setPortEditorData(QSpinBox *sb, unsigned short port) const { Q_ASSERT(sb); sb->setValue(port); } void setPortModelData(const QSpinBox *sb, QAbstractItemModel *model, const QModelIndex &idx) const { Q_ASSERT(sb); Q_ASSERT(model); model->setData(idx, sb->value()); } private: DirectoryServicesWidget::Schemes m_schemes; }; } class DirectoryServicesWidget::Private { friend class ::Kleo::DirectoryServicesWidget; DirectoryServicesWidget *const q; public: explicit Private(DirectoryServicesWidget *qq) : q(qq), protocols(AllProtocols), readOnlyProtocols(NoProtocol), model(), delegate(), ui(q) { ui.treeView->setModel(&model); ui.treeView->setItemDelegate(&delegate); ui.pgpKeyserver->setPlaceholderText(defaultOpenPGPService().toString()); connect(&model, &QAbstractItemModel::dataChanged, q, &DirectoryServicesWidget::changed); connect(&model, &QAbstractItemModel::rowsInserted, q, &DirectoryServicesWidget::changed); connect(&model, &QAbstractItemModel::rowsRemoved, q, &DirectoryServicesWidget::changed); connect(ui.treeView->selectionModel(), &QItemSelectionModel::selectionChanged, q, [this]() { slotSelectionChanged(); }); connect(ui.pgpKeyserver, &QLineEdit::textChanged, q, &DirectoryServicesWidget::changed); slotShowUserAndPasswordToggled(false); } private: void edit(const QModelIndex &index) { if (index.isValid()) { ui.treeView->clearSelection(); ui.treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select | QItemSelectionModel::Rows); ui.treeView->edit(index); } } void slotNewX509Clicked() { edit(model.addX509Service(defaultX509Service(), true)); } void slotDeleteClicked() { model.deleteRow(selectedRow()); } void slotSelectionChanged() { enableDisableActions(); } void slotShowUserAndPasswordToggled(bool on) { QHeaderView *const hv = ui.treeView->header(); Q_ASSERT(hv); hv->setSectionHidden(Model::UserName, !on); hv->setSectionHidden(Model::Password, !on); } int selectedRow() const { const QModelIndexList mil = ui.treeView->selectionModel()->selectedRows(); return mil.empty() ? -1 : mil.front().row(); } int currentRow() const { const QModelIndex idx = ui.treeView->selectionModel()->currentIndex(); return idx.isValid() ? idx.row() : -1; } void enableDisableActions() { const bool x509 = (protocols & X509Protocol) && !(readOnlyProtocols & X509Protocol); const bool pgp = (protocols & OpenPGPProtocol) && !(readOnlyProtocols & OpenPGPProtocol); ui.newTB->setEnabled(x509); ui.pgpKeyserver->setEnabled(pgp); const int row = selectedRow(); ui.deleteTB->setEnabled(row >= 0 && !(readOnlyProtocols & X509Protocol)); } private: Protocols protocols; Protocols readOnlyProtocols; Model model; Delegate delegate; struct UI : Ui_DirectoryServicesWidget { explicit UI(DirectoryServicesWidget *q) : Ui_DirectoryServicesWidget() { setupUi(q); } } ui; }; DirectoryServicesWidget::DirectoryServicesWidget(QWidget *p, Qt::WindowFlags f) : QWidget(p, f), d(new Private(this)) { } DirectoryServicesWidget::~DirectoryServicesWidget() { delete d; } void DirectoryServicesWidget::setAllowedSchemes(Schemes schemes) { d->delegate.setAllowedSchemes(schemes); } DirectoryServicesWidget::Schemes DirectoryServicesWidget::allowedSchemes() const { return d->delegate.allowedSchemes(); } void DirectoryServicesWidget::setAllowedProtocols(Protocols protocols) { if (d->protocols == protocols) { return; } d->protocols = protocols; d->enableDisableActions(); } DirectoryServicesWidget::Protocols DirectoryServicesWidget::allowedProtocols() const { return d->protocols; } void DirectoryServicesWidget::setReadOnlyProtocols(Protocols protocols) { if (d->readOnlyProtocols == protocols) { return; } d->readOnlyProtocols = protocols; d->model.setX509ReadOnly(protocols & X509Protocol); d->enableDisableActions(); } DirectoryServicesWidget::Protocols DirectoryServicesWidget::readOnlyProtocols() const { return d->readOnlyProtocols; } void DirectoryServicesWidget::addOpenPGPServices(const QList &urls) { if (urls.size() > 1) { qCWarning(KLEO_UI_LOG) << "More then one PGP Server, Ignoring all others."; } if (urls.size()) { d->ui.pgpKeyserver->setText(urls[0].toString()); } } QList DirectoryServicesWidget::openPGPServices() const { QList result; const QString pgpStr = d->ui.pgpKeyserver->text(); - if (pgpStr.contains(QStringLiteral("://"))) { + if (pgpStr.contains(QLatin1String("://"))) { // Maybe validate here? Otoh maybe gnupg adds support for more schemes // then we know about in the future. result.push_back(QUrl::fromUserInput(pgpStr)); } else if (!pgpStr.isEmpty()) { result.push_back(QUrl::fromUserInput(QStringLiteral("hkp://") + pgpStr)); } return result; } void DirectoryServicesWidget::addX509Services(const QList &urls) { for (const QUrl &url : urls) { d->model.addX509Service(url); } } QList DirectoryServicesWidget::x509Services() const { QList result; for (unsigned int i = 0, end = d->model.numServices(); i != end; ++i) { result.push_back(d->model.service(i)); } return result; } void DirectoryServicesWidget::clear() { if (!d->model.numServices()) { return; } d->model.clear(); d->ui.pgpKeyserver->setText(QString()); Q_EMIT changed(); } // // Model // QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) if (role == Qt::ToolTipRole) { return toolTipForColumn(section); } else if (role == Qt::DisplayRole) switch (section) { case Host: return i18n("Server Name"); case Port: return i18n("Server Port"); case BaseDN: return i18n("Base DN"); case UserName: return i18n("User Name"); case Password: return i18n("Password"); default: return QVariant(); } else { return QVariant(); } else { return QAbstractTableModel::headerData(section, orientation, role); } } QVariant Model::data(const QModelIndex &index, int role) const { const unsigned int row = index.row(); if (index.isValid() && row < m_items.size()) switch (role) { case Qt::ToolTipRole: { const QString tt = toolTipForColumn(index.column()); if (!m_x509ReadOnly) { return tt; } else return tt.isEmpty() ? i18n("(read-only)") : i18nc("amended tooltip; %1: original tooltip", "%1 (read-only)", tt); } case Qt::DisplayRole: case Qt::EditRole: switch (index.column()) { case Host: return display_host(m_items[row]); case Port: return display_port(m_items[row]); case BaseDN: if (isLdapRow(row)) { return m_items[row].query(); } else { return QVariant(); } case UserName: return m_items[row].userName(); case Password: return m_items[row].password(); default: return QVariant(); } } return QVariant(); } bool Model::isLdapRow(unsigned int row) const { if (row >= m_items.size()) { return false; } return is_ldap_scheme(m_items[row]); } Qt::ItemFlags Model::flags(const QModelIndex &index) const { const unsigned int row = index.row(); Qt::ItemFlags flags = QAbstractTableModel::flags(index); if (m_x509ReadOnly) { flags &= ~Qt::ItemIsSelectable; } if (index.isValid() && row < m_items.size()) switch (index.column()) { case Host: case Port: if (m_x509ReadOnly) { return flags & ~(Qt::ItemIsEditable | Qt::ItemIsEnabled); } else { return flags | Qt::ItemIsEditable; } case BaseDN: if (isLdapRow(row) && !m_x509ReadOnly) { return flags | Qt::ItemIsEditable; } else { return flags & ~(Qt::ItemIsEditable | Qt::ItemIsEnabled); } case UserName: case Password: if (m_x509ReadOnly) { return flags & ~(Qt::ItemIsEditable | Qt::ItemIsEnabled); } else { return flags | Qt::ItemIsEditable; } } return flags; } bool Model::setData(const QModelIndex &idx, const QVariant &value, int role) { const unsigned int row = idx.row(); if (!idx.isValid() || row >= m_items.size()) { return false; } if (m_x509ReadOnly) { return false; } if (!doSetData(row, idx.column(), value, role)) { return false; } Q_EMIT dataChanged(idx, idx); return true; } bool Model::doSetData(unsigned int row, unsigned int column, const QVariant &value, int role) { if (role == Qt::EditRole) switch (column) { case Host: if (display_host(m_items[row]) != m_items[row].host()) { m_items[row].setScheme(display_scheme(m_items[row])); } m_items[row].setHost(value.toString()); return true; case Port: if (value.toUInt() == default_port(display_scheme(m_items[row]))) { m_items[row].setPort(-1); } else { m_items[row].setPort(value.toUInt()); } return true; case BaseDN: if (value.toString().isEmpty()) { m_items[row].setPath(QString()); m_items[row].setQuery(QString()); } else { m_items[row].setQuery(value.toString()); } return true; case UserName: m_items[row].setUserName(value.toString()); return true; case Password: m_items[row].setPassword(value.toString()); return true; } return false; } // static QString Model::toolTipForColumn(int column) { switch (column) { case Host: return i18n("Enter the name or IP address of the server " "hosting the directory service."); case Port: return i18n("(Optional, the default is fine in most cases) " "Pick the port number the directory service is " "listening on."); case BaseDN: return i18n("(Only for LDAP) " "Enter the base DN for this LDAP server to " "limit searches to only that subtree of the directory."); case UserName: return i18n("(Optional) " "Enter your user name here, if needed."); case Password: return i18n("(Optional, not recommended) " "Enter your password here, if needed. " "Note that the password will be saved in the clear " "in a config file in your home directory."); default: return QString(); } } #include "directoryserviceswidget.moc" #include "moc_directoryserviceswidget.cpp" diff --git a/src/ui/keyrequester.cpp b/src/ui/keyrequester.cpp index 0da6aa61b..2f595d02f 100644 --- a/src/ui/keyrequester.cpp +++ b/src/ui/keyrequester.cpp @@ -1,524 +1,524 @@ /* -*- c++ -*- keyrequester.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klar�vdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Libkleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. Based on kpgpui.cpp Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details This file is part of KPGP, the KDE PGP/GnuPG support library. KPGP is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "keyrequester.h" #include "keyselectiondialog.h" #include "libkleo/dn.h" // gpgme++ #include #include #include #include // KDE #include #include #include #include // Qt #include #include #include #include #include using namespace QGpgME; Kleo::KeyRequester::KeyRequester(unsigned int allowedKeys, bool multipleKeys, QWidget *parent) : QWidget(parent), mOpenPGPBackend(nullptr), mSMIMEBackend(nullptr), mMulti(multipleKeys), mKeyUsage(allowedKeys), mJobs(0), d(nullptr) { init(); } Kleo::KeyRequester::KeyRequester(QWidget *parent) : QWidget(parent), mOpenPGPBackend(nullptr), mSMIMEBackend(nullptr), mMulti(false), mKeyUsage(0), mJobs(0), d(nullptr) { init(); } void Kleo::KeyRequester::init() { QHBoxLayout *hlay = new QHBoxLayout(this); hlay->setContentsMargins(0, 0, 0, 0); // the label where the key id is to be displayed: mLabel = new QLabel(this); mLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); // the button to unset any key: mEraseButton = new QPushButton(this); mEraseButton->setAutoDefault(false); mEraseButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); mEraseButton->setIcon(QIcon::fromTheme(QApplication::isRightToLeft() ? QStringLiteral("edit-clear-locationbar-ltr") : QStringLiteral("edit-clear-locationbar-rtl"))); mEraseButton->setToolTip(i18n("Clear")); // the button to call the KeySelectionDialog: mDialogButton = new QPushButton(i18n("Change..."), this); mDialogButton->setAutoDefault(false); hlay->addWidget(mLabel, 1); hlay->addWidget(mEraseButton); hlay->addWidget(mDialogButton); connect(mEraseButton, &QPushButton::clicked, this, &SigningKeyRequester::slotEraseButtonClicked); connect(mDialogButton, &QPushButton::clicked, this, &SigningKeyRequester::slotDialogButtonClicked); setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed)); setAllowedKeys(mKeyUsage); } Kleo::KeyRequester::~KeyRequester() { } const std::vector &Kleo::KeyRequester::keys() const { return mKeys; } const GpgME::Key &Kleo::KeyRequester::key() const { static const GpgME::Key null = GpgME::Key::null; if (mKeys.empty()) { return null; } else { return mKeys.front(); } } void Kleo::KeyRequester::setKeys(const std::vector &keys) { mKeys.clear(); for (std::vector::const_iterator it = keys.begin(); it != keys.end(); ++it) if (!it->isNull()) { mKeys.push_back(*it); } updateKeys(); } void Kleo::KeyRequester::setKey(const GpgME::Key &key) { mKeys.clear(); if (!key.isNull()) { mKeys.push_back(key); } updateKeys(); } QString Kleo::KeyRequester::fingerprint() const { if (mKeys.empty()) { return QString(); } else { return QLatin1String(mKeys.front().primaryFingerprint()); } } QStringList Kleo::KeyRequester::fingerprints() const { QStringList result; for (std::vector::const_iterator it = mKeys.begin(); it != mKeys.end(); ++it) if (!it->isNull()) if (const char *fpr = it->primaryFingerprint()) { result.push_back(QLatin1String(fpr)); } return result; } void Kleo::KeyRequester::setFingerprint(const QString &fingerprint) { startKeyListJob(QStringList(fingerprint)); } void Kleo::KeyRequester::setFingerprints(const QStringList &fingerprints) { startKeyListJob(fingerprints); } void Kleo::KeyRequester::updateKeys() { if (mKeys.empty()) { mLabel->clear(); return; } if (mKeys.size() > 1) { setMultipleKeysEnabled(true); } QStringList labelTexts; QString toolTipText; for (std::vector::const_iterator it = mKeys.begin(); it != mKeys.end(); ++it) { if (it->isNull()) { continue; } const QString fpr = QLatin1String(it->primaryFingerprint()); labelTexts.push_back(fpr.right(8)); toolTipText += fpr.right(8) + QLatin1String(": "); if (const char *uid = it->userID(0).id()) if (it->protocol() == GpgME::OpenPGP) { toolTipText += QString::fromUtf8(uid); } else { toolTipText += Kleo::DN(uid).prettyDN(); } else { toolTipText += xi18n("unknown"); } toolTipText += QLatin1Char('\n'); } - mLabel->setText(labelTexts.join(QStringLiteral(", "))); + mLabel->setText(labelTexts.join(QLatin1String(", "))); mLabel->setToolTip(toolTipText); } #ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ #define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ static void showKeyListError(QWidget *parent, const GpgME::Error &err) { Q_ASSERT(err); const QString msg = i18n("

An error occurred while fetching " "the keys from the backend:

" "

%1

", QString::fromLocal8Bit(err.asString())); KMessageBox::error(parent, msg, i18n("Key Listing Failed")); } #endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ void Kleo::KeyRequester::startKeyListJob(const QStringList &fingerprints) { if (!mSMIMEBackend && !mOpenPGPBackend) { return; } mTmpKeys.clear(); mJobs = 0; unsigned int count = 0; for (QStringList::const_iterator it = fingerprints.begin(); it != fingerprints.end(); ++it) if (!(*it).trimmed().isEmpty()) { ++count; } if (!count) { // don't fall into the trap that an empty pattern means // "return all keys" :) setKey(GpgME::Key::null); return; } if (mOpenPGPBackend) { KeyListJob *job = mOpenPGPBackend->keyListJob(false); // local, no sigs if (!job) { KMessageBox::error(this, i18n("The OpenPGP backend does not support listing keys. " "Check your installation."), i18n("Key Listing Failed")); } else { connect(job, &KeyListJob::result, this, &SigningKeyRequester::slotKeyListResult); connect(job, &KeyListJob::nextKey, this, &SigningKeyRequester::slotNextKey); const GpgME::Error err = job->start(fingerprints, mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && !(mKeyUsage & Kleo::KeySelectionDialog::PublicKeys)); if (err) { showKeyListError(this, err); } else { ++mJobs; } } } if (mSMIMEBackend) { KeyListJob *job = mSMIMEBackend->keyListJob(false); // local, no sigs if (!job) { KMessageBox::error(this, i18n("The S/MIME backend does not support listing keys. " "Check your installation."), i18n("Key Listing Failed")); } else { connect(job, &KeyListJob::result, this, &SigningKeyRequester::slotKeyListResult); connect(job, &KeyListJob::nextKey, this, &SigningKeyRequester::slotNextKey); const GpgME::Error err = job->start(fingerprints, mKeyUsage & Kleo::KeySelectionDialog::SecretKeys && !(mKeyUsage & Kleo::KeySelectionDialog::PublicKeys)); if (err) { showKeyListError(this, err); } else { ++mJobs; } } } if (mJobs > 0) { mEraseButton->setEnabled(false); mDialogButton->setEnabled(false); } } void Kleo::KeyRequester::slotNextKey(const GpgME::Key &key) { if (!key.isNull()) { mTmpKeys.push_back(key); } } void Kleo::KeyRequester::slotKeyListResult(const GpgME::KeyListResult &res) { if (res.error()) { showKeyListError(this, res.error()); } if (--mJobs <= 0) { mEraseButton->setEnabled(true); mDialogButton->setEnabled(true); setKeys(mTmpKeys); mTmpKeys.clear(); } } void Kleo::KeyRequester::slotDialogButtonClicked() { KeySelectionDialog *dlg = mKeys.empty() ? new KeySelectionDialog(mDialogCaption, mDialogMessage, mInitialQuery, mKeyUsage, mMulti, false, this) : new KeySelectionDialog(mDialogCaption, mDialogCaption, mKeys, mKeyUsage, mMulti, false, this); if (dlg->exec() == QDialog::Accepted) { if (mMulti) { setKeys(dlg->selectedKeys()); } else { setKey(dlg->selectedKey()); } Q_EMIT changed(); } delete dlg; } void Kleo::KeyRequester::slotEraseButtonClicked() { if (!mKeys.empty()) { Q_EMIT changed(); } mKeys.clear(); updateKeys(); } void Kleo::KeyRequester::setDialogCaption(const QString &caption) { mDialogCaption = caption; } void Kleo::KeyRequester::setDialogMessage(const QString &msg) { mDialogMessage = msg; } bool Kleo::KeyRequester::isMultipleKeysEnabled() const { return mMulti; } void Kleo::KeyRequester::setMultipleKeysEnabled(bool multi) { if (multi == mMulti) { return; } if (!multi && !mKeys.empty()) { mKeys.erase(mKeys.begin() + 1, mKeys.end()); } mMulti = multi; updateKeys(); } unsigned int Kleo::KeyRequester::allowedKeys() const { return mKeyUsage; } void Kleo::KeyRequester::setAllowedKeys(unsigned int keyUsage) { mKeyUsage = keyUsage; mOpenPGPBackend = nullptr; mSMIMEBackend = nullptr; if (mKeyUsage & KeySelectionDialog::OpenPGPKeys) { mOpenPGPBackend = openpgp(); } if (mKeyUsage & KeySelectionDialog::SMIMEKeys) { mSMIMEBackend = smime(); } if (mOpenPGPBackend && !mSMIMEBackend) { mDialogCaption = i18n("OpenPGP Key Selection"); mDialogMessage = i18n("Please select an OpenPGP key to use."); } else if (!mOpenPGPBackend && mSMIMEBackend) { mDialogCaption = i18n("S/MIME Key Selection"); mDialogMessage = i18n("Please select an S/MIME key to use."); } else { mDialogCaption = i18n("Key Selection"); mDialogMessage = i18n("Please select an (OpenPGP or S/MIME) key to use."); } } QPushButton *Kleo::KeyRequester::dialogButton() { return mDialogButton; } QPushButton *Kleo::KeyRequester::eraseButton() { return mEraseButton; } static inline unsigned int foo(bool openpgp, bool smime, bool trusted, bool valid) { unsigned int result = 0; if (openpgp) { result |= Kleo::KeySelectionDialog::OpenPGPKeys; } if (smime) { result |= Kleo::KeySelectionDialog::SMIMEKeys; } if (trusted) { result |= Kleo::KeySelectionDialog::TrustedKeys; } if (valid) { result |= Kleo::KeySelectionDialog::ValidKeys; } return result; } static inline unsigned int encryptionKeyUsage(bool openpgp, bool smime, bool trusted, bool valid) { return foo(openpgp, smime, trusted, valid) | Kleo::KeySelectionDialog::EncryptionKeys | Kleo::KeySelectionDialog::PublicKeys; } static inline unsigned int signingKeyUsage(bool openpgp, bool smime, bool trusted, bool valid) { return foo(openpgp, smime, trusted, valid) | Kleo::KeySelectionDialog::SigningKeys | Kleo::KeySelectionDialog::SecretKeys; } Kleo::EncryptionKeyRequester::EncryptionKeyRequester(bool multi, unsigned int proto, QWidget *parent, bool onlyTrusted, bool onlyValid) : KeyRequester(encryptionKeyUsage(proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid), multi, parent), d(nullptr) { } Kleo::EncryptionKeyRequester::EncryptionKeyRequester(QWidget *parent) : KeyRequester(0, false, parent), d(nullptr) { } Kleo::EncryptionKeyRequester::~EncryptionKeyRequester() {} void Kleo::EncryptionKeyRequester::setAllowedKeys(unsigned int proto, bool onlyTrusted, bool onlyValid) { KeyRequester::setAllowedKeys(encryptionKeyUsage(proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid)); } Kleo::SigningKeyRequester::SigningKeyRequester(bool multi, unsigned int proto, QWidget *parent, bool onlyTrusted, bool onlyValid) : KeyRequester(signingKeyUsage(proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid), multi, parent), d(nullptr) { } Kleo::SigningKeyRequester::SigningKeyRequester(QWidget *parent) : KeyRequester(0, false, parent), d(nullptr) { } Kleo::SigningKeyRequester::~SigningKeyRequester() {} void Kleo::SigningKeyRequester::setAllowedKeys(unsigned int proto, bool onlyTrusted, bool onlyValid) { KeyRequester::setAllowedKeys(signingKeyUsage(proto & OpenPGP, proto & SMIME, onlyTrusted, onlyValid)); } void Kleo::KeyRequester::virtual_hook(int, void *) {} void Kleo::EncryptionKeyRequester::virtual_hook(int id, void *data) { KeyRequester::virtual_hook(id, data); } void Kleo::SigningKeyRequester::virtual_hook(int id, void *data) { KeyRequester::virtual_hook(id, data); } diff --git a/src/ui/keyselectiondialog.cpp b/src/ui/keyselectiondialog.cpp index 73ee6feee..d9d740881 100644 --- a/src/ui/keyselectiondialog.cpp +++ b/src/ui/keyselectiondialog.cpp @@ -1,989 +1,989 @@ /* -*- c++ -*- keyselectiondialog.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klar�vdalens Datakonsult AB Based on kpgpui.cpp Copyright (C) 2001,2002 the KPGP authors See file libkdenetwork/AUTHORS.kpgp for details Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Libkleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "keyselectiondialog.h" #include "keylistview.h" #include "progressdialog.h" #include "libkleo/dn.h" #include "kleo_ui_debug.h" // gpgme++ #include #include #include #include // KDE #include #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static bool checkKeyUsage(const GpgME::Key &key, unsigned int keyUsage, QString *statusString = nullptr) { auto setStatusString = [statusString](const QString &status) { if (statusString) { *statusString = status; } }; if (keyUsage & Kleo::KeySelectionDialog::ValidKeys) { if (key.isInvalid()) { if (key.keyListMode() & GpgME::Validate) { qCDebug(KLEO_UI_LOG) << "key is invalid"; setStatusString(i18n("The key is not valid.")); return false; } else { qCDebug(KLEO_UI_LOG) << "key is invalid - ignoring"; } } if (key.isExpired()) { qCDebug(KLEO_UI_LOG) << "key is expired"; setStatusString(i18n("The key is expired.")); return false; } else if (key.isRevoked()) { qCDebug(KLEO_UI_LOG) << "key is revoked"; setStatusString(i18n("The key is revoked.")); return false; } else if (key.isDisabled()) { qCDebug(KLEO_UI_LOG) << "key is disabled"; setStatusString(i18n("The key is disabled.")); return false; } } if (keyUsage & Kleo::KeySelectionDialog::EncryptionKeys && !key.canEncrypt()) { qCDebug(KLEO_UI_LOG) << "key can't encrypt"; setStatusString(i18n("The key is not designated for encryption.")); return false; } if (keyUsage & Kleo::KeySelectionDialog::SigningKeys && !key.canSign()) { qCDebug(KLEO_UI_LOG) << "key can't sign"; setStatusString(i18n("The key is not designated for signing.")); return false; } if (keyUsage & Kleo::KeySelectionDialog::CertificationKeys && !key.canCertify()) { qCDebug(KLEO_UI_LOG) << "key can't certify"; setStatusString(i18n("The key is not designated for certifying.")); return false; } if (keyUsage & Kleo::KeySelectionDialog::AuthenticationKeys && !key.canAuthenticate()) { qCDebug(KLEO_UI_LOG) << "key can't authenticate"; setStatusString(i18n("The key is not designated for authentication.")); return false; } if (keyUsage & Kleo::KeySelectionDialog::SecretKeys && !(keyUsage & Kleo::KeySelectionDialog::PublicKeys) && !key.hasSecret()) { qCDebug(KLEO_UI_LOG) << "key isn't secret"; setStatusString(i18n("The key is not secret.")); return false; } if (keyUsage & Kleo::KeySelectionDialog::TrustedKeys && key.protocol() == GpgME::OpenPGP && // only check this for secret keys for now. // Seems validity isn't checked for secret keylistings... !key.hasSecret()) { std::vector uids = key.userIDs(); for (std::vector::const_iterator it = uids.begin(); it != uids.end(); ++it) if (!it->isRevoked() && it->validity() >= GpgME::UserID::Marginal) { return true; } qCDebug(KLEO_UI_LOG) << "key has no UIDs with validity >= Marginal"; setStatusString(i18n("The key is not trusted enough.")); return false; } // X.509 keys are always trusted, else they won't be the keybox. // PENDING(marc) check that this ^ is correct setStatusString(i18n("The key can be used.")); return true; } static bool checkKeyUsage(const std::vector &keys, unsigned int keyUsage) { for (std::vector::const_iterator it = keys.begin(); it != keys.end(); ++it) if (!checkKeyUsage(*it, keyUsage)) { return false; } return true; } static inline QString time_t2string(time_t t) { QDateTime dt; dt.setTime_t(t); return dt.toString(); } namespace { class ColumnStrategy : public Kleo::KeyListView::ColumnStrategy { public: ColumnStrategy(unsigned int keyUsage); QString title(int col) const override; int width(int col, const QFontMetrics &fm) const override; QString text(const GpgME::Key &key, int col) const override; QString toolTip(const GpgME::Key &key, int col) const override; QIcon icon(const GpgME::Key &key, int col) const override; private: const QIcon mKeyGoodPix, mKeyBadPix, mKeyUnknownPix, mKeyValidPix; const unsigned int mKeyUsage; }; static QString iconPath(const QString &name) { return QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("libkleopatra/pics/") + name + QStringLiteral(".png")); } ColumnStrategy::ColumnStrategy(unsigned int keyUsage) : Kleo::KeyListView::ColumnStrategy(), mKeyGoodPix(iconPath(QStringLiteral("key_ok"))), mKeyBadPix(iconPath(QStringLiteral("key_bad"))), mKeyUnknownPix(iconPath(QStringLiteral("key_unknown"))), mKeyValidPix(iconPath(QStringLiteral("key"))), mKeyUsage(keyUsage) { if (keyUsage == 0) qCWarning(KLEO_UI_LOG) << "KeySelectionDialog: keyUsage == 0. You want to use AllKeys instead."; } QString ColumnStrategy::title(int col) const { switch (col) { case 0: return i18n("Key ID"); case 1: return i18n("User ID"); default: return QString(); } } int ColumnStrategy::width(int col, const QFontMetrics &fm) const { if (col == 0) { static const char hexchars[] = "0123456789ABCDEF"; int maxWidth = 0; for (unsigned int i = 0; i < 16; ++i) { maxWidth = qMax(fm.boundingRect(QLatin1Char(hexchars[i])).width(), maxWidth); } return 8 * maxWidth + 2 * 16 /* KIconLoader::SizeSmall */; } return Kleo::KeyListView::ColumnStrategy::width(col, fm); } QString ColumnStrategy::text(const GpgME::Key &key, int col) const { switch (col) { case 0: { if (key.shortKeyID()) { return QString::fromUtf8(key.shortKeyID()); } else { return xi18n("unknown"); } } case 1: { const char *uid = key.userID(0).id(); if (key.protocol() == GpgME::OpenPGP) { return uid && *uid ? QString::fromUtf8(uid) : QString(); } else { // CMS return Kleo::DN(uid).prettyDN(); } } default: return QString(); } } QString ColumnStrategy::toolTip(const GpgME::Key &key, int) const { const char *uid = key.userID(0).id(); const char *fpr = key.primaryFingerprint(); const char *issuer = key.issuerName(); const GpgME::Subkey subkey = key.subkey(0); const QString expiry = subkey.neverExpires() ? i18n("never") : time_t2string(subkey.expirationTime()); const QString creation = time_t2string(subkey.creationTime()); QString keyStatusString; if (!checkKeyUsage(key, mKeyUsage, &keyStatusString)) { // Show the status in bold if there is a problem keyStatusString = QLatin1String("") % keyStatusString % QLatin1String(""); } QString html = QStringLiteral("

"); if (key.protocol() == GpgME::OpenPGP) { html += i18n("OpenPGP key for %1", uid ? QString::fromUtf8(uid) : i18n("unknown")); } else { html += i18n("S/MIME key for %1", uid ? Kleo::DN(uid).prettyDN() : i18n("unknown")); } html += QStringLiteral("

"); const auto addRow = [&html](const QString &name, const QString &value) { html += QStringLiteral("").arg(name, value); }; addRow(i18nc("Key creation date", "Created"), creation); addRow(i18nc("Key Expiration date", "Expiry"), expiry); addRow(i18nc("Key fingerprint", "Fingerprint"), fpr ? QString::fromLatin1(fpr) : i18n("unknown")); if (key.protocol() != GpgME::OpenPGP) { addRow(i18nc("Key issuer", "Issuer"), issuer ? Kleo::DN(issuer).prettyDN() : i18n("unknown")); } addRow(i18nc("Key status", "Status"), keyStatusString); html += QStringLiteral("
%1: %2
"); return html; } QIcon ColumnStrategy::icon(const GpgME::Key &key, int col) const { if (col != 0) { return QIcon(); } // this key did not undergo a validating keylisting yet: if (!(key.keyListMode() & GpgME::Validate)) { return mKeyUnknownPix; } if (!checkKeyUsage(key, mKeyUsage)) { return mKeyBadPix; } if (key.protocol() == GpgME::CMS) { return mKeyGoodPix; } switch (key.userID(0).validity()) { default: case GpgME::UserID::Unknown: case GpgME::UserID::Undefined: return mKeyUnknownPix; case GpgME::UserID::Never: return mKeyValidPix; case GpgME::UserID::Marginal: case GpgME::UserID::Full: case GpgME::UserID::Ultimate: return mKeyGoodPix; } } } static const int sCheckSelectionDelay = 250; Kleo::KeySelectionDialog::KeySelectionDialog(const QString &title, const QString &text, const std::vector &selectedKeys, unsigned int keyUsage, bool extendedSelection, bool rememberChoice, QWidget *parent, bool modal) : QDialog(parent), mOpenPGPBackend(nullptr), mSMIMEBackend(nullptr), mRememberCB(nullptr), mSelectedKeys(selectedKeys), mKeyUsage(keyUsage), mCurrentContextMenuItem(nullptr) { setWindowTitle(title); setModal(modal); init(rememberChoice, extendedSelection, text, QString()); } Kleo::KeySelectionDialog::KeySelectionDialog(const QString &title, const QString &text, const QString &initialQuery, const std::vector &selectedKeys, unsigned int keyUsage, bool extendedSelection, bool rememberChoice, QWidget *parent, bool modal) : QDialog(parent), mOpenPGPBackend(nullptr), mSMIMEBackend(nullptr), mRememberCB(nullptr), mSelectedKeys(selectedKeys), mKeyUsage(keyUsage), mSearchText(initialQuery), mInitialQuery(initialQuery), mCurrentContextMenuItem(nullptr) { setWindowTitle(title); setModal(modal); init(rememberChoice, extendedSelection, text, initialQuery); } Kleo::KeySelectionDialog::KeySelectionDialog(const QString &title, const QString &text, const QString &initialQuery, unsigned int keyUsage, bool extendedSelection, bool rememberChoice, QWidget *parent, bool modal) : QDialog(parent), mOpenPGPBackend(nullptr), mSMIMEBackend(nullptr), mRememberCB(nullptr), mKeyUsage(keyUsage), mSearchText(initialQuery), mInitialQuery(initialQuery), mCurrentContextMenuItem(nullptr) { setWindowTitle(title); setModal(modal); init(rememberChoice, extendedSelection, text, initialQuery); } void Kleo::KeySelectionDialog::init(bool rememberChoice, bool extendedSelection, const QString &text, const QString &initialQuery) { QVBoxLayout *mainLayout = new QVBoxLayout(this); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); mOkButton = buttonBox->button(QDialogButtonBox::Ok); mOkButton->setDefault(true); mOkButton->setShortcut(Qt::CTRL | Qt::Key_Return); QPushButton *user1Button = new QPushButton; buttonBox->addButton(user1Button, QDialogButtonBox::ActionRole); QPushButton *user2Button = new QPushButton; buttonBox->addButton(user2Button, QDialogButtonBox::ActionRole); if (mKeyUsage & OpenPGPKeys) { mOpenPGPBackend = QGpgME::openpgp(); } if (mKeyUsage & SMIMEKeys) { mSMIMEBackend = QGpgME::smime(); } mCheckSelectionTimer = new QTimer(this); mStartSearchTimer = new QTimer(this); QFrame *page = new QFrame(this); mainLayout->addWidget(page); mainLayout->addWidget(buttonBox); mTopLayout = new QVBoxLayout(page); mTopLayout->setContentsMargins(0, 0, 0, 0); if (!text.isEmpty()) { QLabel *textLabel = new QLabel(text, page); textLabel->setWordWrap(true); // Setting the size policy is necessary as a workaround for https://issues.kolab.org/issue4429 // and http://bugreports.qt.nokia.com/browse/QTBUG-8740 textLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); connect(textLabel, &QLabel::linkActivated, this, &KeySelectionDialog::slotStartCertificateManager); mTopLayout->addWidget(textLabel); } QPushButton *const searchExternalPB = new QPushButton(i18n("Search for &External Certificates"), page); mTopLayout->addWidget(searchExternalPB, 0, Qt::AlignLeft); connect(searchExternalPB, &QAbstractButton::clicked, this, &KeySelectionDialog::slotStartSearchForExternalCertificates); if (initialQuery.isEmpty()) { searchExternalPB->hide(); } QHBoxLayout *hlay = new QHBoxLayout(); mTopLayout->addLayout(hlay); QLineEdit *le = new QLineEdit(page); le->setClearButtonEnabled(true); le->setText(initialQuery); QLabel *lbSearchFor = new QLabel(i18n("&Search for:"), page); lbSearchFor->setBuddy(le); hlay->addWidget(lbSearchFor); hlay->addWidget(le, 1); le->setFocus(); connect(le, &QLineEdit::textChanged, this, static_cast(&KeySelectionDialog::slotSearch)); connect(mStartSearchTimer, &QTimer::timeout, this, &KeySelectionDialog::slotFilter); mKeyListView = new KeyListView(new ColumnStrategy(mKeyUsage), nullptr, page); mKeyListView->setObjectName(QStringLiteral("mKeyListView")); mKeyListView->header()->stretchLastSection(); mKeyListView->setRootIsDecorated(true); mKeyListView->setSortingEnabled(true); mKeyListView->header()->setSortIndicatorShown(true); mKeyListView->header()->setSortIndicator(1, Qt::AscendingOrder); // sort by User ID if (extendedSelection) { mKeyListView->setSelectionMode(QAbstractItemView::ExtendedSelection); } mTopLayout->addWidget(mKeyListView, 10); if (rememberChoice) { mRememberCB = new QCheckBox(i18n("&Remember choice"), page); mTopLayout->addWidget(mRememberCB); mRememberCB->setWhatsThis( i18n("

If you check this box your choice will " "be stored and you will not be asked again." "

")); } connect(mCheckSelectionTimer, &QTimer::timeout, this, static_cast(&KeySelectionDialog::slotCheckSelection)); connectSignals(); connect(mKeyListView, &Kleo::KeyListView::doubleClicked, this, &KeySelectionDialog::slotTryOk); connect(mKeyListView, &KeyListView::contextMenu, this, &KeySelectionDialog::slotRMB); user1Button->setText(i18n("&Reread Keys")); user2Button->setText(i18n("&Start Certificate Manager")); connect(user1Button, &QPushButton::clicked, this, &KeySelectionDialog::slotRereadKeys); connect(user2Button, &QPushButton::clicked, this, [this]() { slotStartCertificateManager(); }); connect(mOkButton, &QPushButton::clicked, this, &KeySelectionDialog::slotOk); connect(buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &KeySelectionDialog::slotCancel); slotRereadKeys(); mTopLayout->activate(); if (qApp) { QSize dialogSize(sizeHint()); KWindowSystem::setIcons(winId(), qApp->windowIcon().pixmap(32, 32), qApp->windowIcon().pixmap(16, 16)); KConfigGroup dialogConfig(KSharedConfig::openConfig(), "Key Selection Dialog"); dialogSize = dialogConfig.readEntry("Dialog size", dialogSize); const QByteArray headerState = dialogConfig.readEntry("header", QByteArray()); if (!headerState.isEmpty()) { mKeyListView->header()->restoreState(headerState); } resize(dialogSize); } } Kleo::KeySelectionDialog::~KeySelectionDialog() { disconnectSignals(); KConfigGroup dialogConfig(KSharedConfig::openConfig(), "Key Selection Dialog"); dialogConfig.writeEntry("Dialog size", size()); dialogConfig.writeEntry("header", mKeyListView->header()->saveState()); dialogConfig.sync(); } void Kleo::KeySelectionDialog::connectSignals() { if (mKeyListView->isMultiSelection()) connect(mKeyListView, &QTreeWidget::itemSelectionChanged, this, &KeySelectionDialog::slotSelectionChanged); else connect(mKeyListView, static_cast(&KeyListView::selectionChanged), this, static_cast(&KeySelectionDialog::slotCheckSelection)); } void Kleo::KeySelectionDialog::disconnectSignals() { if (mKeyListView->isMultiSelection()) disconnect(mKeyListView, &QTreeWidget::itemSelectionChanged, this, &KeySelectionDialog::slotSelectionChanged); else disconnect(mKeyListView, static_cast(&KeyListView::selectionChanged), this, static_cast(&KeySelectionDialog::slotCheckSelection)); } const GpgME::Key &Kleo::KeySelectionDialog::selectedKey() const { static const GpgME::Key null = GpgME::Key::null; if (mKeyListView->isMultiSelection() || !mKeyListView->selectedItem()) { return null; } return mKeyListView->selectedItem()->key(); } QString Kleo::KeySelectionDialog::fingerprint() const { return QLatin1String(selectedKey().primaryFingerprint()); } QStringList Kleo::KeySelectionDialog::fingerprints() const { QStringList result; for (std::vector::const_iterator it = mSelectedKeys.begin(); it != mSelectedKeys.end(); ++it) if (const char *fpr = it->primaryFingerprint()) { result.push_back(QLatin1String(fpr)); } return result; } QStringList Kleo::KeySelectionDialog::pgpKeyFingerprints() const { QStringList result; for (std::vector::const_iterator it = mSelectedKeys.begin(); it != mSelectedKeys.end(); ++it) if (it->protocol() == GpgME::OpenPGP) if (const char *fpr = it->primaryFingerprint()) { result.push_back(QLatin1String(fpr)); } return result; } QStringList Kleo::KeySelectionDialog::smimeFingerprints() const { QStringList result; for (std::vector::const_iterator it = mSelectedKeys.begin(); it != mSelectedKeys.end(); ++it) if (it->protocol() == GpgME::CMS) if (const char *fpr = it->primaryFingerprint()) { result.push_back(QLatin1String(fpr)); } return result; } void Kleo::KeySelectionDialog::slotRereadKeys() { mKeyListView->clear(); mListJobCount = 0; mTruncated = 0; mSavedOffsetY = mKeyListView->verticalScrollBar()->value(); disconnectSignals(); mKeyListView->setEnabled(false); // FIXME: save current selection if (mOpenPGPBackend) { startKeyListJobForBackend(mOpenPGPBackend, std::vector(), false /*non-validating*/); } if (mSMIMEBackend) { startKeyListJobForBackend(mSMIMEBackend, std::vector(), false /*non-validating*/); } if (mListJobCount == 0) { mKeyListView->setEnabled(true); KMessageBox::information(this, i18n("No backends found for listing keys. " "Check your installation."), i18n("Key Listing Failed")); connectSignals(); } } void Kleo::KeySelectionDialog::slotStartCertificateManager(const QString &query) { QStringList args; if (!query.isEmpty()) { args << QStringLiteral("--search") << query; } if (!QProcess::startDetached(QStringLiteral("kleopatra"), args)) KMessageBox::error(this, i18n("Could not start certificate manager; " "please check your installation."), i18n("Certificate Manager Error")); else { qCDebug(KLEO_UI_LOG) << "\nslotStartCertManager(): certificate manager started."; } } #ifndef __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ #define __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ static void showKeyListError(QWidget *parent, const GpgME::Error &err) { Q_ASSERT(err); const QString msg = i18n("

An error occurred while fetching " "the keys from the backend:

" "

%1

", QString::fromLocal8Bit(err.asString())); KMessageBox::error(parent, msg, i18n("Key Listing Failed")); } #endif // __KLEO_UI_SHOW_KEY_LIST_ERROR_H__ namespace { struct ExtractFingerprint { QString operator()(const GpgME::Key &key) { return QLatin1String(key.primaryFingerprint()); } }; } void Kleo::KeySelectionDialog::startKeyListJobForBackend(const QGpgME::Protocol *backend, const std::vector &keys, bool validate) { Q_ASSERT(backend); QGpgME::KeyListJob *job = backend->keyListJob(false, false, validate); // local, w/o sigs, validation as givem if (!job) { return; } connect(job, &QGpgME::KeyListJob::result, this, &KeySelectionDialog::slotKeyListResult); if (validate) connect(job, &QGpgME::KeyListJob::nextKey, mKeyListView, &KeyListView::slotRefreshKey); else connect(job, &QGpgME::KeyListJob::nextKey, mKeyListView, &KeyListView::slotAddKey); QStringList fprs; std::transform(keys.begin(), keys.end(), std::back_inserter(fprs), ExtractFingerprint()); const GpgME::Error err = job->start(fprs, mKeyUsage & SecretKeys && !(mKeyUsage & PublicKeys)); if (err) { return showKeyListError(this, err); } #ifndef LIBKLEO_NO_PROGRESSDIALOG // FIXME: create a MultiProgressDialog: (void)new ProgressDialog(job, validate ? i18n("Checking selected keys...") : i18n("Fetching keys..."), this); #endif ++mListJobCount; } static void selectKeys(Kleo::KeyListView *klv, const std::vector &selectedKeys) { klv->clearSelection(); if (selectedKeys.empty()) { return; } for (std::vector::const_iterator it = selectedKeys.begin(); it != selectedKeys.end(); ++it) if (Kleo::KeyListViewItem *item = klv->itemByFingerprint(it->primaryFingerprint())) { item->setSelected(true); } } void Kleo::KeySelectionDialog::slotKeyListResult(const GpgME::KeyListResult &res) { if (res.error()) { showKeyListError(this, res.error()); } else if (res.isTruncated()) { ++mTruncated; } if (--mListJobCount > 0) { return; // not yet finished... } if (mTruncated > 0) KMessageBox::information(this, i18np("One backend returned truncated output.

" "Not all available keys are shown

", "%1 backends returned truncated output.

" "Not all available keys are shown

", mTruncated), i18n("Key List Result")); mKeyListView->flushKeys(); mKeyListView->setEnabled(true); mListJobCount = mTruncated = 0; mKeysToCheck.clear(); selectKeys(mKeyListView, mSelectedKeys); slotFilter(); connectSignals(); slotSelectionChanged(); // restore the saved position of the contents mKeyListView->verticalScrollBar()->setValue(mSavedOffsetY); mSavedOffsetY = 0; } void Kleo::KeySelectionDialog::slotSelectionChanged() { qCDebug(KLEO_UI_LOG) << "KeySelectionDialog::slotSelectionChanged()"; // (re)start the check selection timer. Checking the selection is delayed // because else drag-selection doesn't work very good (checking key trust // is slow). mCheckSelectionTimer->start(sCheckSelectionDelay); } namespace { struct AlreadyChecked { bool operator()(const GpgME::Key &key) const { return key.keyListMode() & GpgME::Validate; } }; } void Kleo::KeySelectionDialog::slotCheckSelection(KeyListViewItem *item) { qCDebug(KLEO_UI_LOG) << "KeySelectionDialog::slotCheckSelection()"; mCheckSelectionTimer->stop(); mSelectedKeys.clear(); if (!mKeyListView->isMultiSelection()) { if (item) { mSelectedKeys.push_back(item->key()); } } for (KeyListViewItem *it = mKeyListView->firstChild(); it; it = it->nextSibling()) if (it->isSelected()) { mSelectedKeys.push_back(it->key()); } mKeysToCheck.clear(); std::remove_copy_if(mSelectedKeys.begin(), mSelectedKeys.end(), std::back_inserter(mKeysToCheck), AlreadyChecked()); if (mKeysToCheck.empty()) { mOkButton->setEnabled(!mSelectedKeys.empty() && checkKeyUsage(mSelectedKeys, mKeyUsage)); return; } // performed all fast checks - now for validating key listing: startValidatingKeyListing(); } void Kleo::KeySelectionDialog::startValidatingKeyListing() { if (mKeysToCheck.empty()) { return; } mListJobCount = 0; mTruncated = 0; mSavedOffsetY = mKeyListView->verticalScrollBar()->value(); disconnectSignals(); mKeyListView->setEnabled(false); std::vector smime, openpgp; for (std::vector::const_iterator it = mKeysToCheck.begin(); it != mKeysToCheck.end(); ++it) if (it->protocol() == GpgME::OpenPGP) { openpgp.push_back(*it); } else { smime.push_back(*it); } if (!openpgp.empty()) { Q_ASSERT(mOpenPGPBackend); startKeyListJobForBackend(mOpenPGPBackend, openpgp, true /*validate*/); } if (!smime.empty()) { Q_ASSERT(mSMIMEBackend); startKeyListJobForBackend(mSMIMEBackend, smime, true /*validate*/); } Q_ASSERT(mListJobCount > 0); } bool Kleo::KeySelectionDialog::rememberSelection() const { return mRememberCB && mRememberCB->isChecked(); } void Kleo::KeySelectionDialog::slotRMB(Kleo::KeyListViewItem *item, const QPoint &p) { if (!item) { return; } mCurrentContextMenuItem = item; QMenu menu; menu.addAction(i18n("Recheck Key"), this, &KeySelectionDialog::slotRecheckKey); menu.exec(p); } void Kleo::KeySelectionDialog::slotRecheckKey() { if (!mCurrentContextMenuItem || mCurrentContextMenuItem->key().isNull()) { return; } mKeysToCheck.clear(); mKeysToCheck.push_back(mCurrentContextMenuItem->key()); } void Kleo::KeySelectionDialog::slotTryOk() { if (!mSelectedKeys.empty() && checkKeyUsage(mSelectedKeys, mKeyUsage)) { slotOk(); } } void Kleo::KeySelectionDialog::slotOk() { if (mCheckSelectionTimer->isActive()) { slotCheckSelection(); } #if 0 //Laurent I don't understand why we returns here. // button could be disabled again after checking the selected key1 if (!mSelectedKeys.empty() && checkKeyUsage(mSelectedKeys, mKeyUsage)) { return; } #endif mStartSearchTimer->stop(); accept(); } void Kleo::KeySelectionDialog::slotCancel() { mCheckSelectionTimer->stop(); mStartSearchTimer->stop(); reject(); } void Kleo::KeySelectionDialog::slotSearch(const QString &text) { mSearchText = text.trimmed().toUpper(); slotSearch(); } void Kleo::KeySelectionDialog::slotSearch() { mStartSearchTimer->setSingleShot(true); mStartSearchTimer->start(sCheckSelectionDelay); } void Kleo::KeySelectionDialog::slotFilter() { if (mSearchText.isEmpty()) { showAllItems(); return; } // OK, so we need to filter: QRegExp keyIdRegExp(QLatin1String("(?:0x)?[A-F0-9]{1,8}"), Qt::CaseInsensitive); if (keyIdRegExp.exactMatch(mSearchText)) { - if (mSearchText.startsWith(QStringLiteral("0X"))) + if (mSearchText.startsWith(QLatin1String("0X"))) // search for keyID only: { filterByKeyID(mSearchText.mid(2)); } else // search for UID and keyID: { filterByKeyIDOrUID(mSearchText); } } else { // search in UID: filterByUID(mSearchText); } } void Kleo::KeySelectionDialog::filterByKeyID(const QString &keyID) { Q_ASSERT(keyID.length() <= 8); Q_ASSERT(!keyID.isEmpty()); // regexp in slotFilter should prevent these if (keyID.isEmpty()) { showAllItems(); } else for (KeyListViewItem *item = mKeyListView->firstChild(); item; item = item->nextSibling()) { item->setHidden(!item->text(0).toUpper().startsWith(keyID)); } } static bool anyUIDMatches(const Kleo::KeyListViewItem *item, QRegExp &rx) { if (!item) { return false; } const std::vector uids = item->key().userIDs(); for (std::vector::const_iterator it = uids.begin(); it != uids.end(); ++it) if (it->id() && rx.indexIn(QString::fromUtf8(it->id())) >= 0) { return true; } return false; } void Kleo::KeySelectionDialog::filterByKeyIDOrUID(const QString &str) { Q_ASSERT(!str.isEmpty()); // match beginnings of words: QRegExp rx(QLatin1String("\\b") + QRegExp::escape(str), Qt::CaseInsensitive); for (KeyListViewItem *item = mKeyListView->firstChild(); item; item = item->nextSibling()) { item->setHidden(!item->text(0).toUpper().startsWith(str) && !anyUIDMatches(item, rx)); } } void Kleo::KeySelectionDialog::filterByUID(const QString &str) { Q_ASSERT(!str.isEmpty()); // match beginnings of words: QRegExp rx(QLatin1String("\\b") + QRegExp::escape(str), Qt::CaseInsensitive); for (KeyListViewItem *item = mKeyListView->firstChild(); item; item = item->nextSibling()) { item->setHidden(!anyUIDMatches(item, rx)); } } void Kleo::KeySelectionDialog::showAllItems() { for (KeyListViewItem *item = mKeyListView->firstChild(); item; item = item->nextSibling()) { item->setHidden(false); } } diff --git a/src/utils/classify.cpp b/src/utils/classify.cpp index b7638fae5..2634fad93 100644 --- a/src/utils/classify.cpp +++ b/src/utils/classify.cpp @@ -1,439 +1,439 @@ /* -*- mode: c++; c-basic-offset:4 -*- utils/classify.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "classify.h" #include "libkleo_debug.h" #include "kleo/checksumdefinition.h" #include #include #include #include #include #include #include #include #include #include #include #include using namespace Kleo::Class; namespace { const unsigned int ExamineContentHint = 0x8000; static const struct _classification { char extension[4]; unsigned int classification; } classifications[] = { // ordered by extension { "arl", CMS | Binary | CertificateRevocationList }, { "asc", OpenPGP | Ascii | OpaqueSignature | DetachedSignature | CipherText | AnyCertStoreType | ExamineContentHint }, { "cer", CMS | Binary | Certificate }, { "crl", CMS | Binary | CertificateRevocationList }, { "crt", CMS | Binary | Certificate }, { "der", CMS | Binary | Certificate | CertificateRevocationList }, { "gpg", OpenPGP | Binary | OpaqueSignature | CipherText | AnyCertStoreType | ExamineContentHint}, { "p10", CMS | Ascii | CertificateRequest }, { "p12", CMS | Binary | ExportedPSM }, { "p7c", CMS | Binary | Certificate }, { "p7m", CMS | AnyFormat | CipherText }, { "p7s", CMS | AnyFormat | AnySignature }, { "pem", CMS | Ascii | AnyType | ExamineContentHint }, { "pfx", CMS | Binary | Certificate }, { "pgp", OpenPGP | Binary | OpaqueSignature | CipherText | AnyCertStoreType | ExamineContentHint}, { "sig", OpenPGP | AnyFormat | DetachedSignature }, }; static const QMap gpgmeTypeMap { { GpgME::Data::PGPSigned, OpenPGP | OpaqueSignature }, /* PGPOther might be just an unencrypted unsigned pgp message. Decrypt * would yield the plaintext anyway so for us this is CipherText. */ { GpgME::Data::PGPOther, OpenPGP | CipherText }, { GpgME::Data::PGPKey, OpenPGP | Certificate }, { GpgME::Data::CMSSigned, CMS | AnySignature }, { GpgME::Data::CMSEncrypted, CMS | CipherText }, /* See PGPOther */ { GpgME::Data::CMSOther, CMS | CipherText }, { GpgME::Data::X509Cert, CMS | Certificate}, { GpgME::Data::PKCS12, CMS | Binary | ExportedPSM }, { GpgME::Data::PGPEncrypted, OpenPGP | CipherText }, { GpgME::Data::PGPSignature, OpenPGP | DetachedSignature }, }; static const unsigned int defaultClassification = NoClass; template