summaryrefslogtreecommitdiff
path: root/lang/cpp/src/key.cpp
blob: f9cc2b6046a5d22e955bde3e219465a4305b7e19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
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
484
485
486
487
488
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
556
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
593
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
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
709
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
736
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
817
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
853
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
/*
  key.cpp - wraps a gpgme key
  Copyright (C) 2003, 2005 Klarälvdalens Datakonsult AB

  This file is part of GPGME++.

  GPGME++ is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  GPGME++ 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 Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with GPGME++; see the file COPYING.LIB.  If not, write to the
  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#ifdef HAVE_CONFIG_H
 #include "config.h"
#endif

#include <key.h>

#include "util.h"
#include "tofuinfo.h"
#include "context.h"
#include "engineinfo.h"

#include <gpgme.h>

#include <string.h>
#include <strings.h>
#include <cassert>
#include <istream>
#include <iterator>

const GpgME::Key::Null GpgME::Key::null;

namespace GpgME
{

Key::Key() : key() {}

Key::Key(const Null &) : key() {}

Key::Key(const shared_gpgme_key_t &k) : key(k) {}

Key::Key(gpgme_key_t k, bool ref)
    : key(k
          ? shared_gpgme_key_t(k, &gpgme_key_unref)
          : shared_gpgme_key_t())
{
    if (ref && impl()) {
        gpgme_key_ref(impl());
    }
}

UserID Key::userID(unsigned int index) const
{
    return UserID(key, index);
}

Subkey Key::subkey(unsigned int index) const
{
    return Subkey(key, index);
}

unsigned int Key::numUserIDs() const
{
    if (!key) {
        return 0;
    }
    unsigned int count = 0;
    for (gpgme_user_id_t uid = key->uids ; uid ; uid = uid->next) {
        ++count;
    }
    return count;
}

unsigned int Key::numSubkeys() const
{
    if (!key) {
        return 0;
    }
    unsigned int count = 0;
    for (gpgme_sub_key_t subkey = key->subkeys ; subkey ; subkey = subkey->next) {
        ++count;
    }
    return count;
}

std::vector<UserID> Key::userIDs() const
{
    if (!key) {
        return std::vector<UserID>();
    }

    std::vector<UserID> v;
    v.reserve(numUserIDs());
    for (gpgme_user_id_t uid = key->uids ; uid ; uid = uid->next) {
        v.push_back(UserID(key, uid));
    }
    return v;
}

std::vector<Subkey> Key::subkeys() const
{
    if (!key) {
        return std::vector<Subkey>();
    }

    std::vector<Subkey> v;
    v.reserve(numSubkeys());
    for (gpgme_sub_key_t subkey = key->subkeys ; subkey ; subkey = subkey->next) {
        v.push_back(Subkey(key, subkey));
    }
    return v;
}

Key::OwnerTrust Key::ownerTrust() const
{
    if (!key) {
        return Unknown;
    }
    switch (key->owner_trust) {
    default:
    case GPGME_VALIDITY_UNKNOWN:   return Unknown;
    case GPGME_VALIDITY_UNDEFINED: return Undefined;
    case GPGME_VALIDITY_NEVER:     return Never;
    case GPGME_VALIDITY_MARGINAL:  return Marginal;
    case GPGME_VALIDITY_FULL:     return Full;
    case GPGME_VALIDITY_ULTIMATE: return Ultimate;
    }
}
char Key::ownerTrustAsString() const
{
    if (!key) {
        return '?';
    }
    switch (key->owner_trust) {
    default:
    case GPGME_VALIDITY_UNKNOWN:   return '?';
    case GPGME_VALIDITY_UNDEFINED: return 'q';
    case GPGME_VALIDITY_NEVER:     return 'n';
    case GPGME_VALIDITY_MARGINAL:  return 'm';
    case GPGME_VALIDITY_FULL:     return 'f';
    case GPGME_VALIDITY_ULTIMATE: return 'u';
    }
}

Protocol Key::protocol() const
{
    if (!key) {
        return UnknownProtocol;
    }
    switch (key->protocol) {
    case GPGME_PROTOCOL_CMS:     return CMS;
    case GPGME_PROTOCOL_OpenPGP: return OpenPGP;
    default:                     return UnknownProtocol;
    }
}

const char *Key::protocolAsString() const
{
    return key ? gpgme_get_protocol_name(key->protocol) : nullptr ;
}

bool Key::isRevoked() const
{
    return key && key->revoked;
}

bool Key::isExpired() const
{
    return key && key->expired;
}

bool Key::isDisabled() const
{
    return key && key->disabled;
}

bool Key::isInvalid() const
{
    return key && key->invalid;
}

bool Key::hasSecret() const
{
    return key && key->secret;
}

bool Key::isRoot() const
{
    return key && key->subkeys && key->subkeys->fpr && key->chain_id &&
           strcasecmp(key->subkeys->fpr, key->chain_id) == 0;
}

bool Key::canEncrypt() const
{
    return key && key->can_encrypt;
}

bool Key::canSign() const
{
#ifndef GPGME_CAN_SIGN_ON_SECRET_OPENPGP_KEYLISTING_NOT_BROKEN
    if (key && key->protocol == GPGME_PROTOCOL_OpenPGP) {
        return true;
    }
#endif
    return canReallySign();
}

bool Key::canReallySign() const
{
    return key && key->can_sign;
}

bool Key::canCertify() const
{
    return key && key->can_certify;
}

bool Key::canAuthenticate() const
{
    return key && key->can_authenticate;
}

bool Key::isQualified() const
{
    return key && key->is_qualified;
}

bool Key::isDeVs() const
{
    if (!key) {
        return false;
    }
    if (!key->subkeys || !key->subkeys->is_de_vs) {
        return false;
    }
    for (gpgme_sub_key_t subkey = key->subkeys ; subkey ; subkey = subkey->next) {
        if (!subkey->is_de_vs) {
            return false;
        }
    }
    return true;
}

const char *Key::issuerSerial() const
{
    return key ? key->issuer_serial : nullptr ;
}
const char *Key::issuerName() const
{
    return key ? key->issuer_name : nullptr ;
}
const char *Key::chainID() const
{
    return key ? key->chain_id : nullptr ;
}

const char *Key::keyID() const
{
    return key && key->subkeys ? key->subkeys->keyid : nullptr ;
}

const char *Key::shortKeyID() const
{
    if (!key || !key->subkeys || !key->subkeys->keyid) {
        return nullptr;
    }
    const int len = strlen(key->subkeys->keyid);
    if (len > 8) {
        return key->subkeys->keyid + len - 8; // return the last 8 bytes (in hex notation)
    } else {
        return key->subkeys->keyid;
    }
}

const char *Key::primaryFingerprint() const
{
    if (!key) {
        return nullptr;
    }
    if (key->fpr) {
        /* Return what gpgme thinks is the primary fingerprint */
        return key->fpr;
    }
    if (key->subkeys) {
        /* Return the first subkeys fingerprint */
        return key->subkeys->fpr;
    }
    return nullptr;
}

unsigned int Key::keyListMode() const
{
    return key ? convert_from_gpgme_keylist_mode_t(key->keylist_mode) : 0;
}

const Key &Key::mergeWith(const Key &other)
{
    // ### incomplete. Just merges has* and can*, nothing else atm
    // ### detach also missing

    if (!this->primaryFingerprint() ||
            !other.primaryFingerprint() ||
            strcasecmp(this->primaryFingerprint(), other.primaryFingerprint()) != 0) {
        return *this; // only merge the Key object which describe the same key
    }

    const gpgme_key_t me = impl();
    const gpgme_key_t him = other.impl();

    if (!me || !him) {
        return *this;
    }

    me->revoked          |= him->revoked;
    me->expired          |= him->expired;
    me->disabled         |= him->disabled;
    me->invalid          |= him->invalid;
    me->can_encrypt      |= him->can_encrypt;
    me->can_sign         |= him->can_sign;
    me->can_certify      |= him->can_certify;
    me->secret           |= him->secret;
    me->can_authenticate |= him->can_authenticate;
    me->is_qualified     |= him->is_qualified;
    me->keylist_mode     |= him->keylist_mode;

    // make sure the gpgme_sub_key_t::is_cardkey flag isn't lost:
    for (gpgme_sub_key_t mysk = me->subkeys ; mysk ; mysk = mysk->next) {
        for (gpgme_sub_key_t hissk = him->subkeys ; hissk ; hissk = hissk->next) {
            if (strcmp(mysk->fpr, hissk->fpr) == 0) {
                mysk->is_cardkey |= hissk->is_cardkey;
                mysk->secret |= hissk->secret;
                if (hissk->keygrip && !mysk->keygrip) {
                    mysk->keygrip = strdup(hissk->keygrip);
                }
                break;
            }
        }
    }

    return *this;
}

void Key::update()
{
    if (isNull() || !primaryFingerprint()) {
        return;
    }
    auto ctx = Context::createForProtocol(protocol());
    if (!ctx) {
        return;
    }
    ctx->setKeyListMode(KeyListMode::Local |
                        KeyListMode::Signatures |
                        KeyListMode::SignatureNotations |
                        KeyListMode::Validate |
                        KeyListMode::WithTofu |
                        KeyListMode::WithKeygrip |
                        KeyListMode::WithSecret);
    Error err;
    Key newKey;
    if (GpgME::engineInfo(GpgME::GpgEngine).engineVersion() < "2.1.0") {
        newKey = ctx->key(primaryFingerprint(), err, true);
        // Not secret so we get the information from the pubring.
        if (newKey.isNull()) {
            newKey = ctx->key(primaryFingerprint(), err, false);
        }
    } else {
        newKey = ctx->key(primaryFingerprint(), err, false);
    }
    delete ctx;
    if (err) {
        return;
    }
    swap(newKey);
}

// static
Key Key::locate(const char *mbox)
{
    if (!mbox) {
        return Key();
    }

    auto ctx = Context::createForProtocol(OpenPGP);
    if (!ctx) {
        return Key();
    }

    ctx->setKeyListMode (Extern | Local);

    Error e = ctx->startKeyListing (mbox);
    auto ret = ctx->nextKey (e);
    delete ctx;

    return ret;
}

//
//
// class Subkey
//
//

static gpgme_sub_key_t find_subkey(const shared_gpgme_key_t &key, unsigned int idx)
{
    if (key) {
        for (gpgme_sub_key_t s = key->subkeys ; s ; s = s->next, --idx) {
            if (idx == 0) {
                return s;
            }
        }
    }
    return nullptr;
}

static gpgme_sub_key_t verify_subkey(const shared_gpgme_key_t &key, gpgme_sub_key_t subkey)
{
    if (key) {
        for (gpgme_sub_key_t s = key->subkeys ; s ; s = s->next) {
            if (s == subkey) {
                return subkey;
            }
        }
    }
    return nullptr;
}

Subkey::Subkey() : key(), subkey(nullptr) {}

Subkey::Subkey(const shared_gpgme_key_t &k, unsigned int idx)
    : key(k), subkey(find_subkey(k, idx))
{

}

Subkey::Subkey(const shared_gpgme_key_t &k, gpgme_sub_key_t sk)
    : key(k), subkey(verify_subkey(k, sk))
{

}

Key Subkey::parent() const
{
    return Key(key);
}

const char *Subkey::keyID() const
{
    return subkey ? subkey->keyid : nullptr ;
}

const char *Subkey::fingerprint() const
{
    return subkey ? subkey->fpr : nullptr ;
}

Subkey::PubkeyAlgo Subkey::publicKeyAlgorithm() const
{
    return subkey ? static_cast<PubkeyAlgo>(subkey->pubkey_algo) : AlgoUnknown;
}

const char *Subkey::publicKeyAlgorithmAsString() const
{
    return gpgme_pubkey_algo_name(subkey ? subkey->pubkey_algo : (gpgme_pubkey_algo_t)0);
}

/* static */
const char *Subkey::publicKeyAlgorithmAsString(PubkeyAlgo algo)
{
    if (algo == AlgoUnknown) {
        return NULL;
    }
    return gpgme_pubkey_algo_name(static_cast<gpgme_pubkey_algo_t>(algo));
}

std::string Subkey::algoName() const
{
    char *gpgmeStr;
    if (subkey && (gpgmeStr = gpgme_pubkey_algo_string(subkey))) {
        std::string ret = std::string(gpgmeStr);
        gpgme_free(gpgmeStr);
        return ret;
    }
    return std::string();
}

bool Subkey::canEncrypt() const
{
    return subkey && subkey->can_encrypt;
}

bool Subkey::canSign() const
{
    return subkey && subkey->can_sign;
}

bool Subkey::canCertify() const
{
    return subkey && subkey->can_certify;
}

bool Subkey::canAuthenticate() const
{
    return subkey && subkey->can_authenticate;
}

bool Subkey::isQualified() const
{
    return subkey && subkey->is_qualified;
}

bool Subkey::isDeVs() const
{
    return subkey && subkey->is_de_vs;
}

bool Subkey::isCardKey() const
{
    return subkey && subkey->is_cardkey;
}

const char *Subkey::cardSerialNumber() const
{
    return subkey ? subkey->card_number : nullptr;
}

const char *Subkey::keyGrip() const
{
    return subkey ? subkey->keygrip : nullptr;
}

bool Subkey::isSecret() const
{
    return subkey && subkey->secret;
}

unsigned int Subkey::length() const
{
    return subkey ? subkey->length : 0 ;
}

time_t Subkey::creationTime() const
{
    return static_cast<time_t>(subkey ? subkey->timestamp : 0);
}

time_t Subkey::expirationTime() const
{
    return static_cast<time_t>(subkey ? subkey->expires : 0);
}

bool Subkey::neverExpires() const
{
    return expirationTime() == time_t(0);
}

bool Subkey::isRevoked() const
{
    return subkey && subkey->revoked;
}

bool Subkey::isInvalid() const
{
    return subkey && subkey->invalid;
}

bool Subkey::isExpired() const
{
    return subkey && subkey->expired;
}

bool Subkey::isDisabled() const
{
    return subkey && subkey->disabled;
}

//
//
// class UserID
//
//

static gpgme_user_id_t find_uid(const shared_gpgme_key_t &key, unsigned int idx)
{
    if (key) {
        for (gpgme_user_id_t u = key->uids ; u ; u = u->next, --idx) {
            if (idx == 0) {
                return u;
            }
        }
    }
    return nullptr;
}

static gpgme_user_id_t verify_uid(const shared_gpgme_key_t &key, gpgme_user_id_t uid)
{
    if (key) {
        for (gpgme_user_id_t u = key->uids ; u ; u = u->next) {
            if (u == uid) {
                return uid;
            }
        }
    }
    return nullptr;
}

UserID::UserID() : key(), uid(nullptr) {}

UserID::UserID(const shared_gpgme_key_t &k, gpgme_user_id_t u)
    : key(k), uid(verify_uid(k, u))
{

}

UserID::UserID(const shared_gpgme_key_t &k, unsigned int idx)
    : key(k), uid(find_uid(k, idx))
{

}

Key UserID::parent() const
{
    return Key(key);
}

UserID::Signature UserID::signature(unsigned int index) const
{
    return Signature(key, uid, index);
}

unsigned int UserID::numSignatures() const
{
    if (!uid) {
        return 0;
    }
    unsigned int count = 0;
    for (gpgme_key_sig_t sig = uid->signatures ; sig ; sig = sig->next) {
        ++count;
    }
    return count;
}

std::vector<UserID::Signature> UserID::signatures() const
{
    if (!uid) {
        return std::vector<Signature>();
    }

    std::vector<Signature> v;
    v.reserve(numSignatures());
    for (gpgme_key_sig_t sig = uid->signatures ; sig ; sig = sig->next) {
        v.push_back(Signature(key, uid, sig));
    }
    return v;
}

const char *UserID::id() const
{
    return uid ? uid->uid : nullptr ;
}

const char *UserID::name() const
{
    return uid ? uid->name : nullptr ;
}

const char *UserID::email() const
{
    return uid ? uid->email : nullptr ;
}

const char *UserID::comment() const
{
    return uid ? uid->comment : nullptr ;
}

const char *UserID::uidhash() const
{
    return uid ? uid->uidhash : nullptr ;
}

UserID::Validity UserID::validity() const
{
    if (!uid) {
        return Unknown;
    }
    switch (uid->validity) {
    default:
    case GPGME_VALIDITY_UNKNOWN:   return Unknown;
    case GPGME_VALIDITY_UNDEFINED: return Undefined;
    case GPGME_VALIDITY_NEVER:     return Never;
    case GPGME_VALIDITY_MARGINAL:  return Marginal;
    case GPGME_VALIDITY_FULL:      return Full;
    case GPGME_VALIDITY_ULTIMATE:  return Ultimate;
    }
}

char UserID::validityAsString() const
{
    if (!uid) {
        return '?';
    }
    switch (uid->validity) {
    default:
    case GPGME_VALIDITY_UNKNOWN:   return '?';
    case GPGME_VALIDITY_UNDEFINED: return 'q';
    case GPGME_VALIDITY_NEVER:     return 'n';
    case GPGME_VALIDITY_MARGINAL:  return 'm';
    case GPGME_VALIDITY_FULL:      return 'f';
    case GPGME_VALIDITY_ULTIMATE:  return 'u';
    }
}

bool UserID::isRevoked() const
{
    return uid && uid->revoked;
}

bool UserID::isInvalid() const
{
    return uid && uid->invalid;
}

TofuInfo UserID::tofuInfo() const
{
    if (!uid) {
        return TofuInfo();
    }
    return TofuInfo(uid->tofu);
}

static gpgme_key_sig_t find_last_valid_sig_for_keyid (gpgme_user_id_t uid,
                                                      const char *keyid)
{
    if (!keyid) {
        return nullptr;
    }
    gpgme_key_sig_t ret = NULL;
    for (gpgme_key_sig_t s = uid->signatures ; s ; s = s->next) {
        if (s->keyid && !strcmp(keyid, s->keyid)) {
            if (!s->expired && !s->revoked && !s->invalid && !s->status) {
                if (!ret) {
                    ret = s;
                } else if (ret && ret->timestamp <= s->timestamp) {
                    /* Equals because when the timestamps are the same we prefer
                       the last in the list */
                    ret = s;
                }
            }
        }
    }
    return ret;
}

const char *UserID::remark(const Key &remarker, Error &err) const
{
    if (!uid || remarker.isNull()) {
        err = Error::fromCode(GPG_ERR_GENERAL);
        return nullptr;
    }

    if (key->protocol != GPGME_PROTOCOL_OpenPGP) {
        return nullptr;
    }

    if (!(key->keylist_mode & GPGME_KEYLIST_MODE_SIG_NOTATIONS) ||
        !(key->keylist_mode & GPGME_KEYLIST_MODE_SIGS)) {
        err = Error::fromCode(GPG_ERR_NO_DATA);
        return nullptr;
    }

    gpgme_key_sig_t s = find_last_valid_sig_for_keyid(uid, remarker.keyID());

    if (!s) {
        return nullptr;
    }

    for (gpgme_sig_notation_t n = s->notations; n ; n = n->next) {
        if (n->name && !strcmp(n->name, "rem@gnupg.org")) {
            return n->value;
        }
    }
    return nullptr;
}

std::vector<std::string> UserID::remarks(std::vector<Key> keys, Error &err) const
{
    std::vector<std::string> ret;

    for (const auto &key: keys) {
        const char *rem = remark(key, err);
        if (err) {
            return ret;
        }
        if (rem) {
            ret.push_back(rem);
        }
    }
    return ret;
}

//
//
// class Signature
//
//

static gpgme_key_sig_t find_signature(gpgme_user_id_t uid, unsigned int idx)
{
    if (uid) {
        for (gpgme_key_sig_t s = uid->signatures ; s ; s = s->next, --idx) {
            if (idx == 0) {
                return s;
            }
        }
    }
    return nullptr;
}

static gpgme_key_sig_t verify_signature(gpgme_user_id_t uid, gpgme_key_sig_t sig)
{
    if (uid) {
        for (gpgme_key_sig_t s = uid->signatures ; s ; s = s->next) {
            if (s == sig) {
                return sig;
            }
        }
    }
    return nullptr;
}

static int signature_index(gpgme_user_id_t uid, gpgme_key_sig_t sig)
{
    if (uid) {
        int i = 0;
        for (gpgme_key_sig_t s = uid->signatures ; s ; s = s->next, ++i) {
            if (s == sig) {
                return i;
            }
        }
    }
    return -1;
}

UserID::Signature::Signature() : key(), uid(nullptr), sig(nullptr) {}

UserID::Signature::Signature(const shared_gpgme_key_t &k, gpgme_user_id_t u, unsigned int idx)
    : key(k), uid(verify_uid(k, u)), sig(find_signature(uid, idx))
{
}

UserID::Signature::Signature(const shared_gpgme_key_t &k, gpgme_user_id_t u, gpgme_key_sig_t s)
    : key(k), uid(verify_uid(k, u)), sig(verify_signature(uid, s))
{
}

bool UserID::Signature::operator<(const Signature &other)
{
    // kept for binary compatibility
    return static_cast<const UserID::Signature *>(this)->operator<(other);
}

bool UserID::Signature::operator<(const Signature &other) const
{
    // based on cmp_signodes() in g10/keylist.c

    // both signatures must belong to the same user ID
    assert(uid == other.uid);

    // self-signatures are ordered first
    const char *primaryKeyId = parent().parent().keyID();
    const bool thisIsSelfSignature = strcmp(signerKeyID(), primaryKeyId) == 0;
    const bool otherIsSelfSignature = strcmp(other.signerKeyID(), primaryKeyId) == 0;
    if (thisIsSelfSignature && !otherIsSelfSignature) {
        return true;
    }
    if (otherIsSelfSignature && !thisIsSelfSignature) {
        return false;
    }

    // then sort by signer key ID (which are or course the same for self-sigs)
    const int keyIdComparison = strcmp(signerKeyID(), other.signerKeyID());
    if (keyIdComparison < 0) {
        return true;
    }
    if (keyIdComparison > 0) {
        return false;
    }

    // followed by creation time
    if (creationTime() < other.creationTime()) {
        return true;
    }
    if (creationTime() > other.creationTime()) {
        return false;
    }

    // followed by the class in a way that a rev comes first
    if (certClass() < other.certClass()) {
        return true;
    }
    if (certClass() > other.certClass()) {
        return false;
    }

    // to make the sort stable we compare the indexes of the signatures as last resort
    return signature_index(uid, sig) < signature_index(uid, other.sig);
}

UserID UserID::Signature::parent() const
{
    return UserID(key, uid);
}

const char *UserID::Signature::signerKeyID() const
{
    return sig ? sig->keyid : nullptr ;
}

const char *UserID::Signature::algorithmAsString() const
{
    return gpgme_pubkey_algo_name(sig ? sig->pubkey_algo : (gpgme_pubkey_algo_t)0);
}

unsigned int UserID::Signature::algorithm() const
{
    return sig ? sig->pubkey_algo : 0 ;
}

time_t UserID::Signature::creationTime() const
{
    return static_cast<time_t>(sig ? sig->timestamp : 0);
}

time_t UserID::Signature::expirationTime() const
{
    return static_cast<time_t>(sig ? sig->expires : 0);
}

bool UserID::Signature::neverExpires() const
{
    return expirationTime() == time_t(0);
}

bool UserID::Signature::isRevokation() const
{
    return sig && sig->revoked;
}

bool UserID::Signature::isInvalid() const
{
    return sig && sig->invalid;
}

bool UserID::Signature::isExpired() const
{
    return sig && sig->expired;
}

bool UserID::Signature::isExportable() const
{
    return sig && sig->exportable;
}

const char *UserID::Signature::signerUserID() const
{
    return sig ? sig->uid : nullptr ;
}

const char *UserID::Signature::signerName() const
{
    return sig ? sig->name : nullptr ;
}

const char *UserID::Signature::signerEmail() const
{
    return sig ? sig->email : nullptr ;
}

const char *UserID::Signature::signerComment() const
{
    return sig ? sig->comment : nullptr ;
}

unsigned int UserID::Signature::certClass() const
{
    return sig ? sig->sig_class : 0 ;
}

UserID::Signature::Status UserID::Signature::status() const
{
    if (!sig) {
        return GeneralError;
    }

    switch (gpgme_err_code(sig->status)) {
    case GPG_ERR_NO_ERROR:      return NoError;
    case GPG_ERR_SIG_EXPIRED:   return SigExpired;
    case GPG_ERR_KEY_EXPIRED:   return KeyExpired;
    case GPG_ERR_BAD_SIGNATURE: return BadSignature;
    case GPG_ERR_NO_PUBKEY:     return NoPublicKey;
    default:
    case GPG_ERR_GENERAL:       return GeneralError;
    }
}

std::string UserID::Signature::statusAsString() const
{
    if (!sig) {
        return std::string();
    }
    char buf[ 1024 ];
    gpgme_strerror_r(sig->status, buf, sizeof buf);
    buf[ sizeof buf - 1 ] = '\0';
    return std::string(buf);
}

GpgME::Notation UserID::Signature::notation(unsigned int idx) const
{
    if (!sig) {
        return GpgME::Notation();
    }
    for (gpgme_sig_notation_t nota = sig->notations ; nota ; nota = nota->next) {
        if (nota->name) {
            if (idx-- == 0) {
                return GpgME::Notation(nota);
            }
        }
    }
    return GpgME::Notation();
}

unsigned int UserID::Signature::numNotations() const
{
    if (!sig) {
        return 0;
    }
    unsigned int count = 0;
    for (gpgme_sig_notation_t nota = sig->notations ; nota ; nota = nota->next) {
        if (nota->name) {
            ++count; // others are policy URLs...
        }
    }
    return count;
}

std::vector<Notation> UserID::Signature::notations() const
{
    if (!sig) {
        return std::vector<GpgME::Notation>();
    }
    std::vector<GpgME::Notation> v;
    v.reserve(numNotations());
    for (gpgme_sig_notation_t nota = sig->notations ; nota ; nota = nota->next) {
        if (nota->name) {
            v.push_back(GpgME::Notation(nota));
        }
    }
    return v;
}

const char *UserID::Signature::policyURL() const
{
    if (!sig) {
        return nullptr;
    }
    for (gpgme_sig_notation_t nota = sig->notations ; nota ; nota = nota->next) {
        if (!nota->name) {
            return nota->value;
        }
    }
    return nullptr;
}

std::string UserID::addrSpecFromString(const char *userid)
{
    if (!userid) {
        return std::string();
    }
    char *normalized = gpgme_addrspec_from_uid (userid);
    if (normalized) {
        std::string ret(normalized);
        gpgme_free(normalized);
        return ret;
    }
    return std::string();
}

std::string UserID::addrSpec() const
{
    if (!uid || !uid->address) {
        return std::string();
    }

    return uid->address;
}

Error UserID::revoke()
{
    if (isNull()) {
        return Error::fromCode(GPG_ERR_GENERAL);
    }
    auto ctx = Context::createForProtocol(parent().protocol());
    if (!ctx) {
        return Error::fromCode(GPG_ERR_INV_ENGINE);
    }
    Error ret = ctx->revUid(key, id());
    delete ctx;
    return ret;
}

static Key::Origin gpgme_origin_to_pp_origin (const unsigned int origin)
{
    switch (origin) {
        case GPGME_KEYORG_KS:
            return Key::OriginKS;
        case GPGME_KEYORG_DANE:
            return Key::OriginDane;
        case GPGME_KEYORG_WKD:
            return Key::OriginWKD;
        case GPGME_KEYORG_URL:
            return Key::OriginURL;
        case GPGME_KEYORG_FILE:
            return Key::OriginFile;
        case GPGME_KEYORG_SELF:
            return Key::OriginSelf;
        case GPGME_KEYORG_OTHER:
            return Key::OriginOther;
        case GPGME_KEYORG_UNKNOWN:
        default:
            return Key::OriginUnknown;
    }
}

Key::Origin UserID::origin() const
{
    if (isNull()) {
        return Key::OriginUnknown;
    }
    return gpgme_origin_to_pp_origin(uid->origin);
}

time_t UserID::lastUpdate() const
{
    return static_cast<time_t>(uid ? uid->last_update : 0);
}

Error Key::addUid(const char *uid)
{
    if (isNull()) {
        return Error::fromCode(GPG_ERR_GENERAL);
    }
    auto ctx = Context::createForProtocol(protocol());
    if (!ctx) {
        return Error::fromCode(GPG_ERR_INV_ENGINE);
    }
    Error ret = ctx->addUid(key, uid);
    delete ctx;
    return ret;
}

Key::Origin Key::origin() const
{
    if (isNull()) {
        return OriginUnknown;
    }
    return gpgme_origin_to_pp_origin(key->origin);
}

time_t Key::lastUpdate() const
{
    return static_cast<time_t>(key ? key->last_update : 0);
}

bool Key::isBad() const
{
    return isNull() || isRevoked() || isExpired() || isDisabled() || isInvalid();
}

bool Subkey::isBad() const
{
    return isNull() || isRevoked() || isExpired() || isDisabled() || isInvalid();
}

bool UserID::isBad() const
{
    return isNull() || isRevoked() || isInvalid();
}

bool UserID::Signature::isBad() const
{
    return isNull() || isExpired() || isInvalid();
}

std::ostream &operator<<(std::ostream &os, const UserID &uid)
{
    os << "GpgME::UserID(";
    if (!uid.isNull()) {
        os << "\n name:      " << protect(uid.name())
           << "\n email:     " << protect(uid.email())
           << "\n mbox:      " << uid.addrSpec()
           << "\n comment:   " << protect(uid.comment())
           << "\n validity:  " << uid.validityAsString()
           << "\n revoked:   " << uid.isRevoked()
           << "\n invalid:   " << uid.isInvalid()
           << "\n numsigs:   " << uid.numSignatures()
           << "\n origin:    " << uid.origin()
           << "\n updated:   " << uid.lastUpdate()
           << "\n tofuinfo:\n" << uid.tofuInfo();
    }
    return os << ')';
}

std::ostream &operator<<(std::ostream &os, const Subkey &subkey)
{
    os << "GpgME::Subkey(";
    if (!subkey.isNull()) {
        os << "\n fingerprint:   " << protect(subkey.fingerprint())
           << "\n creationTime:  " << subkey.creationTime()
           << "\n expirationTime:" << subkey.expirationTime()
           << "\n isRevoked:     " << subkey.isRevoked()
           << "\n isExpired:     " << subkey.isExpired()
           << "\n isInvalid:     " << subkey.isRevoked()
           << "\n isDisabled:    " << subkey.isInvalid()
           << "\n canSign:       " << subkey.canSign()
           << "\n canEncrypt:    " << subkey.canEncrypt()
           << "\n canCertify:    " << subkey.canCertify()
           << "\n canAuth:       " << subkey.canAuthenticate();
    }
    return os << ')';
}

std::ostream &operator<<(std::ostream &os, const Key &key)
{
    os << "GpgME::Key(";
    if (!key.isNull()) {
        os << "\n protocol:   " << protect(key.protocolAsString())
           << "\n ownertrust: " << key.ownerTrustAsString()
           << "\n issuer:     " << protect(key.issuerName())
           << "\n fingerprint:" << protect(key.primaryFingerprint())
           << "\n listmode:   " << key.keyListMode()
           << "\n canSign:    " << key.canReallySign()
           << "\n canEncrypt: " << key.canEncrypt()
           << "\n canCertify: " << key.canCertify()
           << "\n canAuth:    " << key.canAuthenticate()
           << "\n origin:     " << key.origin()
           << "\n updated:    " << key.lastUpdate()
           << "\n uids:\n";
        const std::vector<UserID> uids = key.userIDs();
        std::copy(uids.begin(), uids.end(),
                  std::ostream_iterator<UserID>(os, "\n"));
        const std::vector<Subkey> subkeys = key.subkeys();
        std::copy(subkeys.begin(), subkeys.end(),
                  std::ostream_iterator<Subkey>(os, "\n"));
    }
    return os << ')';
}

} // namespace GpgME