aboutsummaryrefslogtreecommitdiffstats
path: root/src/m_email/EMailModule.cpp
blob: 9beabaeb78fe4edd82ae77ac23adffc4a4c6fabf (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
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
/**
 * Copyright (C) 2021-2026 Saturneric <eric@bktus.com>
 *
 * This file is part of GpgFrontend.
 *
 * GpgFrontend 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 3 of the License, or
 * (at your option) any later version.
 *
 * GpgFrontend 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 GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from
 * the gpg4usb project, which is under GPL-3.0-or-later.
 *
 * All the source code of GpgFrontend was modified and released by
 * Saturneric <eric@bktus.com> starting on May 12, 2021.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#include "EMailModule.h"

#include <GFSDKBasic.h>
#include <GFSDKBuildInfo.h>
#include <GFSDKLog.h>

#include "EMailAccountSettingsPage.h"
#include "EMailAccountStore.h"
#include "EMailSecret.h"
#include "EMailImapController.h"
#include "EMailSendDialog.h"

// qt
#include <QApplication>
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QFileDialog>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QSaveFile>
#include <QStandardPaths>
#include <QString>
#include <QTextDocument>

#include "EMailPageView.h"

// vmime
// The test target defines this on the command line; the module build does
// not, so it is set here and guarded rather than assumed either way.
#ifndef VMIME_STATIC
#define VMIME_STATIC
#endif
#include <algorithm>
#include <vmime/vmime.hpp>

// vmime extend
#include <vmime/contentTypeField.hpp>

#include "GFModuleCommonUtils.hpp"
#include "GFModuleDefine.h"

//
#include "EMailBasicGpgOpera.h"
#include "EMailHelper.h"

GF_MODULE_API_DEFINE_V2("com.bktus.gpgfrontend.module.email", "Email", "2.0.0",
                        "Everything related to E-Mails.", "Saturneric")

DEFINE_TRANSLATIONS_STRUCTURE(ModuleEMail);

namespace {

// Build one Info Board card object (title/status/fields) in the JSON shape the
// UI's decode_info_board_cards() expects. Empty values are dropped so the card
// stays compact, matching how the native operations render.
auto MakeCardJson(const QString& title, const QString& status,
                  const QList<QPair<QString, QString>>& fields) -> QJsonObject {
  QJsonArray field_array;
  for (const auto& f : fields) {
    if (f.second.isEmpty()) continue;
    field_array.append(QJsonArray{f.first, f.second});
  }
  return QJsonObject{
      {"title", title}, {"status", status}, {"fields", field_array}};
}

// Structured E-Mail header card from parsed metadata.
auto BuildEMailHeaderCard(const EMailMetaData& m) -> QJsonObject {
  return MakeCardJson(
      QApplication::translate("EMailModule", "E-Mail"), "neutral",
      {{QApplication::translate("EMailModule", "From"), m.from},
       {QApplication::translate("EMailModule", "To"), m.to.join("; ")},
       {QApplication::translate("EMailModule", "Subject"), m.subject},
       {QApplication::translate("EMailModule", "CC"), m.cc.join("; ")},
       {QApplication::translate("EMailModule", "BCC"), m.bcc_header.join("; ")},
       {QApplication::translate("EMailModule", "Date"),
        m.datetime.isValid() ? QLocale().toString(m.datetime) : QString()}});
}

// Structured OpenPGP/MIME metadata card from parsed metadata.
auto BuildOpenPGPMetaCard(const EMailMetaData& m) -> QJsonObject {
  return MakeCardJson(
      QApplication::translate("EMailModule", "OpenPGP"), "neutral",
      // Two different things, kept apart on purpose: the first is a digest we
      // computed over the bytes the signature covers, the second is only what
      // the message declares about the signature's hash algorithm.
      {{QApplication::translate("EMailModule",
                                "Digest of Signed MIME Entity (SHA-256)"),
        m.signed_entity_digest},
       {QApplication::translate("EMailModule",
                                "Declared Signature Hash (micalg)"),
        m.micalg}});
}

// Human-readable byte size for an attachment row.
auto FormatSize(qint64 bytes) -> QString {
  return QLocale().formattedDataSize(bytes);
}

// One card listing what the message carries besides its body.
//
// Attachments used to be enumerated and then dropped on the floor, so a signed
// or encrypted message with a document in it looked, to the user, exactly like
// one without. The unsigned marker matters: in PGP/MIME only the
// multipart/signed subtree is authenticated, so a part outside it arrived
// unverified however good the signature on the rest is.
auto BuildAttachmentCard(const EMailMetaData& m) -> QJsonObject {
  QList<QPair<QString, QString>> fields;

  for (const auto& att : m.attachments) {
    const auto name = SanitizeAttachmentFileName(att.filename, att.mime_type);

    auto description =
        QString("%1, %2").arg(att.mime_type, FormatSize(att.data.size()));
    if (att.is_openpgp_key) {
      description += QApplication::translate("EMailModule", " — OpenPGP key");
    }
    if (!att.inside_signed_part) {
      description +=
          QApplication::translate("EMailModule", " — NOT covered by signature");
    }

    fields.append({name, description});
  }

  return MakeCardJson(QApplication::translate("EMailModule", "Attachments"),
                      "neutral", fields);
}

// Build "Encryption Recipient" cards from the selected recipient keys. The
// encrypt result itself does not carry recipient identities for every engine
// (GnuPG reports none), but the module always knows which keys it encrypted to,
// so resolve each to its primary UID here — mirroring the native operation's
// recipient card.
// The address a key stands for, as "Name <email>".
auto AddressOfKey(int channel, const QString& key_id) -> QString {
  if (key_id.isEmpty()) return {};

  GFGpgKeyUID* uid = nullptr;
  if (GFGpgKeyPrimaryUID(channel, QDUP(key_id), &uid) != 0 || uid == nullptr) {
    return {};
  }

  const auto name = UDUP(uid->name);
  const auto email = UDUP(uid->email);
  UDUP(uid->comment);  // free the unused field
  GFFreeMemory(uid);

  return email.isEmpty() ? name : QString("%1 <%2>").arg(name, email);
}

// Envelope for content that is not a message yet -- text typed straight into
// the raw source view and handed to an operation without going through the
// message view first.
//
// This used to be a modal dialog asking for From, To and Subject. Everything it
// really needed is already known: encryption is to a set of keys and signing is
// with one, and each of those keys carries the address it belongs to. So the
// envelope is derived rather than demanded, and the user is not interrupted to
// retype what they already chose in the key list.
auto EnvelopeFromKeys(int channel, const QString& sign_key,
                      const QStringList& encrypt_keys) -> EMailMetaData {
  EMailMetaData meta_data;

  meta_data.from = AddressOfKey(channel, sign_key);
  for (const auto& key : encrypt_keys) {
    const auto address = AddressOfKey(channel, key);
    if (!address.isEmpty()) meta_data.to.append(address);
  }

  // A signed-only message has no recipient key to derive an address from, so
  // it stays unaddressed -- which BuildMimeEML now handles rather than
  // refusing.
  if (meta_data.from.isEmpty() && !meta_data.to.isEmpty()) {
    meta_data.from = meta_data.to.front();
  }

  meta_data.datetime = QDateTime::currentDateTime();
  return meta_data;
}

auto BuildRecipientCards(int channel, const QStringList& encrypt_keys)
    -> QJsonArray {
  QJsonArray cards;
  for (const auto& key_id : encrypt_keys) {
    if (key_id.isEmpty()) continue;

    const auto recipient = AddressOfKey(channel, key_id);

    cards.append(MakeCardJson(
        QApplication::translate("EMailModule", "Encryption Recipient"), "ok",
        {{QApplication::translate("EMailModule", "Recipient"), recipient},
         {QApplication::translate("EMailModule", "Key ID"), key_id}}));
  }
  return cards;
}

// The metadata cards for a message that was read rather than composed.
auto BuildReadMetaCards(const EMailMetaData& m, bool with_openpgp)
    -> QJsonArray {
  QJsonArray cards{BuildEMailHeaderCard(m)};
  if (with_openpgp) cards.append(BuildOpenPGPMetaCard(m));
  // The board renders a limited number of cards, so only spend one on
  // attachments when there is something to list.
  if (!m.attachments.isEmpty()) cards.append(BuildAttachmentCard(m));
  return cards;
}

// Concatenate two crypto card JSON arrays (as returned by GFAnalyse*Result)
// into one, for combined operations like Encrypt+Sign and Decrypt+Verify.
auto MergeCardArrays(const QString& a, const QString& b) -> QString {
  QJsonArray merged;
  for (const auto& s : {a, b}) {
    if (s.isEmpty()) continue;
    const auto doc = QJsonDocument::fromJson(s.toUtf8());
    if (doc.isArray()) {
      for (const auto& v : doc.array()) merged.append(v);
    }
  }
  return QString::fromUtf8(
      QJsonDocument(merged).toJson(QJsonDocument::Compact));
}

// The recipient cross-check, as a card.
//
// Asymmetric on purpose. Someone in To or Cc who was not encrypted to has a
// real problem: they were told the message is for them and cannot open it.
// The reverse -- a key that is not in the headers -- is ordinary (a blind
// copy, an archive key, the sender's own key, or a deliberately hidden
// recipient) and is reported without alarm. Treating it as suspicious would
// raise a warning on most correct messages.
auto BuildRecipientCheckCard(const EMailMetaData& m,
                             const QByteArray& decrypt_info_json)
    -> QJsonObject {
  const auto encrypted = ParseRecipientInfos(decrypt_info_json);
  if (encrypted.isEmpty()) return {};

  const auto rows = MatchRecipients(m.to, m.cc, m.bcc_header, encrypted);

  QList<QPair<QString, QString>> fields;
  bool any_warning = false;

  for (const auto& row : rows) {
    switch (row.match) {
      case RecipientMatch::kMATCHED:
        fields.append({row.address,
                       QApplication::translate("EMailModule", "encrypted to")});
        break;
      case RecipientMatch::kADDRESSED_NOT_ENCRYPTED:
        any_warning = true;
        fields.append(
            {row.address,
             QApplication::translate("EMailModule",
                                     "in %1 but NOT encrypted to - cannot read")
                 .arg(row.header_field)});
        break;
      case RecipientMatch::kENCRYPTED_NOT_ADDRESSED:
        fields.append({row.info.uid.isEmpty() ? row.info.key_id : row.info.uid,
                       QApplication::translate(
                           "EMailModule", "encrypted to, not in the headers")});
        break;
      case RecipientMatch::kHIDDEN_RECIPIENT:
        fields.append(
            {QApplication::translate("EMailModule", "Hidden recipient"),
             QApplication::translate("EMailModule",
                                     "the sender withheld this key id")});
        break;
    }
  }

  if (fields.isEmpty()) return {};

  return MakeCardJson(QApplication::translate("EMailModule", "Recipient Check"),
                      any_warning ? "warn" : "ok", fields);
}

// Assemble the `result_cards` payload the UI decodes: the module's own metadata
// cards followed by the crypto-analysis cards produced by the SDK (which reuses
// the same converter the native operations use). `crypto_cards_json` is the
// JSON array string returned via the GFAnalyse*Result `cards` out-param.
auto BuildResultCardsParam(const QString& operation,
                           const QJsonArray& meta_cards,
                           const QString& crypto_cards_json,
                           const QByteArray& info_json = {}) -> QString {
  QJsonArray cards = meta_cards;
  if (!crypto_cards_json.isEmpty()) {
    const auto doc = QJsonDocument::fromJson(crypto_cards_json.toUtf8());
    if (doc.isArray()) {
      for (const auto& v : doc.array()) cards.append(v);
    }
  }

  QJsonObject obj{{"operation", operation}};

  // The structured analysis, if the caller had one. Without it the Info Board
  // has no description to show and falls back to "<operation> failed. See the
  // details for more information." -- which is how a failed e-mail decrypt came
  // to say less than the same failure on plain text, where the native path
  // hands over exactly these fields.
  //
  // Read from the JSON rather than from the rendered report: the Info Board
  // never parses report text, and neither does this.
  if (!info_json.isEmpty()) {
    const auto info = QJsonDocument::fromJson(info_json).object();

    // "Decrypt E-Mail · GnuPG v2.4.7" -- the engine belongs in the heading,
    // because which engine produced a verdict is part of the verdict.
    const auto engine = info.value("engine").toString();
    if (!engine.isEmpty()) {
      obj["operation"] = QString("%1 · %2").arg(operation, engine);
    }

    const auto description = info.value("description").toString();
    if (!description.isEmpty()) obj.insert("description", description);

    const auto details = info.value("details").toArray();
    if (!details.isEmpty()) {
      // The same titles the native path uses, chosen the same way, so one
      // failure does not get two different names depending on which door the
      // user came in through.
      QString title = QApplication::translate("EMailModule", "DETAILS");
      if (operation.contains(QApplication::translate("EMailModule", "Decrypt"),
                             Qt::CaseInsensitive)) {
        title = QApplication::translate("EMailModule", "RECIPIENT");
      } else if (operation.contains(
                     QApplication::translate("EMailModule", "Sign"),
                     Qt::CaseInsensitive) ||
                 operation.contains(
                     QApplication::translate("EMailModule", "Verify"),
                     Qt::CaseInsensitive)) {
        title = QApplication::translate("EMailModule", "SIGNER");
      }

      obj.insert("details_title", title);
      obj.insert("details_items", details);
    }
  }

  // A payload with neither cards nor a description has nothing the board could
  // render, so the caller falls back to the plain-text path.
  if (cards.isEmpty() && !obj.contains("description")) return {};

  obj.insert("cards", cards);
  return QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Compact));
}

}  // namespace

/// Identifier of the settings page this module owns.
constexpr auto kMailSettingsPageId =
    "com.bktus.gpgfrontend.module.email.accounts";

auto GFRegisterModule() -> int {
  MLogDebug("email module registering...");

  // The MIME code carries no SDK symbol of its own so it can be unit-tested
  // without a module host; this is what gives it a logger at runtime.
  SetMimeLogSink([](const QString& m) { MLogDebug(m); });

  REGISTER_TRANS_READER();

  LISTEN("MAINWINDOW_MENU_MOUNTED");

  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_ENCRYPT");
  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_DECRYPT");
  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_SIGN");
  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_VERIFY");
  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_ENCRYPT_SIGN");
  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_DECRYPT_VERIFY");

  LISTEN("EDIT_TAB_TYPE_EMAIL_OP_SAVE_FILE");

  // The message view of an e-mail tab. The host still owns the page and its
  // document -- this only supplies the widget shown on top of it, with the raw
  // MIME still one click away.
  GFUIRegisterTabPageView(
      DUP("EMAIL"), [](void*) -> void* { return new EMailPageView(nullptr); },
      nullptr);

  // register file extension handler
  GFUIRegisterFileExtensionHandleEvent(DUP("eml"), DUP("EMAIL"));

  LISTEN("FILE_EXT_EMAIL_OP_OPEN_FILE");

  // These cross thread boundaries as queued signal arguments, so Qt has to
  // know how to copy them before the first connection is made.
  qRegisterMetaType<MailAccountConfig>("MailAccountConfig");
  // Shared rather than copied: a queued connection copies its arguments, and
  // copying the pointer is not copying the password. See EMailSecret.
  qRegisterMetaType<EMailSecretPtr>("EMailSecretPtr");
  qRegisterMetaType<MailError>("MailError");
  qRegisterMetaType<EMailFolderInfo>("EMailFolderInfo");
  qRegisterMetaType<QList<EMailFolderInfo>>("QList<EMailFolderInfo>");
  qRegisterMetaType<EMailMessageSummary>("EMailMessageSummary");
  qRegisterMetaType<EMailMessagePage>("EMailMessagePage");
  qRegisterMetaType<EMailOutgoingMessage>("EMailOutgoingMessage");
  qRegisterMetaType<EMailSendReceipt>("EMailSendReceipt");
  // Crosses a thread boundary as a queued signal argument, so it has to be
  // known to the metatype system by name before the first one is emitted.
  qRegisterMetaType<MailSentSaveOutcome>("MailSentSaveOutcome");

  // vmime's platform handler is assigned lazily with no synchronisation, so
  // two worker threads racing their first connection could construct it twice.
  // Touching it once here, on the thread that loads the module, settles it
  // before any worker exists.
  vmime::platform::getHandler();

  const auto keywords =
      QStringList{GC_TR("mail"), GC_TR("email"),   GC_TR("imap"),
                  GC_TR("smtp"), GC_TR("account"), GC_TR("send")}
          .join('\n');
  GFUIRegisterSettingsPage(DUP(kMailSettingsPageId), DUP("features"),
                           DUP(GC_TR("Mail Accounts")), QDUP(keywords),
                           EMailAccountSettingsPageFactory, nullptr);

  // An imported key changes what an already-open message can be told about
  // itself, so the views have to hear about it.
  LISTEN("KEY_DATABASE_REFRESH_DONE");
  return 0;
}

auto GFActiveModule() -> int { return 0; }

auto GFDeactivateModule() -> int {
  // A factory pointing into an unloaded shared object would crash the next
  // time an e-mail tab is opened.
  GFUIUnregisterTabPageView(DUP("EMAIL"));
  GFUIUnregisterSettingsPage(DUP(kMailSettingsPageId));
  return 0;
}

auto GFUnregisterModule() -> int {
  MLogDebug("email module unregistering...");

  return 0;
}

namespace {

// The preflight dialog: what the user should know before this message leaves.
//
// Shown only when there is something to say, and it never refuses the save --
// the decision is the user's, and a check that blocks gets worked around
// rather than read. Returns false when the user chooses not to write the file.
auto ConfirmExport(QWidget* parent, const QByteArray& source) -> bool {
  vmime::shared_ptr<vmime::message> parsed;
  if (!CheckIfEMLMessage(source, parsed)) return true;

  EMailPart root;
  QList<EMailSignatureRegion> regions;
  if (ParseMimeTree(parsed, source, root, regions) != 0) return true;

  EMailMetaData meta;
  GetEMLMetaData(parsed, meta);

  const auto findings = PreflightMessage(meta, root, regions, {});

  QStringList risks;
  QStringList notes;
  for (const auto& finding : findings) {
    const auto line = QString("%1 - %2").arg(finding.title, finding.detail);
    if (finding.level == EMailFindingLevel::kRISK) {
      risks.append(line);
    } else if (finding.level == EMailFindingLevel::kWARN) {
      notes.append(line);
    }
  }

  // Notes alone are not worth interrupting a save for; the Security tab
  // already carries them.
  if (risks.isEmpty()) return true;

  QMessageBox box(parent);
  box.setIcon(QMessageBox::Warning);
  box.setWindowTitle(
      QApplication::translate("EMailModule", "Check before exporting"));
  box.setText(QApplication::translate(
      "EMailModule",
      "Something about this message is worth checking before you save it."));
  box.setInformativeText(risks.join("\n\n"));
  if (!notes.isEmpty()) box.setDetailedText(notes.join("\n\n"));
  box.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
  box.setDefaultButton(QMessageBox::Cancel);

  return box.exec() == QMessageBox::Save;
}

// Where a Save dialog should open. Falls back to the home directory only if
// the host cannot answer, which it always can in practice.
auto default_save_dir() -> QString {
  auto path = UnStrDup(GFUIDefaultUserFilePath());
  return path.isEmpty() ? QDir::homePath() : path;
}

// Ceiling on the size of an .eml this module will open. Generous, because a
// message with attachments is legitimately large; the protection against a
// hostile *shape* is EMailParseLimits, not this number.
constexpr qint64 kMaxEMLFileSize = kMailMaxMessageSize;

/// Identifier of the settings page this module owns.
constexpr auto kMailSettingsPageId =
    "com.bktus.gpgfrontend.module.email.accounts";

auto ErrorHelper(int ret, const QString& err) -> QString {
  if (ret == -2) {
    auto info =
        QApplication::translate(
            "EMailModule",
            "# EML Data Error\n\n"
            "The provided EML data does not conform to RFC 3156 standards "
            "and cannot be processed.\n\n"
            "**Details:** %1\n\n"
            "### What is EML Data?\n"
            "EML is a file format for representing email messages, "
            "typically "
            "including headers, body text, attachments, and metadata. "
            "Complete and properly structured EML data is required for "
            "validation.\n\n"
            "### Suggested Solutions\n"
            "1. Verify the EML data is complete and matches the structure "
            "outlined in RFC 3156.\n"
            "2. Refer to the official documentation for the EML structure: "
            "%2\n\n"
            "After correcting the EML data, try the operation again.")
            .arg(err)
            .arg("https://www.rfc-editor.org/rfc/rfc3156.txt");

    return info;
  }

  auto error_message =
      QApplication::translate(
          "EMailModule",
          "# Email Operation Error\n\n"
          "An error occurred during the email operation. The process "
          "could not be completed.\n\n"
          "**Details:**\n"
          "- **Error Code:** %1\n"
          "- **Error Message:** %2\n\n"
          "### Possible Causes\n"
          "1. The email data may be incomplete or corrupted.\n"
          "2. The selected GPG key does not have the necessary "
          "permissions.\n"
          "3. Issues in the GPG environment or configuration.\n\n"
          "### Suggested Solutions\n"
          "1. Ensure the email data is complete and follows the expected "
          "format.\n"
          "2. Verify the GPG key has the required access permissions.\n"
          "3. Check your GPG environment and configuration settings.\n"
          "4. Review the error details above or application logs for "
          "further troubleshooting.\n\n"
          "If the issue persists, consider seeking technical support or "
          "consulting the documentation.")
          .arg(ret)
          .arg(err);

  return error_message;
}

}  // namespace

REGISTER_EVENT_HANDLER(KEY_DATABASE_REFRESH_DONE,
                       [](const MEvent& event) -> int {
                         // A verification that reported a missing key stops
                         // being true once that key is imported; open messages
                         // work their signatures out again rather than keeping
                         // the stale verdict.
                         EMailNotifyKeyringChanged();
                         CB_SUCC(event);
                       });

namespace {

/**
 * @brief Open @p raw as a new e-mail tab, exactly as a file would be.
 *
 * The only thing the IMAP side is allowed to do with what it fetched. Nothing
 * about the account, folder or UID comes with it, so an imported message is
 * indistinguishable from the same bytes opened from disk -- which is the whole
 * point of treating IMAP as a file picker.
 *
 * Must run on the GUI thread.
 */
auto OpenRawAsEMailTab(const QByteArray& raw, const QString& title) -> bool {
  auto* edit = GFUIGetGUIObjectAs<QWidget>("main_window_edit");
  if (edit == nullptr) {
    LOG_ERROR("main_window_edit handle invalid or not QWidget");
    return false;
  }

  QWidget* page = nullptr;
  auto ok = QMetaObject::invokeMethod(
      edit, "SlotNewCustomTab", Qt::DirectConnection,
      Q_RETURN_ARG(QWidget*, page), Q_ARG(QString, "email"),
      Q_ARG(QString, title), Q_ARG(QIcon, QIcon(":/icons/email.png")),
      Q_ARG(QString, ":/icons/email.png"));

  if (!ok || page == nullptr) {
    LOG_ERROR("create new email tab page failed");
    return false;
  }

  // Bytes, not text: the page records which line endings the message arrived
  // with, and a PGP/MIME signature covers the exact octets. Going through
  // setPlainText would destroy every signature before anything could check
  // one.
  if (!QMetaObject::invokeMethod(page, "SetContentFromBytes",
                                 Qt::DirectConnection,
                                 Q_ARG(QByteArray, raw))) {
    LOG_ERROR("host does not support SetContentFromBytes");
    return false;
  }
  return true;
}

/// A tab title for an imported message: its subject, or a neutral fallback.
///
/// Sanitized, because this title also becomes the suggested file name when the
/// tab is saved, and the subject is written by whoever sent the message -- a
/// subject containing a path separator would otherwise produce a name that
/// resolves somewhere else entirely.
auto TitleForImported(const QByteArray& raw) -> QString {
  vmime::shared_ptr<vmime::message> parsed;
  if (CheckIfEMLMessage(raw, parsed)) {
    EMailMetaData meta;
    GetEMLMetaData(parsed, meta);
    const auto subject = meta.subject.trimmed();
    if (!subject.isEmpty()) return SuggestedEMailFileName(subject);
  }
  return "imported.eml";
}

}  // namespace

REGISTER_EVENT_HANDLER(MAINWINDOW_MENU_MOUNTED, [](const MEvent& event) -> int {
  LOG_DEBUG("main window menu mounted event: processing");

  if (!event.contains("main_window")) {
    LOG_DEBUG("main window menu mounted event: no main_window found");
    CB_ERR(event, -1, "no main_window found");
  }

  auto* main_window = GFUIGetGUIObjectAs<QMainWindow>(event["main_window"]);
  if (!main_window) {
    LOG_ERROR(
        "main window menu mounted: main_window handle invalid or not "
        "QMainWindow");
    CB_ERR(event, -1, "main_window handle invalid or not QMainWindow");
  }

  if (!event.contains("import_key_menu")) {
    LOG_DEBUG("main window menu mounted event: no import_key_menu found");
    CB_ERR(event, -1, "no import_key_menu found");
  }

  // Importing over the network is a different kind of act from opening a new
  // editor, so it belongs in Advanced rather than beside "Mail Editor" in the
  // workspace menu.
  auto* advance_menu = GFUIGetGUIObjectAs<QMenu>(event["advance_menu"]);
  if (advance_menu == nullptr) {
    LOG_ERROR("advance_menu handle invalid or not QMenu");
  }

  auto* workspace_menu =
      GFUIGetGUIObjectAs<QMenu>(event["file_workspace_menu"]);
  if (!workspace_menu) {
    LOG_ERROR(
        "main window menu mounted: workspace_menu handle invalid or not "
        "QMenu");
    CB_ERR(event, -1, "workspace_menu handle invalid or not QMenu");
  }

  LOG_DEBUG("adding key server sync actions to import key menu");

  auto* edit = GFUIGetGUIObjectAs<QWidget>("main_window_edit");
  if (!edit) {
    LOG_ERROR(
        "main window menu mounted: main_window_edit handle invalid or not "
        "QWidget");
    CB_ERR(event, -1, "main_window_edit handle invalid or not QWidget");
  }

  QMetaObject::invokeMethod(
      QApplication::instance(),
      [&, advance_menu]() -> void {
        QWidget* parent =
            qobject_cast<QWidget*>(static_cast<QObject*>(main_window));
        auto* action = new QAction(
            QCoreApplication::translate("GTrC", "Mail Editor"), parent);

        action->setToolTip(QCoreApplication::translate(
            "GTrC", "Open a new text editor for email."));
        action->setIcon(QIcon(":/icons/email.png"));
        bool ok =
            QObject::connect(action, &QAction::triggered, parent, [edit]() {
              QMetaObject::invokeMethod(
                  edit, "SlotNewCustomTab", Qt::DirectConnection,
                  Q_ARG(QString, "email"), Q_ARG(QString, "untitled.eml"),
                  Q_ARG(QIcon, QIcon(":/icons/email.png")),
                  Q_ARG(QString, ":/icons/email.png"));
            });

        if (!ok) {
          LOG_ERROR("connecting mail editor action failed");
        }

        workspace_menu->addAction(action);

        // Import from IMAP. Shown only when an account could actually be
        // browsed: an entry that always fails teaches people to ignore it.
        // Named and dressed like its neighbours in this menu ("Open Smart
        // Card Controller", "Open Module Controller"): it opens a controller
        // rather than prompting for anything, so it takes no ellipsis.
        auto* import_action = new QAction(
            QCoreApplication::translate("GTrC", "Open IMAP Controller"),
            parent);
        import_action->setIcon(QIcon(":/icons/receive_email.png"));
        import_action->setToolTip(
            QCoreApplication::translate("GTrC", "Open IMAP Controller Dialog"));
        QObject::connect(
            import_action, &QAction::triggered, parent, [parent]() {
              if (!EMailImapController::HasUsableAccount()) {
                QMessageBox::information(
                    parent,
                    QCoreApplication::translate("GTrC", "No mail account"),
                    QCoreApplication::translate(
                        "GTrC",
                        "Configure a mail account with IMAP enabled in "
                        "Settings first."));
                return;
              }

              auto* controller = new EMailImapController(parent);
              controller->setAttribute(Qt::WA_DeleteOnClose);

              // The narrow boundary: raw bytes in, a tab out. The controller
              // never touches the tab widget itself.
              QObject::connect(controller,
                               &EMailImapController::SignalMessageChosen,
                               parent, [](const QByteArray& raw) {
                                 OpenRawAsEMailTab(raw, TitleForImported(raw));
                               });
              controller->show();
            });
        if (advance_menu != nullptr) advance_menu->addAction(import_action);
      },
      Qt::BlockingQueuedConnection);
  CB_SUCC(event);
});

namespace {

auto DoVerifyEMLData(int channel, const QByteArray& data, const MEvent& event,
                     int& result_status, QString& result_detail,
                     QString& result_cards, QString& error_string,
                     EMailMetaData& meta_data) -> int {
  gpg_error_t err;
  QString capsule_id;
  auto ret =
      VerifyEMLData(channel, data, meta_data, error_string, err, capsule_id);
  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, error_string)},
       });
    return ret;
  }

  QByteArray info_json;
  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, not the plain one: the structured description
  // and details are what let a FAILURE explain itself, and without
  // them the board can only fall back to "<operation> failed."
  result_status = GFAnalyseVerifyResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // The operation failed, and the ANALYSIS of that failure is exactly what
    // the user needs -- which key was wanted, what the engine said. Those
    // cards were just built above; dropping them here is what left a failed
    // decrypt showing raw report text where every other outcome shows a
    // structured card.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Verify E-Mail"), {},
                result_cards, info_json)},
       });
    return ret;
  }

  if (ret != kSUCCESS) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, error_string)},
       });
    return ret;
  }
  return kSUCCESS;
}
}  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_VERIFY, [](const MEvent& event) -> int {
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["data"].isEmpty()) CB_ERR(event, -1, "data is empty");

      auto channel = event.value("channel", "0").toInt();
      auto data = QByteArray::fromBase64(QString(event["data"]).toLatin1());

      EMailMetaData meta_data;
      QString error_string;
      int result_status = 0;
      QString result_detail;
      QString result_cards;
      if (DoVerifyEMLData(channel, data, event, result_status, result_detail,
                          result_cards, error_string, meta_data) != kSUCCESS) {
        return -1;
      }

      QString email_info;
      email_info.append("# E-Mail Information\n\n");
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "From"))
                            .arg(meta_data.from));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "To"))
                            .arg(meta_data.to.join("; ")));
      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate("EMailModule", "Subject"))
              .arg(meta_data.subject));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "CC"))
                            .arg(meta_data.cc.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "BCC"))
                            .arg(meta_data.bcc_header.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "Date"))
                            .arg(QLocale().toString(meta_data.datetime)));

      email_info.append("\n");

      email_info.append("# OpenPGP Information\n\n");

      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate(
                  "EMailModule", "Digest of Signed MIME Entity (SHA-256)"))
              .arg(meta_data.signed_entity_digest));
      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate("EMailModule",
                                           "Declared Signature Hash (micalg)"))
              .arg(meta_data.micalg));

      // Without this, a message whose line endings were rewritten after
      // signing reads exactly like a forged one, and the user has no way to
      // tell the difference or to know that importing a key cannot help.
      if (meta_data.signed_entity_non_canonical) {
        email_info.append(QString("- %1\n").arg(QApplication::translate(
            "EMailModule",
            "**Note**: the signed part is not in canonical form, "
            "because its line endings are not CRLF. Something rewrote "
            "this message after it was signed, which is usually a "
            "program that changed line endings while saving or "
            "copying it. A signature cannot verify against these "
            "bytes, and importing the sender's key will not change "
            "that.")));
      }

      email_info.append("\n");

      email_info.append("#" + result_detail + "\n");

      const auto result_cards_param = BuildResultCardsParam(
          QApplication::translate("EMailModule", "Verify E-Mail"),
          BuildReadMetaCards(meta_data, true), result_cards);

      // callback
      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"result_status", QString::number(result_status)},
             {"result", email_info},
             {"result_cards", result_cards_param},
         });
      return 0;
    });

namespace {

auto DoDecryptEMLData(int channel, const QByteArray& data, const MEvent& event,
                      int& result_status, QString& result_detail,
                      QString& result_cards, QByteArray& eml_data,
                      EMailMetaData& meta_data, QByteArray& decrypt_info_json)
    -> int {
  gpgme_error_t err;
  QString capsule_id;
  auto ret =
      DecryptEMLData(channel, data, meta_data, eml_data, err, capsule_id);

  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, because the recipient cross-check needs the structured
  // recipients rather than the rendered report. The capsule is consumed by
  // whichever analyse call touches it, so everything has to come from this one.
  result_status = GFAnalyseDecryptResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  decrypt_info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // decrypt failed. The analysis cards built above travel with it: a failure
    // is the outcome that most needs explaining, not the one to explain least.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", data},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Decrypt E-Mail"), {},
                result_cards, decrypt_info_json)},
       });
    return ret;
  }

  if (ret != kSUCCESS) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  return 0;
}

}  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_DECRYPT, [](const MEvent& event) -> int {
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["data"].isEmpty()) CB_ERR(event, -1, "data is empty");

      auto channel = event.value("channel", "0").toInt();
      auto data = QByteArray::fromBase64(QString(event["data"]).toLatin1());

      QByteArray eml_data;
      int result_status = 0;
      QString result_detail;
      QString result_cards;
      EMailMetaData meta_data;
      QByteArray decrypt_info_json;
      if (DoDecryptEMLData(channel, data, event, result_status, result_detail,
                           result_cards, eml_data, meta_data,
                           decrypt_info_json) != kSUCCESS) {
        return -1;
      }

      QString email_info;
      email_info.append("# E-Mail Information\n\n");
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "From"))
                            .arg(meta_data.from));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "To"))
                            .arg(meta_data.to.join("; ")));
      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate("EMailModule", "Subject"))
              .arg(meta_data.subject));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "CC"))
                            .arg(meta_data.cc.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "BCC"))
                            .arg(meta_data.bcc_header.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "Date"))
                            .arg(QLocale().toString(meta_data.datetime)));

      email_info.append("\n");

      email_info.append("# OpenPGP Information\n\n");
      email_info.append("#" + result_detail + "\n");

      auto decrypt_meta_cards = BuildReadMetaCards(meta_data, false);
      const auto recipient_card =
          BuildRecipientCheckCard(meta_data, decrypt_info_json);
      if (!recipient_card.isEmpty()) decrypt_meta_cards.append(recipient_card);

      const auto result_cards_param = BuildResultCardsParam(
          QApplication::translate("EMailModule", "Decrypt E-Mail"),
          decrypt_meta_cards, result_cards);

      // callback
      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"data", eml_data},
             {"result_status", QString::number(result_status)},
             {"result", email_info},
             {"result_cards", result_cards_param},
         });
      return kSUCCESS;
    });

namespace {

auto DoSignEMLData(int channel, const QString& sign_key,
                   vmime::shared_ptr<vmime::message>& message,
                   const QByteArray& body_data, const MEvent& event,
                   int& result_status, QString& result_detail,
                   QString& result_cards, QByteArray& eml_data) -> int {
  EMailMetaData meta_data;
  auto ret = GetEMLMetaData(message, meta_data);

  if (ret != 0) {
    CB_ERR(event, -1, "Get MetaData From EML Data Failed");
  }

  gpg_error_t err;
  QString capsule_id;
  ret = SignEMLData(channel, sign_key, message, eml_data, err, capsule_id);

  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  QByteArray info_json;
  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, not the plain one: the structured description
  // and details are what let a FAILURE explain itself, and without
  // them the board can only fall back to "<operation> failed."
  result_status = GFAnalyseSignResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // decrypt failed. The analysis cards built above travel with it: a failure
    // is the outcome that most needs explaining, not the one to explain least.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Sign E-Mail"), {},
                result_cards, info_json)},
       });
    return ret;
  }

  if (ret != kSUCCESS) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  return kSUCCESS;
}

auto DoSignPlainText(int channel, const QString& sign_key,
                     const EMailMetaData& meta_data,
                     const QByteArray& body_data, const MEvent& event,
                     int& result_status, QString& result_detail,
                     QString& result_cards, QByteArray& eml_data) -> int {
  gpg_error_t err;
  QString capsule_id;

  auto ret = SignPlainText(channel, sign_key, meta_data, body_data, eml_data,
                           err, capsule_id);
  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  QByteArray info_json;
  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, not the plain one: the structured description
  // and details are what let a FAILURE explain itself, and without
  // them the board can only fall back to "<operation> failed."
  result_status = GFAnalyseSignResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // decrypt failed. The analysis cards built above travel with it: a failure
    // is the outcome that most needs explaining, not the one to explain least.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Sign E-Mail"), {},
                result_cards, info_json)},
       });
    return ret;
  }

  if (ret != kSUCCESS) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", body_data},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  return kSUCCESS;
}

}  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_SIGN, [](const MEvent& event) -> int {
      if (event["body_data"].isEmpty()) CB_ERR(event, -1, "body_data is empty");
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["sign_key"].isEmpty()) CB_ERR(event, -1, "sign_key is empty");

      auto channel = event.value("channel", "0").toInt();
      auto sign_key = event.value("sign_key", "");

      FLOG_DEBUG("eml sign key: %1", sign_key);

      auto body_data =
          QByteArray::fromBase64(QString(event["body_data"]).toLatin1());

      vmime::shared_ptr<vmime::message> message;
      if (CheckIfEMLMessage(body_data, message)) {
        int result_status = 0;
        QString result_detail;
        QString result_cards;
        QByteArray eml_data;
        if (DoSignEMLData(channel, sign_key, message, body_data, event,
                          result_status, result_detail, result_cards,
                          eml_data) != kSUCCESS) {
          return -1;
        }

        CB(event, GFGetModuleID(),
           {
               {"ret", QString::number(0)},
               {"data", eml_data},
               {"result_status", QString::number(result_status)},
               {"result", result_detail},
               {"result_cards",
                BuildResultCardsParam(
                    QApplication::translate("EMailModule", "Sign E-Mail"), {},
                    result_cards)},
           });
        return 0;
      }

      // Not a message yet: wrap the text in an envelope derived from the
      // signing key rather than stopping to ask for one.
      const auto meta_data = EnvelopeFromKeys(channel, sign_key, {});

      int result_status = 0;
      QString result_detail;
      QString result_cards;
      QByteArray eml_data;
      if (DoSignPlainText(channel, sign_key, meta_data, body_data, event,
                          result_status, result_detail, result_cards,
                          eml_data) != kSUCCESS) {
        return -1;
      }

      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"data", eml_data},
             {"result_status", QString::number(result_status)},
             {"result", result_detail},
             {"result_cards",
              BuildResultCardsParam(
                  QApplication::translate("EMailModule", "Sign E-Mail"),
                  {BuildEMailHeaderCard(meta_data)}, result_cards)},
         });
      return 0;
    });

namespace {

auto DoEncryptEMLData(int channel, const QStringList& encrypt_keys,
                      const vmime::shared_ptr<vmime::message>& message,
                      const QByteArray& body_data, const MEvent& event,
                      int& result_status, QString& result_detail,
                      QString& result_cards, QByteArray& eml_data) -> int {
  gpgme_error_t err;
  QString capsule_id;
  auto ret = EncryptEMLData(channel, encrypt_keys, message, body_data, eml_data,
                            err, capsule_id);

  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", QString::fromLatin1(body_data.toBase64())},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  QByteArray info_json;
  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, not the plain one: the structured description
  // and details are what let a FAILURE explain itself, and without
  // them the board can only fall back to "<operation> failed."
  result_status = GFAnalyseEncryptResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // encrypt failed. The analysis cards built above travel with it: a failure
    // is the outcome that most needs explaining, not the one to explain least.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", QString::fromLatin1(body_data.toBase64())},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Encrypt E-Mail"), {},
                result_cards, info_json)},
       });
    return ret;
  }

  return kSUCCESS;
}

auto DoEncryptPlainText(int channel, const QStringList& encrypt_keys,
                        const EMailMetaData& meta_data,
                        const QByteArray& body_data, const MEvent& event,
                        int& result_status, QString& result_detail,
                        QString& result_cards, QByteArray& eml_data) -> int {
  gpgme_error_t err;
  QString capsule_id;
  QByteArray plain_text_eml_data;
  auto ret = BuildPlainTextEML(meta_data, body_data, plain_text_eml_data);

  if (ret != kSUCCESS) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", QString::fromLatin1(body_data.toBase64())},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  ret = EncryptPlainText(channel, encrypt_keys, meta_data, plain_text_eml_data,
                         eml_data, err, capsule_id);

  if (ret == kFAILED || ret == kEML_FAILED) {
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", QString::fromLatin1(body_data.toBase64())},
           {"result_status", QString::number(-1)},
           {"result", ErrorHelper(ret, QString::fromUtf8(eml_data))},
       });
    return ret;
  }

  QByteArray info_json;
  const char* tmp = nullptr;
  const char* cards_tmp = nullptr;
  const char* info_tmp = nullptr;
  // The Info variant, not the plain one: the structured description
  // and details are what let a FAILURE explain itself, and without
  // them the board can only fall back to "<operation> failed."
  result_status = GFAnalyseEncryptResultInfoByCapsule(
      channel, err, QDUP(capsule_id), &tmp, &cards_tmp, &info_tmp);
  result_detail = UnStrDup(tmp);
  result_cards = UnStrDup(cards_tmp);
  info_json = UnStrDup(info_tmp).toUtf8();

  if (ret == kGPG_FAILED) {
    // encrypt failed. The analysis cards built above travel with it: a failure
    // is the outcome that most needs explaining, not the one to explain least.
    CB(event, GFGetModuleID(),
       {
           {"ret", QString::number(0)},
           {"data", QString::fromLatin1(body_data.toBase64())},
           {"result_status", QString::number(result_status)},
           {"result", result_detail},
           {"result_cards",
            BuildResultCardsParam(
                QApplication::translate("EMailModule", "Encrypt E-Mail"), {},
                result_cards, info_json)},
       });
    return ret;
  }

  return kSUCCESS;
}
};  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_ENCRYPT, [](const MEvent& event) -> int {
      if (event["body_data"].isEmpty()) CB_ERR(event, -1, "body_data is empty");
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["encrypt_keys"].isEmpty())
        CB_ERR(event, -1, "encrypt_keys is empty");

      auto channel = event.value("channel", "0").toInt();
      auto encrypt_keys = event.value("encrypt_keys", "").split(';');

      FLOG_DEBUG("eml encrypt keys: %1", encrypt_keys.join(';'));

      auto body_data =
          QByteArray::fromBase64(QString(event["body_data"]).toLatin1());

      vmime::shared_ptr<vmime::message> message;
      if (CheckIfEMLMessage(body_data, message)) {
        QByteArray eml_data;
        int result_status = 0;
        QString result_detail;
        QString result_cards;
        if (DoEncryptEMLData(channel, encrypt_keys, message, body_data, event,
                             result_status, result_detail, result_cards,
                             eml_data) != kSUCCESS) {
          return -1;
        }

        CB(event, GFGetModuleID(),
           {
               {"ret", QString::number(0)},
               {"data", eml_data},
               {"result", result_detail},
               {"result_status", QString::number(result_status)},
               {"result_cards",
                BuildResultCardsParam(
                    QApplication::translate("EMailModule", "Encrypt E-Mail"),
                    BuildRecipientCards(channel, encrypt_keys), result_cards)},
           });
        return 0;
      }

      // Not a message yet: address it to the keys the user picked to encrypt
      // to, rather than stopping to ask for addresses they have just chosen.
      const auto meta_data = EnvelopeFromKeys(channel, {}, encrypt_keys);

      QByteArray eml_data;
      int result_status = 0;
      QString result_detail;
      QString result_cards;
      if (DoEncryptPlainText(channel, encrypt_keys, meta_data, body_data, event,
                             result_status, result_detail, result_cards,
                             eml_data) != kSUCCESS) {
        return -1;
      }

      auto meta_cards = BuildRecipientCards(channel, encrypt_keys);
      meta_cards.prepend(BuildEMailHeaderCard(meta_data));
      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"data", eml_data},
             {"result", result_detail},
             {"result_status", QString::number(result_status)},
             {"result_cards",
              BuildResultCardsParam(
                  QApplication::translate("EMailModule", "Encrypt E-Mail"),
                  meta_cards, result_cards)},
         });
      return 0;
    });

namespace {

auto DoEncryptSignEMLData(int channel, const QStringList& encrypt_keys,
                          const QString& sign_key,
                          vmime::shared_ptr<vmime::message>& message,
                          QByteArray& body_data, const MEvent& event,
                          int& result_status, QString& result_detail,
                          QString& result_cards, QByteArray& eml_data) -> int {
  QString sign_cards;
  if (DoSignEMLData(channel, sign_key, message, body_data, event, result_status,
                    result_detail, sign_cards, eml_data) != kSUCCESS) {
    return -1;
  }

  // UTF-8, not Latin-1: these are the bytes the signature was just taken
  // over, and they are about to be re-parsed and encrypted. Latin-1 collapses
  // every two-byte sequence to one byte and replaces anything above U+00FF, so
  // the recipient would verify a different message than the one that was
  // signed. The module converts through UTF-8 everywhere else -- Q_SC, QDUP
  // and UDUP are all UTF-8 -- and corpus fixture 18 pins it.
  body_data = eml_data;
  eml_data.clear();

  int t_result_status = 0;
  QString t_result_detail;
  QString encrypt_cards;

  vmime::shared_ptr<vmime::message> signed_message;
  bool r = CheckIfEMLMessage(body_data, signed_message);
  if (!r) {
    CB_ERR(event, -1, "Parse Signed Message Failed");
  }

  auto ret = DoEncryptEMLData(channel, encrypt_keys, signed_message, body_data,
                              event, t_result_status, t_result_detail,
                              encrypt_cards, eml_data);

  // The callee has already reported every failure of its own through CB, and
  // leaves t_result_status untouched on the earliest of those paths.
  // Aggregating there would read an uninitialised value and overwrite a status
  // that has already been sent.
  if (ret != kSUCCESS) return ret;

  result_status = WorseStatus(t_result_status, result_status);
  result_detail = t_result_detail + "\n\n" + result_detail;
  result_cards = MergeCardArrays(encrypt_cards, sign_cards);
  return ret;
}

auto DoEncryptSignPlainText(int channel, const QStringList& encrypt_keys,
                            const QString& sign_key,
                            const EMailMetaData& meta_data,
                            QByteArray& body_data, const MEvent& event,
                            int& result_status, QString& result_detail,
                            QString& result_cards, QByteArray& eml_data)
    -> int {
  QString sign_cards;
  if (DoSignPlainText(channel, sign_key, meta_data, body_data, event,
                      result_status, result_detail, sign_cards,
                      eml_data) != kSUCCESS) {
    return -1;
  }

  // UTF-8, not Latin-1: these are the bytes the signature was just taken
  // over, and they are about to be re-parsed and encrypted. Latin-1 collapses
  // every two-byte sequence to one byte and replaces anything above U+00FF, so
  // the recipient would verify a different message than the one that was
  // signed. The module converts through UTF-8 everywhere else -- Q_SC, QDUP
  // and UDUP are all UTF-8 -- and corpus fixture 18 pins it.
  body_data = eml_data;
  eml_data.clear();

  int t_result_status = 0;
  QString t_result_detail;
  QString encrypt_cards;

  vmime::shared_ptr<vmime::message> signed_message;
  bool r = CheckIfEMLMessage(body_data, signed_message);
  if (!r) {
    CB_ERR(event, -1, "Parse Signed Message Failed");
  }

  auto ret = DoEncryptEMLData(channel, encrypt_keys, signed_message, body_data,
                              event, t_result_status, t_result_detail,
                              encrypt_cards, eml_data);

  // The callee has already reported every failure of its own through CB, and
  // leaves t_result_status untouched on the earliest of those paths.
  // Aggregating there would read an uninitialised value and overwrite a status
  // that has already been sent.
  if (ret != kSUCCESS) return ret;

  result_status = WorseStatus(t_result_status, result_status);
  result_detail = t_result_detail + "\n" + result_detail;
  result_cards = MergeCardArrays(encrypt_cards, sign_cards);
  return ret;
}

}  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_ENCRYPT_SIGN, [](const MEvent& event) -> int {
      if (event["body_data"].isEmpty()) CB_ERR(event, -1, "body_data is empty");
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["encrypt_keys"].isEmpty())
        CB_ERR(event, -1, "encrypt_keys is empty");
      if (event["sign_key"].isEmpty()) CB_ERR(event, -1, "sign_key is empty");

      auto channel = event.value("channel", "0").toInt();
      auto sign_key = event.value("sign_key", "");
      auto encrypt_keys = event.value("encrypt_keys", "").split(';');

      FLOG_DEBUG("eml encrypt keys: %1", encrypt_keys.join(';'));

      auto body_data =
          QByteArray::fromBase64(QString(event["body_data"]).toLatin1());

      vmime::shared_ptr<vmime::message> message;
      if (CheckIfEMLMessage(body_data, message)) {
        QByteArray eml_data;
        int result_status = 0;
        QString result_detail;
        QString result_cards;
        if (DoEncryptSignEMLData(channel, encrypt_keys, sign_key, message,
                                 body_data, event, result_status, result_detail,
                                 result_cards, eml_data) != kSUCCESS) {
          return -1;
        }
        CB(event, GFGetModuleID(),
           {
               {"ret", QString::number(0)},
               {"data", eml_data},
               {"result", result_detail},
               {"result_status", QString::number(result_status)},
               {"result_cards",
                BuildResultCardsParam(
                    QApplication::translate("EMailModule",
                                            "Encrypt and Sign E-Mail"),
                    BuildRecipientCards(channel, encrypt_keys), result_cards)},
           });
        return 0;
      }

      // Not a message yet: address it from the signing key to the encryption
      // keys, rather than stopping to ask for what the key list already says.
      const auto meta_data = EnvelopeFromKeys(channel, sign_key, encrypt_keys);

      QByteArray eml_data;
      int result_status = 0;
      QString result_detail;
      QString result_cards;
      QByteArray body_data_copy = body_data;

      if (DoEncryptSignPlainText(channel, encrypt_keys, sign_key, meta_data,
                                 body_data_copy, event, result_status,
                                 result_detail, result_cards,
                                 eml_data) != kSUCCESS) {
        return -1;
      }

      auto meta_cards = BuildRecipientCards(channel, encrypt_keys);
      meta_cards.prepend(BuildEMailHeaderCard(meta_data));
      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"data", eml_data},
             {"result", result_detail},
             {"result_status", QString::number(result_status)},
             {"result_cards", BuildResultCardsParam(
                                  QApplication::translate(
                                      "EMailModule", "Encrypt and Sign E-Mail"),
                                  meta_cards, result_cards)},
         });
      return 0;
    });

namespace {

auto DoDecryptVerifyEMLData(int channel, const QByteArray& data,
                            const MEvent& event, int& result_status,
                            QString& result_detail, QString& result_cards,
                            QByteArray& eml_data, QString& error_string,
                            EMailMetaData& meta_data,
                            QByteArray& decrypt_info_json) -> int {
  QString decrypt_cards;
  if (DoDecryptEMLData(channel, data, event, result_status, result_detail,
                       decrypt_cards, eml_data, meta_data,
                       decrypt_info_json) != kSUCCESS) {
    return -1;
  }

  int t_result_status = 0;
  QString t_result_detail;
  QString verify_cards;

  // UTF-8, not Latin-1: this is the decrypted plaintext and the signature
  // inside it is checked against these exact bytes. See DoEncryptSignEMLData.
  if (DoVerifyEMLData(channel, eml_data, event, t_result_status,
                      t_result_detail, verify_cards, error_string,
                      meta_data) != kSUCCESS) {
    return -1;
  }

  result_status = WorseStatus(t_result_status, result_status);
  result_detail = t_result_detail + "\n" + result_detail;
  result_cards = MergeCardArrays(verify_cards, decrypt_cards);

  return kSUCCESS;
}
}  // namespace

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_DECRYPT_VERIFY, [](const MEvent& event) -> int {
      if (event["channel"].isEmpty()) CB_ERR(event, -1, "channel is empty");
      if (event["data"].isEmpty()) CB_ERR(event, -1, "data is empty");

      auto channel = event.value("channel", "0").toInt();
      auto data = QByteArray::fromBase64(QString(event["data"]).toLatin1());

      auto body_data =
          QByteArray::fromBase64(QString(event["body_data"]).toLatin1());

      QByteArray eml_data;
      EMailMetaData meta_data;
      QString error_string;
      int result_status = 0;
      QString result_detail;
      QString result_cards;

      QByteArray decrypt_info_json;
      if (DoDecryptVerifyEMLData(channel, data, event, result_status,
                                 result_detail, result_cards, eml_data,
                                 error_string, meta_data,
                                 decrypt_info_json) != kSUCCESS) {
        return -1;
      }

      QString email_info;
      email_info.append("# E-Mail Information\n\n");
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "From"))
                            .arg(meta_data.from));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "To"))
                            .arg(meta_data.to.join("; ")));
      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate("EMailModule", "Subject"))
              .arg(meta_data.subject));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "CC"))
                            .arg(meta_data.cc.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "BCC"))
                            .arg(meta_data.bcc_header.join("; ")));
      email_info.append(QString("- %1: %2\n")
                            .arg(QApplication::translate("EMailModule", "Date"))
                            .arg(QLocale().toString(meta_data.datetime)));

      email_info.append("\n");

      email_info.append("# OpenPGP Information\n\n");

      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate(
                  "EMailModule", "Digest of Signed MIME Entity (SHA-256)"))
              .arg(meta_data.signed_entity_digest));
      email_info.append(
          QString("- %1: %2\n")
              .arg(QApplication::translate("EMailModule",
                                           "Declared Signature Hash (micalg)"))
              .arg(meta_data.micalg));

      // Without this, a message whose line endings were rewritten after
      // signing reads exactly like a forged one, and the user has no way to
      // tell the difference or to know that importing a key cannot help.
      if (meta_data.signed_entity_non_canonical) {
        email_info.append(QString("- %1\n").arg(QApplication::translate(
            "EMailModule",
            "**Note**: the signed part is not in canonical form, "
            "because its line endings are not CRLF. Something rewrote "
            "this message after it was signed, which is usually a "
            "program that changed line endings while saving or "
            "copying it. A signature cannot verify against these "
            "bytes, and importing the sender's key will not change "
            "that.")));
      }

      email_info.append("\n");

      email_info.append("#" + result_detail + "\n");

      auto dv_meta_cards = BuildReadMetaCards(meta_data, true);
      const auto dv_recipient_card =
          BuildRecipientCheckCard(meta_data, decrypt_info_json);
      if (!dv_recipient_card.isEmpty()) dv_meta_cards.append(dv_recipient_card);

      const auto result_cards_param = BuildResultCardsParam(
          QApplication::translate("EMailModule", "Decrypt and Verify E-Mail"),
          dv_meta_cards, result_cards);

      // callback
      CB(event, GFGetModuleID(),
         {
             {"ret", QString::number(0)},
             {"data", eml_data},
             {"result_status", QString::number(result_status)},
             {"result", email_info},
             {"result_cards", result_cards_param},
         });
      return 0;
    });

REGISTER_EVENT_HANDLER(
    EDIT_TAB_TYPE_EMAIL_OP_SAVE_FILE, [](const MEvent& event) -> int {
      if (event["page"].isEmpty()) CB_ERR(event, -1, "page is empty");

      auto* page = GFUIGetGUIObjectAs<QWidget>(event["page"]);
      if (!page) {
        LOG_ERROR("page handler is not a QWidget");
        CB_ERR(event, -1, "page handle invalid or not QMainWindow");
      }

      auto* tab_widget = GFUIGetGUIObjectAs<QTabWidget>(event["tab_widget"]);
      if (!tab_widget) {
        LOG_ERROR("tab widget handler is not a QTabWidget");
        CB_ERR(event, -1, "main_window handle invalid or not QMainWindow");
      }

      QString filename;

      auto ok = QMetaObject::invokeMethod(page, "GetFilePath",
                                          Qt::BlockingQueuedConnection,
                                          Q_RETURN_ARG(QString, filename));

      if (!ok) {
        LOG_ERROR("invoke GetFilePath failed");
        CB_ERR(event, -1, "invoke GetFilePath failed");
      }

      if (filename.isEmpty()) {
        auto ok = QMetaObject::invokeMethod(
            QCoreApplication::instance(),
            [&]() -> void {
              // Named after the message rather than left blank. The view is
              // the only thing that knows the subject, and it is reached the
              // same way the rest of this module reaches it.
              QString suggested;
              if (auto* view = page->findChild<EMailPageView*>();
                  view != nullptr) {
                suggested = view->SuggestedFileName();
              }
              if (suggested.isEmpty())
                suggested = QStringLiteral("untitled.eml");

              filename = QFileDialog::getSaveFileName(
                  page, QApplication::translate("EMailModule", "Save file"),
                  QDir(default_save_dir()).filePath(suggested),
                  QApplication::translate("EMailModule",
                                          "E-Mail Message (*.eml);;All Files "
                                          "(*)"));
            },
            Qt::BlockingQueuedConnection);

        if (!ok) {
          LOG_ERROR("invoke getSaveFileName failed");
          CB_ERR(event, -1, "invoke getSaveFileName failed");
        }
      }

      if (filename.isEmpty()) {
        LOG_INFO("user cancelled to select file to save");
        CB_SUCC(event);
      }

      QFileInfo file_info(filename);
      if (file_info.suffix().toLower() != "eml") {
        file_info.setFile(file_info.path(),
                          file_info.completeBaseName() + ".eml");
        filename = file_info.absoluteFilePath();
        FLOG_DEBUG("append .eml suffix to filename: %1", filename);
      }

      QPlainTextEdit* text_edit = nullptr;
      ok = QMetaObject::invokeMethod(page, "GetTextPage",
                                     Qt::BlockingQueuedConnection,
                                     Q_RETURN_ARG(QPlainTextEdit*, text_edit));
      if (!ok || text_edit == nullptr) {
        LOG_ERROR("invoke GetTextPage failed");
        CB_ERR(event, -1, "invoke GetTextPage failed");
      }

      // Normalize to LF first: the editor may already hold CRLF, and blindly
      // expanding every "\n" then turns each of those into CRCRLF.
      auto text = text_edit->toPlainText();
      text.replace("\r\n", "\n");
      text.replace("\n", "\r\n");

      // Last look before the bytes leave. Deliberately after the content is
      // assembled and before anything is written, so what is checked is
      // exactly what would be saved.
      if (!ConfirmExport(page, text.toUtf8())) {
        LOG_INFO("user cancelled the save after the export check");
        CB_SUCC(event);
      }

      // Written binary and through QSaveFile: QIODevice::Text would translate
      // the line endings a second time on Windows, and a plain QFile leaves a
      // truncated .eml behind if the write fails halfway.
      QSaveFile file(filename);
      if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(
            page, QApplication::translate("EMailModule", "Warning"),
            QApplication::translate("EMailModule", "Cannot write file %1:\n%2.")
                .arg(filename)
                .arg(file.errorString()));
        CB_ERR(event, -1, "cannot open file for writing");
      }

      QApplication::setOverrideCursor(Qt::WaitCursor);
      const auto bytes = text.toUtf8();
      const bool written = file.write(bytes) == bytes.size() && file.commit();
      QApplication::restoreOverrideCursor();

      if (!written) {
        QMessageBox::warning(
            page, QApplication::translate("EMailModule", "Warning"),
            QApplication::translate("EMailModule", "Cannot write file %1:\n%2.")
                .arg(filename)
                .arg(file.errorString()));
        CB_ERR(event, -1, "writing file failed");
      }

      QTextDocument* document = text_edit->document();

      document->setModified(false);

      int cur_index = tab_widget->currentIndex();
      tab_widget->setTabText(cur_index, QFileInfo(filename).fileName());

      QMetaObject::invokeMethod(page, "SetFilePath",
                                Qt::BlockingQueuedConnection,
                                Q_ARG(QString, filename));
      QMetaObject::invokeMethod(page, "NotifyFileSaved",
                                Qt::BlockingQueuedConnection);
      return 0;
    });

REGISTER_EVENT_HANDLER(
    FILE_EXT_EMAIL_OP_OPEN_FILE, [](const MEvent& event) -> int {
      if (event["file_path"].isEmpty()) CB_ERR(event, -1, "file_path is empty");

      auto file_path = event.value("file_path", "");
      QFileInfo file_info(file_path);

      // A 1 MB ceiling used to stand here, which refused any message with a
      // real attachment. What it was actually protecting was the synchronous
      // parse of untrusted input, and that is now bounded properly by the
      // depth, part-count and decoded-size limits in ExtractParts -- so the
      // ceiling can be about memory alone.
      if (file_info.size() > kMaxEMLFileSize) {
        QMessageBox::warning(
            nullptr, QApplication::translate("EMailModule", "Warning"),
            QApplication::translate(
                "EMailModule",
                "The file %1 is too large (%2) to be opened. The maximum "
                "allowed size is %3.")
                .arg(file_path)
                .arg(QLocale().formattedDataSize(file_info.size()))
                .arg(QLocale().formattedDataSize(kMaxEMLFileSize)));
        CB_ERR(event, -1, "file too large");
      }

      auto* edit = GFUIGetGUIObjectAs<QWidget>("main_window_edit");
      if (!edit) {
        LOG_ERROR(
            "main window menu mounted: main_window_edit "
            "handle invalid or not "
            "QWidget");
        CB_ERR(event, -1,
               "main_window_edit handle invalid or not "
               "QWidget");
      }

      // Run in GUI thread to avoid blocking the main thread
      QMetaObject::invokeMethod(QCoreApplication::instance(), [=]() -> void {
        QFileInfo file_info(file_path);
        QFile file(file_path);
        // NOT QIODevice::Text. Text mode translates CRLF to LF on the way
        // in, and a PGP/MIME signature covers the exact octets of the message
        // in canonical CRLF form -- so reading it that way silently destroys
        // every signature in the file before anything has a chance to check
        // one.
        if (!file.open(QIODevice::ReadOnly)) {
          QMessageBox::warning(
              nullptr, QApplication::translate("EMailModule", "Warning"),
              QApplication::translate("EMailModule",
                                      "Cannot read file %1:\n%2.")
                  .arg(file_path)
                  .arg(file.errorString()));
          return;
        }

        QWidget* page = nullptr;

        auto ok = QMetaObject::invokeMethod(
            edit, "SlotNewCustomTab", Qt::DirectConnection,
            Q_RETURN_ARG(QWidget*, page), Q_ARG(QString, "email"),
            Q_ARG(QString, file_info.fileName()),
            Q_ARG(QIcon, QIcon(":/icons/email.png")),
            Q_ARG(QString, ":/icons/email.png"));

        if (!ok || !page) {
          LOG_ERROR("create new email tab page failed");
          CB_ERR_NO_RET(event, -1, "create new email tab page failed");
          return;
        }

        QPlainTextEdit* text_edit = nullptr;
        ok =
            QMetaObject::invokeMethod(page, "GetTextPage", Qt::DirectConnection,
                                      Q_RETURN_ARG(QPlainTextEdit*, text_edit));
        if (!ok || text_edit == nullptr) {
          LOG_ERROR("invoke GetTextPage failed");
          CB_ERR_NO_RET(event, -1, "invoke GetTextPage failed");
          return;
        }

        const auto raw = file.readAll();

        // Handed over as bytes so the page can record which line endings the
        // message arrived with and reproduce them when it is read back or
        // saved. Falls back to the old path on a host that does not offer
        // this, where the endings are lost exactly as they were before.
        if (!QMetaObject::invokeMethod(page, "SetContentFromBytes",
                                       Qt::DirectConnection,
                                       Q_ARG(QByteArray, raw))) {
          text_edit->setPlainText(QString::fromUtf8(raw));
          text_edit->document()->setModified(false);
        }

        QMetaObject::invokeMethod(page, "SetFilePath", Qt::DirectConnection,
                                  Q_ARG(QString, file_path));
      });
      return 0;
    })