formatting.cpp 31.4 KB
Newer Older
Justus Winter's avatar
Justus Winter committed
1
2
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; -*-

3
4
5
    utils/formatting.cpp

    This file is part of Kleopatra, the KDE keymanager
6
    SPDX-FileCopyrightText: 2007 Klarälvdalens Datakonsult AB
7

8
    SPDX-License-Identifier: GPL-2.0-or-later
9
10
11
12
*/

#include "formatting.h"
#include "kleo/dn.h"
13
#include "kleo/keyfiltermanager.h"
14
#include "kleo/keygroup.h"
15
16
17
18

#include <gpgme++/key.h>
#include <gpgme++/importresult.h>

19
20
21
#include <QGpgME/CryptoConfig>
#include <QGpgME/Protocol>

22
23
24
25
26
27
28
29
30
#include <KLocalizedString>
#include <KEmailAddress>

#include <QString>
#include <QStringList>
#include <QDateTime>
#include <QTextDocument> // for Qt::escape
#include <QLocale>
#include <QIcon>
31
#include <QRegularExpression>
32

33
34
#include "models/keycache.h"

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using namespace GpgME;
using namespace Kleo;

//
// Name
//

QString Formatting::prettyName(int proto, const char *id, const char *name_, const char *comment_)
{

    if (proto == OpenPGP) {
        const QString name = QString::fromUtf8(name_);
        if (name.isEmpty()) {
            return QString();
        }
        const QString comment = QString::fromUtf8(comment_);
        if (comment.isEmpty()) {
            return name;
        }
        return QStringLiteral("%1 (%2)").arg(name, comment);
    }

    if (proto == CMS) {
        const DN subject(id);
        const QString cn = subject[QStringLiteral("CN")].trimmed();
        if (cn.isEmpty()) {
            return subject.prettyDN();
        }
        return cn;
    }

    return QString();
}

QString Formatting::prettyNameAndEMail(int proto, const char *id, const char *name_, const char *email_, const char *comment_)
{
    return prettyNameAndEMail(proto, QString::fromUtf8(id), QString::fromUtf8(name_), prettyEMail(email_, id), QString::fromUtf8(comment_));
}

QString Formatting::prettyNameAndEMail(int proto, const QString &id, const QString &name, const QString &email, const QString &comment)
{

    if (proto == OpenPGP) {
        if (name.isEmpty()) {
            if (email.isEmpty()) {
                return QString();
            } else if (comment.isEmpty()) {
                return QStringLiteral("<%1>").arg(email);
            } else {
                return QStringLiteral("(%2) <%1>").arg(email, comment);
            }
        }
        if (email.isEmpty()) {
            if (comment.isEmpty()) {
                return name;
            } else {
                return QStringLiteral("%1 (%2)").arg(name, comment);
            }
        }
        if (comment.isEmpty()) {
            return QStringLiteral("%1 <%2>").arg(name, email);
        } else {
            return QStringLiteral("%1 (%3) <%2>").arg(name, email, comment);
        }
    }

    if (proto == CMS) {
        const DN subject(id);
        const QString cn = subject[QStringLiteral("CN")].trimmed();
        if (cn.isEmpty()) {
            return subject.prettyDN();
        }
        return cn;
    }
    return QString();
}

QString Formatting::prettyUserID(const UserID &uid)
{
    if (uid.parent().protocol() == OpenPGP) {
        return prettyNameAndEMail(uid);
    }
    const QByteArray id = QByteArray(uid.id()).trimmed();
    if (id.startsWith('<')) {
        return prettyEMail(uid.email(), uid.id());
    }
    if (id.startsWith('('))
        // ### parse uri/dns:
    {
        return QString::fromUtf8(uid.id());
    } else {
        return DN(uid.id()).prettyDN();
    }
}

QString Formatting::prettyKeyID(const char *id)
{
    if (!id) {
        return QString();
    }
    return QLatin1String("0x") + QString::fromLatin1(id).toUpper();
}

QString Formatting::prettyNameAndEMail(const UserID &uid)
{
    return prettyNameAndEMail(uid.parent().protocol(), uid.id(), uid.name(), uid.email(), uid.comment());
}

QString Formatting::prettyNameAndEMail(const Key &key)
{
    return prettyNameAndEMail(key.userID(0));
}

QString Formatting::prettyName(const Key &key)
{
    return prettyName(key.userID(0));
}

QString Formatting::prettyName(const UserID &uid)
{
    return prettyName(uid.parent().protocol(), uid.id(), uid.name(), uid.comment());
}

QString Formatting::prettyName(const UserID::Signature &sig)
{
    return prettyName(OpenPGP, sig.signerUserID(), sig.signerName(), sig.signerComment());
}

//
// EMail
//

QString Formatting::prettyEMail(const Key &key)
{
    for (unsigned int i = 0, end = key.numUserIDs(); i < end; ++i) {
        const QString email = prettyEMail(key.userID(i));
        if (!email.isEmpty()) {
            return email;
        }
    }
    return QString();
}

QString Formatting::prettyEMail(const UserID &uid)
{
    return prettyEMail(uid.email(), uid.id());
}

QString Formatting::prettyEMail(const UserID::Signature &sig)
{
    return prettyEMail(sig.signerEmail(), sig.signerUserID());
}

QString Formatting::prettyEMail(const char *email_, const char *id)
{
    QString email, name, comment;
    if (email_ && KEmailAddress::splitAddress(QString::fromUtf8(email_),
Andre Heinecke's avatar
Andre Heinecke committed
192
                                              name, email, comment) == KEmailAddress::AddressOk) {
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        return email;
    } else {
        return DN(id)[QStringLiteral("EMAIL")].trimmed();
    }
}

//
// Tooltip
//

namespace
{

static QString protect_whitespace(QString s)
{
    static const QLatin1Char SP(' '), NBSP('\xA0');
    return s.replace(SP, NBSP);
}

template <typename T_arg>
QString format_row(const QString &field, const T_arg &arg)
{
Laurent Montel's avatar
Laurent Montel committed
215
    return QStringLiteral("<tr><th>%1:</th><td>%2</td></tr>").arg(protect_whitespace(field), arg);
216
217
218
}
QString format_row(const QString &field, const QString &arg)
{
Laurent Montel's avatar
Laurent Montel committed
219
    return QStringLiteral("<tr><th>%1:</th><td>%2</td></tr>").arg(protect_whitespace(field), arg.toHtmlEscaped());
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
}
QString format_row(const QString &field, const char *arg)
{
    return format_row(field, QString::fromUtf8(arg));
}

QString format_keytype(const Key &key)
{
    const Subkey subkey = key.subkey(0);
    if (key.hasSecret()) {
        return i18n("%1-bit %2 (secret key available)", subkey.length(), QLatin1String(subkey.publicKeyAlgorithmAsString()));
    } else {
        return i18n("%1-bit %2", subkey.length(), QLatin1String(subkey.publicKeyAlgorithmAsString()));
    }
}

236
237
238
239
240
241
242
243
244
245
246
247
248
QString format_subkeytype(const Subkey &subkey)
{
    const auto algo = subkey.publicKeyAlgorithm();

    if (algo == Subkey::AlgoECC ||
        algo == Subkey::AlgoECDSA ||
        algo == Subkey::AlgoECDH ||
        algo == Subkey::AlgoEDDSA) {
        return QString::fromStdString(subkey.algoName());
    }
    return i18n("%1-bit %2", subkey.length(), QLatin1String(subkey.publicKeyAlgorithmAsString()));
}

249
250
251
252
253
QString format_keyusage(const Key &key)
{
    QStringList capabilities;
    if (key.canReallySign()) {
        if (key.isQualified()) {
Andre Heinecke's avatar
Andre Heinecke committed
254
            capabilities.push_back(i18n("Signing (Qualified)"));
255
        } else {
Andre Heinecke's avatar
Andre Heinecke committed
256
            capabilities.push_back(i18n("Signing"));
257
258
259
        }
    }
    if (key.canEncrypt()) {
Andre Heinecke's avatar
Andre Heinecke committed
260
        capabilities.push_back(i18n("Encryption"));
261
262
    }
    if (key.canCertify()) {
263
        capabilities.push_back(i18n("Certifying User-IDs"));
264
265
    }
    if (key.canAuthenticate()) {
Andre Heinecke's avatar
Andre Heinecke committed
266
        capabilities.push_back(i18n("SSH Authentication"));
267
    }
268
    return capabilities.join(QLatin1String(", "));
269
270
}

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
QString format_subkeyusage(const Subkey &subkey)
{
    QStringList capabilities;
    if (subkey.canSign()) {
        if (subkey.isQualified()) {
            capabilities.push_back(i18n("Signing (Qualified)"));
        } else {
            capabilities.push_back(i18n("Signing"));
        }
    }
    if (subkey.canEncrypt()) {
        capabilities.push_back(i18n("Encryption"));
    }
    if (subkey.canCertify()) {
        capabilities.push_back(i18n("Certifying User-IDs"));
    }
    if (subkey.canAuthenticate()) {
        capabilities.push_back(i18n("SSH Authentication"));
    }
290
    return capabilities.join(QLatin1String(", "));
291
292
}

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
static QString time_t2string(time_t t)
{
    QDateTime dt;
    dt.setTime_t(t);
    return QLocale().toString(dt, QLocale::ShortFormat);
}

static QString make_red(const QString &txt)
{
    return QLatin1String("<font color=\"red\">") + txt.toHtmlEscaped() + QLatin1String("</font>");
}

}

QString Formatting::toolTip(const Key &key, int flags)
{
    if (flags == 0 || (key.protocol() != CMS && key.protocol() != OpenPGP)) {
        return QString();
    }

    const Subkey subkey = key.subkey(0);

    QString result;
    if (flags & Validity) {
        if (key.protocol() == OpenPGP || (key.keyListMode() & Validate))
            if (key.isRevoked()) {
Andre Heinecke's avatar
Andre Heinecke committed
319
                result = make_red(i18n("Revoked"));
320
            } else if (key.isExpired()) {
Andre Heinecke's avatar
Andre Heinecke committed
321
                result = make_red(i18n("Expired"));
322
            } else if (key.isDisabled()) {
Andre Heinecke's avatar
Andre Heinecke committed
323
                result = i18n("Disabled");
324
            } else {
Andre Heinecke's avatar
Andre Heinecke committed
325
326
327
328
329
330
331
                unsigned int fullyTrusted = 0;
                for (const auto &uid: key.userIDs()) {
                    if (uid.validity() >= UserID::Validity::Full) {
                        fullyTrusted++;
                    }
                }
                if (fullyTrusted == key.numUserIDs()) {
332
                    result = i18n("All User-IDs are certified.");
333
334
335
336
                    const auto compliance = complianceStringForKey(key);
                    if (!compliance.isEmpty()) {
                        result += QStringLiteral("<br>") + compliance;
                    }
Andre Heinecke's avatar
Andre Heinecke committed
337
                } else {
338
                    result = i18np("One User-ID is not certified.", "%1 User-IDs are not certified.", key.numUserIDs() - fullyTrusted);
Andre Heinecke's avatar
Andre Heinecke committed
339
                }
340
341
            }
        else {
Andre Heinecke's avatar
Andre Heinecke committed
342
            result = i18n("The validity cannot be checked at the moment.");
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
        }
    }
    if (flags == Validity) {
        return result;
    }

    result += QLatin1String("<table border=\"0\">");
    if (key.protocol() == CMS) {
        if (flags & SerialNumber) {
            result += format_row(i18n("Serial number"), key.issuerSerial());
        }
        if (flags & Issuer) {
            result += format_row(i18n("Issuer"), key.issuerName());
        }
    }
    if (flags & UserIDs) {
        const std::vector<UserID> uids = key.userIDs();
        if (!uids.empty())
            result += format_row(key.protocol() == CMS
                                 ? i18n("Subject")
                                 : i18n("User-ID"), prettyUserID(uids.front()));
        if (uids.size() > 1)
Laurent Montel's avatar
Laurent Montel committed
365
            for (auto it = uids.begin() + 1, end = uids.end(); it != end; ++it)
366
367
368
369
                if (!it->isRevoked() && !it->isInvalid()) {
                    result += format_row(i18n("a.k.a."), prettyUserID(*it));
                }
    }
Andre Heinecke's avatar
Andre Heinecke committed
370
371
372
373
374
375
376
377
378
    if (flags & ExpiryDates) {
        result += format_row(i18n("Created"), time_t2string(subkey.creationTime()));

        if (key.isExpired()) {
            result += format_row(i18n("Expired"), time_t2string(subkey.expirationTime()));
        } else if (!subkey.neverExpires()) {
            result += format_row(i18n("Expires"), time_t2string(subkey.expirationTime()));
        }
    }
379
    if (flags & CertificateType) {
Andre Heinecke's avatar
Andre Heinecke committed
380
        result += format_row(i18n("Type"), format_keytype(key));
381
382
    }
    if (flags & CertificateUsage) {
Andre Heinecke's avatar
Andre Heinecke committed
383
        result += format_row(i18n("Usage"), format_keyusage(key));
384
385
386
387
388
389
390
391
392
    }
    if (flags & KeyID) {
        result += format_row(i18n("Key-ID"), QString::fromLatin1(key.shortKeyID()));
    }
    if (flags & Fingerprint) {
        result += format_row(i18n("Fingerprint"), key.primaryFingerprint());
    }
    if (flags & OwnerTrust) {
        if (key.protocol() == OpenPGP) {
393
            result += format_row(i18n("Certification trust"), ownerTrustShort(key));
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        } else if (key.isRoot()) {
            result += format_row(i18n("Trusted issuer?"),
                                 key.userID(0).validity() == UserID::Ultimate ? i18n("Yes") :
                                 /* else */                                     i18n("No"));
        }
    }

    if (flags & StorageLocation) {
        if (const char *card = subkey.cardSerialNumber()) {
            result += format_row(i18n("Stored"), i18nc("stored...", "on SmartCard with serial no. %1", QString::fromUtf8(card)));
        } else {
            result += format_row(i18n("Stored"), i18nc("stored...", "on this computer"));
        }
    }
408
409
410
411
412
    if (flags & Subkeys) {
        for (const auto &sub: key.subkeys()) {
            result += QLatin1String("<hr/>");
            result += format_row(i18n("Subkey"), sub.fingerprint());
            if (sub.isRevoked()) {
413
                result += format_row(i18n("Status"), i18n("Revoked"));
414
            } else if (sub.isExpired()) {
415
                result += format_row(i18n("Status"), i18n("Expired"));
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
            }
            if (flags & ExpiryDates) {
                result += format_row(i18n("Created"), time_t2string(sub.creationTime()));

                if (key.isExpired()) {
                    result += format_row(i18n("Expired"), time_t2string(sub.expirationTime()));
                } else if (!subkey.neverExpires()) {
                    result += format_row(i18n("Expires"), time_t2string(sub.expirationTime()));
                }
            }

            if (flags & CertificateType) {
                result += format_row(i18n("Type"), format_subkeytype(sub));
            }
            if (flags & CertificateUsage) {
                result += format_row(i18n("Usage"), format_subkeyusage(sub));
            }
            if (flags & StorageLocation) {
                if (const char *card = sub.cardSerialNumber()) {
                    result += format_row(i18n("Stored"), i18nc("stored...", "on SmartCard with serial no. %1", QString::fromUtf8(card)));
                } else {
                    result += format_row(i18n("Stored"), i18nc("stored...", "on this computer"));
                }
            }
        }
    }
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    result += QLatin1String("</table>");

    return result;
}

//
// Creation and Expiration
//

namespace
{
static QDate time_t2date(time_t t)
{
    if (!t) {
Laurent Montel's avatar
Laurent Montel committed
456
        return {};
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
    }
    QDateTime dt;
    dt.setTime_t(t);
    return dt.date();
}
static QString date2string(const QDate &date)
{
    return QLocale().toString(date, QLocale::ShortFormat);
}

template <typename T>
QString expiration_date_string(const T &tee)
{
    return tee.neverExpires() ? QString() : date2string(time_t2date(tee.expirationTime()));
}
template <typename T>
QDate creation_date(const T &tee)
{
    return time_t2date(tee.creationTime());
}
template <typename T>
QDate expiration_date(const T &tee)
{
    return time_t2date(tee.expirationTime());
}
}

484
485
486
487
488
QString Formatting::dateString(time_t t)
{
    return date2string(time_t2date(t));
}

489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
QString Formatting::expirationDateString(const Key &key)
{
    return expiration_date_string(key.subkey(0));
}

QString Formatting::expirationDateString(const Subkey &subkey)
{
    return expiration_date_string(subkey);
}

QString Formatting::expirationDateString(const UserID::Signature &sig)
{
    return expiration_date_string(sig);
}

QDate Formatting::expirationDate(const Key &key)
{
    return expiration_date(key.subkey(0));
}

QDate Formatting::expirationDate(const Subkey &subkey)
{
    return expiration_date(subkey);
}

QDate Formatting::expirationDate(const UserID::Signature &sig)
{
    return expiration_date(sig);
}

QString Formatting::creationDateString(const Key &key)
{
    return date2string(creation_date(key.subkey(0)));
}

QString Formatting::creationDateString(const Subkey &subkey)
{
    return date2string(creation_date(subkey));
}

QString Formatting::creationDateString(const UserID::Signature &sig)
{
    return date2string(creation_date(sig));
}

QDate Formatting::creationDate(const Key &key)
{
    return creation_date(key.subkey(0));
}

QDate Formatting::creationDate(const Subkey &subkey)
{
    return creation_date(subkey);
}

QDate Formatting::creationDate(const UserID::Signature &sig)
{
    return creation_date(sig);
}

//
// Types
//

QString Formatting::displayName(Protocol p)
{
    if (p == CMS) {
556
        return i18nc("X.509/CMS encryption standard", "S/MIME");
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    }
    if (p == OpenPGP) {
        return i18n("OpenPGP");
    }
    return i18nc("Unknown encryption protocol", "Unknown");
}

QString Formatting::type(const Key &key)
{
    return displayName(key.protocol());
}

QString Formatting::type(const Subkey &subkey)
{
    return QString::fromUtf8(subkey.publicKeyAlgorithmAsString());
}

//
// Status / Validity
//

QString Formatting::ownerTrustShort(const Key &key)
{
    return ownerTrustShort(key.ownerTrust());
}

QString Formatting::ownerTrustShort(Key::OwnerTrust trust)
{
    switch (trust) {
    case Key::Unknown:   return i18nc("unknown trust level", "unknown");
    case Key::Never:     return i18n("untrusted");
    case Key::Marginal:  return i18nc("marginal trust", "marginal");
    case Key::Full:      return i18nc("full trust", "full");
    case Key::Ultimate:  return i18nc("ultimate trust", "ultimate");
    case Key::Undefined: return i18nc("undefined trust", "undefined");
    default:
Daniel Vrátil's avatar
Daniel Vrátil committed
593
        Q_ASSERT(!"unexpected owner trust value");
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
        break;
    }
    return QString();
}

QString Formatting::validityShort(const Subkey &subkey)
{
    if (subkey.isRevoked()) {
        return i18n("revoked");
    }
    if (subkey.isExpired()) {
        return i18n("expired");
    }
    if (subkey.isDisabled()) {
        return i18n("disabled");
    }
    if (subkey.isInvalid()) {
        return i18n("invalid");
    }
    return i18nc("as in good/valid signature", "good");
}

QString Formatting::validityShort(const UserID &uid)
{
    if (uid.isRevoked()) {
        return i18n("revoked");
    }
    if (uid.isInvalid()) {
        return i18n("invalid");
    }
    switch (uid.validity()) {
    case UserID::Unknown:   return i18nc("unknown trust level", "unknown");
    case UserID::Undefined: return i18nc("undefined trust", "undefined");
    case UserID::Never:     return i18n("untrusted");
    case UserID::Marginal:  return i18nc("marginal trust", "marginal");
    case UserID::Full:      return i18nc("full trust", "full");
    case UserID::Ultimate:  return i18nc("ultimate trust", "ultimate");
    }
    return QString();
}

QString Formatting::validityShort(const UserID::Signature &sig)
{
    switch (sig.status()) {
    case UserID::Signature::NoError:
        if (!sig.isInvalid()) {
640
641
642
643
644
645
646
647
648
649
            /* See RFC 4880 Section 5.2.1 */
            switch (sig.certClass()) {
            case 0x10: /* Generic */
            case 0x11: /* Persona */
            case 0x12: /* Casual */
            case 0x13: /* Positive */
                return i18n("valid");
            case 0x30:
                return i18n("revoked");
            default:
650
651
652
                return i18n("class %1", sig.certClass());
            }
        }
Laurent Montel's avatar
Laurent Montel committed
653
        Q_FALLTHROUGH();
Laurent Montel's avatar
Laurent Montel committed
654
        // fall through:
655
656
657
658
659
    case UserID::Signature::GeneralError:
        return i18n("invalid");
    case UserID::Signature::SigExpired:   return i18n("expired");
    case UserID::Signature::KeyExpired:   return i18n("certificate expired");
    case UserID::Signature::BadSignature: return i18nc("fake/invalid signature", "bad");
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    case UserID::Signature::NoPublicKey: {
            /* GnuPG returns the same error for no public key as for expired
             * or revoked certificates. */
            const auto key = KeyCache::instance()->findByKeyIDOrFingerprint (sig.signerKeyID());
            if (key.isNull()) {
                return i18n("no public key");
            } else if (key.isExpired()) {
                return i18n("key expired");
            } else if (key.isRevoked()) {
                return i18n("key revoked");
            } else if (key.isDisabled()) {
                return i18n("key disabled");
            }
            /* can't happen */
674
            return QStringLiteral("unknown");
675
        }
676
677
678
679
    }
    return QString();
}

680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
QIcon Formatting::validityIcon(const UserID::Signature &sig)
{
    switch (sig.status()) {
    case UserID::Signature::NoError:
        if (!sig.isInvalid()) {
            /* See RFC 4880 Section 5.2.1 */
            switch (sig.certClass()) {
            case 0x10: /* Generic */
            case 0x11: /* Persona */
            case 0x12: /* Casual */
            case 0x13: /* Positive */
                return QIcon::fromTheme(QStringLiteral("emblem-success"));
            case 0x30:
                return QIcon::fromTheme(QStringLiteral("emblem-error"));
            default:
                return QIcon();
            }
        }
        Q_FALLTHROUGH();
        // fall through:
    case UserID::Signature::BadSignature:
    case UserID::Signature::GeneralError:
        return QIcon::fromTheme(QStringLiteral("emblem-error"));
    case UserID::Signature::SigExpired:
    case UserID::Signature::KeyExpired:
        return QIcon::fromTheme(QStringLiteral("emblem-information"));
    case UserID::Signature::NoPublicKey:
        return QIcon::fromTheme(QStringLiteral("emblem-question"));
    }
Laurent Montel's avatar
Laurent Montel committed
709
    return QIcon();
710
711
}

712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
QString Formatting::formatKeyLink(const Key &key)
{
    if (key.isNull()) {
        return QString();
    }
    return QStringLiteral("<a href=\"key:%1\">%2</a>").arg(QLatin1String(key.primaryFingerprint()), Formatting::prettyName(key));
}

QString Formatting::formatForComboBox(const GpgME::Key &key)
{
    const QString name = prettyName(key);
    QString mail = prettyEMail(key);
    if (!mail.isEmpty()) {
        mail = QLatin1Char('<') + mail + QLatin1Char('>');
    }
    return i18nc("name, email, key id", "%1 %2 (%3)", name, mail, QLatin1String(key.shortKeyID())).simplified();
}

namespace
{

static QString keyToString(const Key &key)
{

Daniel Vrátil's avatar
Daniel Vrátil committed
736
    Q_ASSERT(!key.isNull());
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816

    const QString email = Formatting::prettyEMail(key);
    const QString name = Formatting::prettyName(key);

    if (name.isEmpty()) {
        return email;
    } else if (email.isEmpty()) {
        return name;
    } else {
        return QStringLiteral("%1 <%2>").arg(name, email);
    }
}

}

const char *Formatting::summaryToString(const Signature::Summary summary)
{
    if (summary & Signature::Red) {
        return "RED";
    }
    if (summary & Signature::Green) {
        return "GREEN";
    }
    return "YELLOW";
}

QString Formatting::signatureToString(const Signature &sig, const Key &key)
{
    if (sig.isNull()) {
        return QString();
    }

    const bool red   = (sig.summary() & Signature::Red);
    const bool valid = (sig.summary() & Signature::Valid);

    if (red)
        if (key.isNull())
            if (const char *fpr = sig.fingerprint()) {
                return i18n("Bad signature by unknown certificate %1: %2", QString::fromLatin1(fpr), QString::fromLocal8Bit(sig.status().asString()));
            } else {
                return i18n("Bad signature by an unknown certificate: %1", QString::fromLocal8Bit(sig.status().asString()));
            }
        else {
            return i18n("Bad signature by %1: %2", keyToString(key), QString::fromLocal8Bit(sig.status().asString()));
        }

    else if (valid)
        if (key.isNull())
            if (const char *fpr = sig.fingerprint()) {
                return i18n("Good signature by unknown certificate %1.", QString::fromLatin1(fpr));
            } else {
                return i18n("Good signature by an unknown certificate.");
            }
        else {
            return i18n("Good signature by %1.", keyToString(key));
        }

    else if (key.isNull())
        if (const char *fpr = sig.fingerprint()) {
            return i18n("Invalid signature by unknown certificate %1: %2", QString::fromLatin1(fpr), QString::fromLocal8Bit(sig.status().asString()));
        } else {
            return i18n("Invalid signature by an unknown certificate: %1", QString::fromLocal8Bit(sig.status().asString()));
        }
    else {
        return i18n("Invalid signature by %1: %2", keyToString(key), QString::fromLocal8Bit(sig.status().asString()));
    }
}

//
// ImportResult
//

QString Formatting::importMetaData(const Import &import, const QStringList &ids)
{
    const QString result = importMetaData(import);
    if (result.isEmpty()) {
        return QString();
    } else
        return result + QLatin1Char('\n') +
               i18n("This certificate was imported from the following sources:") + QLatin1Char('\n') +
Laurent Montel's avatar
Laurent Montel committed
817
               ids.join(QLatin1Char('\n'));
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
}

QString Formatting::importMetaData(const Import &import)
{

    if (import.isNull()) {
        return QString();
    }

    if (import.error().isCanceled()) {
        return i18n("The import of this certificate was canceled.");
    }
    if (import.error())
        return i18n("An error occurred importing this certificate: %1",
                    QString::fromLocal8Bit(import.error().asString()));

    const unsigned int status = import.status();
    if (status & Import::NewKey)
        return (status & Import::ContainedSecretKey)
               ? i18n("This certificate was new to your keystore. The secret key is available.")
               : i18n("This certificate is new to your keystore.");

    QStringList results;
    if (status & Import::NewUserIDs) {
        results.push_back(i18n("New user-ids were added to this certificate by the import."));
    }
    if (status & Import::NewSignatures) {
        results.push_back(i18n("New signatures were added to this certificate by the import."));
    }
    if (status & Import::NewSubkeys) {
        results.push_back(i18n("New subkeys were added to this certificate by the import."));
    }

    return results.empty()
           ? i18n("The import contained no new data for this certificate. It is unchanged.")
Laurent Montel's avatar
Laurent Montel committed
853
           : results.join(QLatin1Char('\n'));
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
}

//
// Overview in CertificateDetailsDialog
//

QString Formatting::formatOverview(const Key &key)
{
    return toolTip(key, AllOptions);
}

QString Formatting::usageString(const Subkey &sub)
{
    QStringList usageStrings;
    if (sub.canCertify()) {
        usageStrings << i18n("Certify");
    }
    if (sub.canSign()) {
        usageStrings << i18n("Sign");
    }
    if (sub.canEncrypt()) {
        usageStrings << i18n("Encrypt");
    }
    if (sub.canAuthenticate()) {
        usageStrings << i18n("Authenticate");
    }
880
    return usageStrings.join(QLatin1String(", "));
881
882
883
884
}

QString Formatting::summaryLine(const Key &key)
{
Laurent Montel's avatar
Laurent Montel committed
885
    return keyToString(key) + QLatin1Char(' ') +
886
887
888
889
           i18nc("(validity, protocol, creation date)",
                 "(%1, %2, created: %3)",
		 Formatting::complianceStringShort(key),
		 displayName(key.protocol()),
890
891
892
                 Formatting::creationDateString(key));
}

893
894
895
896
897
QString Formatting::summaryLine(const KeyGroup &group)
{
    return i18nc("name of group (group)", "%1 (group)", group.name());
}

898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// Icon for certificate selection indication
QIcon Formatting::iconForUid(const UserID &uid)
{
    switch (uid.validity()) {
        case UserID::Ultimate:
        case UserID::Full:
        case UserID::Marginal:
            return QIcon::fromTheme(QStringLiteral("emblem-success"));
        case UserID::Never:
            return QIcon::fromTheme(QStringLiteral("emblem-error"));
        case UserID::Undefined:
        case UserID::Unknown:
        default:
            return QIcon::fromTheme(QStringLiteral("emblem-information"));
    }
}

QString Formatting::validity(const UserID &uid)
{
    switch (uid.validity()) {
        case UserID::Ultimate:
            return i18n("The certificate is marked as your own.");
        case UserID::Full:
            return i18n("The certificate belongs to this recipient.");
        case UserID::Marginal:
            return i18n("The trust model indicates marginally that the certificate belongs to this recipient.");
        case UserID::Never:
            return i18n("This certificate should not be used.");
        case UserID::Undefined:
        case UserID::Unknown:
        default:
            return i18n("There is no indication that this certificate belongs to this recipient.");
    }
}
932

933
934
bool Formatting::uidsHaveFullValidity(const GpgME::Key &key)
{
935
    bool oneValid = false;
936
    for (const auto &uid: key.userIDs()) {
937
938
939
940
        if (uid.isRevoked()) {
            /* Skip revoked uids */
            continue;
        }
941
942
943
        if (uid.validity() < UserID::Validity::Full) {
            return false;
        }
944
945
946
947
        /* Only return true if we have found at least one
         * valid uid. E.g. if all uids are revoked we do
         * not want to return true here. */
        oneValid = true;
948
    }
949
    return oneValid;
950
951
}

952
953
954
955
956
957
958
959
QString Formatting::complianceMode()
{
    const QGpgME::CryptoConfig *const config = QGpgME::cryptoConfig();
    if (!config) {
        return QString();
    }
    const QGpgME::CryptoConfigEntry *const entry = config->entry(QStringLiteral("gpg"), QStringLiteral("Configuration"), QStringLiteral("compliance"));

960
    if (!entry || entry->stringValue() == QLatin1String("gnupg")) {
961
962
963
964
965
        return QString();
    }
    return entry->stringValue();
}

Justus Winter's avatar
Justus Winter committed
966
bool Formatting::isKeyDeVs(const GpgME::Key &key)
967
{
Justus Winter's avatar
Justus Winter committed
968
969
970
971
972
973
974
975
976
977
978
979
980
981
    for (const auto &sub: key.subkeys()) {
        if (sub.isExpired() || sub.isRevoked()) {
            // Ignore old subkeys
            continue;
        }
        if (!sub.isDeVs()) {
            return false;
        }
    }
    return true;
}

QString Formatting::complianceStringForKey(const GpgME::Key &key)
{
982
983
    // There will likely be more in the future for other institutions
    // for now we only have DE-VS
984
    if (complianceMode() == QLatin1String("de-vs")) {
Justus Winter's avatar
Justus Winter committed
985
        if (uidsHaveFullValidity(key) && isKeyDeVs(key)) {
986
987
            return i18nc("%1 is a placeholder for the name of a compliance mode. E.g. NATO RESTRICTED compliant or VS-NfD compliant",
                         "May be used for %1 communication.", deVsString());
988
        } else {
989
            return i18nc("VS-NfD-conforming is a German standard for restricted documents. For which special restrictions about algorithms apply. The string describes if a key is compliant to that..",
990
                         "May <b>not</b> be used for %1 communication.", deVsString());
991
992
993
994
        }
    }
    return QString();
}
995
996
997
998

QString Formatting::complianceStringShort(const GpgME::Key &key)
{
    if (Formatting::uidsHaveFullValidity(key)) {
999
        if (complianceMode() == QLatin1String("de-vs")
1000
            && Formatting::isKeyDeVs(key)) {
1001
            return QStringLiteral("★ ") + deVsString(true);
1002
1003
1004
        }
        return i18nc("As in all user IDs are valid.", "certified");
    }
1005
1006
1007
    if (key.isExpired()) {
        return i18n("expired");
    }
1008
1009
1010
1011
1012
1013
1014
1015
1016
    if (key.isRevoked()) {
        return i18n("revoked");
    }
    if (key.isDisabled()) {
        return i18n("disabled");
    }
    if (key.isInvalid()) {
        return i18n("invalid");
    }
1017
1018
1019

    return i18nc("As in not all user IDs are valid.", "not certified");
}
1020
1021
1022
1023
1024
1025

QString Formatting::prettyID(const char *id)
{
    if (!id) {
        return QString();
    }
1026
1027
1028
1029
1030
1031
1032
1033
    QString ret = QString::fromLatin1(id).toUpper().replace(QRegularExpression(QStringLiteral("(....)")),
                                                            QStringLiteral("\\1 ")).trimmed();
    // For the standard 10 group fingerprint let us use a double space in the
    // middle to increase readability
    if (ret.size() == 49) {
        ret.insert(24, QLatin1Char(' '));
    }
    return ret;
1034
}
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056

QString Formatting::origin(int o)
{
    switch (o) {
        case Key::OriginKS:
            return i18n("Keyserver");
        case Key::OriginDane:
            return QStringLiteral("DANE");
        case Key::OriginWKD:
            return QStringLiteral("WKD");
        case Key::OriginURL:
            return QStringLiteral("URL");
        case Key::OriginFile:
            return i18n("File import");
        case Key::OriginSelf:
            return i18n("Generated");
        case Key::OriginOther:
        case Key::OriginUnknown:
        default:
          return i18n("Unknown");
    }
}
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067

QString Formatting::deVsString(bool compliant)
{
    const auto filter = KeyFilterManager::instance()->keyFilterByID(compliant ?
            QStringLiteral("de-vs-filter") :
            QStringLiteral("not-de-vs-filter"));
    if (!filter) {
        return compliant ? i18n("VS-NfD compliant") : i18n("Not VS-NfD compliant");
    }
    return filter->name();
}