File: itemencrypted.cpp

package info (click to toggle)
copyq 13.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,964 kB
  • sloc: cpp: 63,306; sh: 992; xml: 452; python: 293; ruby: 152; makefile: 27; javascript: 25
file content (1035 lines) | stat: -rw-r--r-- 31,419 bytes parent folder | download
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
// SPDX-License-Identifier: GPL-3.0-or-later

#include "itemencrypted.h"
#include "ui_itemencryptedsettings.h"

#include "common/command.h"
#include "common/config.h"
#include "common/contenttype.h"
#include "common/mimetypes.h"
#include "common/shortcuts.h"
#include "common/processsignals.h"
#include "common/textdata.h"
#include "gui/icons.h"
#include "gui/iconwidget.h"
#include "gui/fromiconid.h"
#include "item/serialize.h"

#ifdef HAS_TESTS
#   include "tests/itemencryptedtests.h"
#endif

#include <QAbstractItemModel>
#include <QDebug>
#include <QDir>
#include <QIODevice>
#include <QLabel>
#include <QLoggingCategory>
#include <QModelIndex>
#include <QSettings>
#include <QTextEdit>
#include <QtPlugin>
#include <QVBoxLayout>
#include <QVariantMap>

namespace {

const QLatin1String mimeEncryptedData("application/x-copyq-encrypted");

const QLatin1String dataFileHeader("CopyQ_encrypted_tab");
const QLatin1String dataFileHeaderV2("CopyQ_encrypted_tab v2");

const QLatin1String configEncryptTabs("encrypt_tabs");

const int maxItemCount = 100'000;

Q_DECLARE_LOGGING_CATEGORY(plugin)
Q_LOGGING_CATEGORY(plugin, "copyq.plugin.itemencrypted")

bool waitOrTerminate(QProcess *p, int timeoutMs)
{
    p->waitForStarted();

    if ( p->state() != QProcess::NotRunning && !p->waitForFinished(timeoutMs) ) {
        p->terminate();
        if ( !p->waitForFinished(5000) )
            p->kill();
        return false;
    }

    return true;
}

bool verifyProcess(QProcess *p, int timeoutMs = 30000)
{
    if ( !waitOrTerminate(p, timeoutMs) ) {
        qCCritical(plugin) << "Process timed out; stderr:" << p->readAllStandardError();
        return false;
    }

    const int exitCode = p->exitCode();
    if ( p->exitStatus() != QProcess::NormalExit ) {
        qCCritical(plugin) << "Failed to run GnuPG:" << p->errorString();
        return false;
    }

    if (exitCode != 0) {
        if (const QString errors = p->readAllStandardError(); !errors.isEmpty()) {
            qCCritical(plugin) << "GnuPG stderr:" << errors;
        }
        return false;
    }

    return true;
}

QString getGpgVersionOutput(const QString &executable) {
    QProcess p;
    p.start(executable, QStringList("--version"), QIODevice::ReadWrite);
    p.closeReadChannel(QProcess::StandardError);

    if ( !verifyProcess(&p, 5000) )
        return QString();

    return p.readAllStandardOutput();
}

struct GpgVersion {
    int major;
    int minor;
};

GpgVersion parseVersion(const QString &versionOutput)
{
    const int lineEndIndex = versionOutput.indexOf('\n');
    const auto firstLine = QStringView{versionOutput}.mid(0, lineEndIndex);
    const QRegularExpression versionRegex(QStringLiteral(R"( (\d+)\.(\d+))"));
    const QRegularExpressionMatch match = versionRegex.match(firstLine);
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
    const int major = match.hasMatch() ? match.capturedView(1).toInt() : 0;
    const int minor = match.hasMatch() ? match.capturedView(2).toInt() : 0;
#else
    const int major = match.hasMatch() ? match.capturedRef(1).toInt() : 0;
    const int minor = match.hasMatch() ? match.capturedRef(2).toInt() : 0;
#endif
    return GpgVersion{major, minor};
}

class GpgExecutable {
public:
    GpgExecutable() = default;

    explicit GpgExecutable(const QString &executable)
        : m_executable(executable)
    {
        const auto versionOutput = getGpgVersionOutput(executable);
        if ( !versionOutput.isEmpty() ) {
            qCDebug(plugin).nospace()
                << "'" << executable << " --version' output: " << versionOutput;

            const GpgVersion version = parseVersion(versionOutput);
            m_isSupported = version.major >= 2;
            qCDebug(plugin).nospace()
                << (m_isSupported ? "Supported" : "Unsupported")
                << " gpg version: " << version.major << "." << version.minor;

            const bool needsSecring = version.major == 2 && version.minor == 0;

            const QString path = getConfigurationFilePath("");
            m_pubring = path + ".pub";
            m_pubringNative = QDir::toNativeSeparators(m_pubring);
            if (needsSecring) {
                m_secring = path + ".sec";
                m_secringNative = QDir::toNativeSeparators(m_secring);
            }

#ifdef Q_OS_WIN
            const bool isUnixGpg = versionOutput.contains("Home: /c/");
            if (isUnixGpg) {
                m_pubringNative = QString(m_pubring).replace(":", "").insert(0, '/');
                if (needsSecring)
                    m_secringNative = QString(m_secring).replace(":", "").insert(0, '/');
            }
#endif
        }
    }

    const QString &executable() const { return m_executable; }
    bool isSupported() const { return m_isSupported; }
    bool needsSecring() const { return !m_secring.isEmpty(); }
    const QString &pubring() const { return m_pubring; }
    const QString &secring() const { return m_secring; }
    const QString &pubringNative() const { return m_pubringNative; }
    const QString &secringNative() const { return m_secringNative; }

private:
    QString m_executable;
    QString m_pubring;
    QString m_secring;
    QString m_pubringNative;
    QString m_secringNative;
    bool m_isSupported = false;
};

GpgExecutable findGpgExecutable()
{
    for (const auto &executable : {"gpg2", "gpg"}) {
        GpgExecutable gpg(executable);
        if ( gpg.isSupported() )
            return gpg;
    }

    return GpgExecutable();
}

const GpgExecutable &gpgExecutable()
{
    static const auto gpg = findGpgExecutable();
    return gpg;
}

QStringList getDefaultEncryptCommandArguments(const QString &publicKeyPath)
{
    return QStringList() << "--trust-model" << "always" << "--recipient" << "copyq"
                         << "--charset" << "utf-8" << "--display-charset" << "utf-8" << "--no-tty"
                         << "--no-default-keyring" << "--keyring" << publicKeyPath;
}

void startGpgProcess(QProcess *p, const QStringList &args, QIODevice::OpenModeFlag mode)
{
    const auto &gpg = gpgExecutable();
    p->start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) + args, mode);
}

QString importGpgKey()
{
    const auto &gpg = gpgExecutable();
    if ( !gpg.needsSecring() )
        return QString();

    QProcess p;
    p.start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) << "--import" << gpg.secringNative());
    if ( !verifyProcess(&p) )
        return "Failed to import private key (see log).";

    return QString();
}

QString exportGpgKey()
{
    const auto &gpg = gpgExecutable();
    if ( !gpg.needsSecring() )
        return QString();

    // Private key already created or exported.
    if ( QFile::exists(gpg.secring()) )
        return QString();

    QProcess p;
    p.start(gpg.executable(), getDefaultEncryptCommandArguments(gpg.pubringNative()) << "--export-secret-key" << gpg.secringNative());
    if ( !verifyProcess(&p) )
        return "Failed to export private key (see log).";

    QFile secKey(gpg.secring());
    if ( !secKey.open(QIODevice::WriteOnly) )
        return "Failed to create private key.";

    if ( !secKey.setPermissions(QFile::ReadOwner | QFile::WriteOwner) )
        return "Failed to set permissions for private key.";

    const QByteArray secKeyData = p.readAllStandardOutput();
    secKey.write(secKeyData);
    secKey.close();

    return QString();
}

QByteArray readGpgOutput(const QStringList &args, const QByteArray &input = QByteArray())
{
    QProcess p;
    startGpgProcess(&p, args, QIODevice::ReadWrite);
    p.write(input);
    p.closeWriteChannel();
    p.waitForFinished();
    verifyProcess(&p);
    return p.readAllStandardOutput();
}

bool keysExist()
{
    return !readGpgOutput( QStringList("--list-keys") ).isEmpty();
}

bool decryptMimeData(QVariantMap *data)
{
    const QByteArray encryptedBytes = data->take(mimeEncryptedData).toByteArray();
    const QByteArray bytes = readGpgOutput( QStringList() << "--decrypt", encryptedBytes );
    if ( bytes.isEmpty() )
        return false;

    return deserializeData(data, bytes);
}

bool encryptMimeData(const QVariantMap &data, const QModelIndex &index, QAbstractItemModel *model)
{
    QVariantMap dataToEncrypt;
    QVariantMap dataMap;
    for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
        if ( it.key().startsWith(COPYQ_MIME_PREFIX) )
            dataMap.insert(it.key(), it.value());
        else
            dataToEncrypt.insert(it.key(), it.value());
    }

    if ( dataToEncrypt.isEmpty() )
        return false;

    const QByteArray bytes = serializeData(dataToEncrypt);
    const QByteArray encryptedBytes = readGpgOutput( QStringList("--encrypt"), bytes );
    if ( encryptedBytes.isEmpty() )
        return false;

    dataMap.insert(mimeEncryptedData, encryptedBytes);
    return model->setData(index, dataMap, contentType::updateData);
}

void startGenerateKeysProcess(QProcess *process, bool useTransientPasswordlessKey = false)
{
    const auto &gpg = gpgExecutable();

    auto args = QStringList() << "--batch" << "--gen-key";

    QByteArray transientOptions;
    if (useTransientPasswordlessKey) {
        args << "--debug-quick-random";
        transientOptions =
                "\n%no-protection"
                "\n%transient-key";
    }

    startGpgProcess(process, args, QIODevice::ReadWrite);
    process->write(
        "\nKey-Type: RSA"
        "\nKey-Usage: encrypt"
        "\nKey-Length: 4096"
        "\nName-Real: copyq"
        + transientOptions +
        "\n%pubring " + gpg.pubringNative().toUtf8()
    );

    if ( gpg.needsSecring() )
        process->write("\n%secring " + gpg.secringNative().toUtf8());

    process->write("\n%commit\n");
    process->closeWriteChannel();
}

QString exportImportGpgKeys()
{
    if (const auto error = exportGpgKey(); !error.isEmpty())
        return error;

    return importGpgKey();
}

bool isGpgInstalled()
{
    return gpgExecutable().isSupported();
}

} // namespace

ItemEncrypted::ItemEncrypted(QWidget *parent)
    : QWidget(parent)
    , ItemWidget(this)
{
    auto layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    // Show small icon.
    QWidget *iconWidget = new IconWidget(IconLock, this);
    layout->addWidget(iconWidget);
}

bool ItemEncryptedSaver::saveItems(const QString &, const QAbstractItemModel &model, QIODevice *file)
{
    const auto length = model.rowCount();
    QByteArray bytes;

    {
        QDataStream stream(&bytes, QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_4_7);

        stream << static_cast<quint64>(length);

        for (int i = 0; i < length && stream.status() == QDataStream::Ok; ++i) {
            QModelIndex index = model.index(i, 0);
            QVariantMap dataMap = index.data(contentType::data).toMap();
            for (auto it = dataMap.begin(); it != dataMap.end(); ++it) {
                if (it.value().type() != QVariant::ByteArray)
                    it.value() = it.value().toByteArray();
            }
            stream << dataMap;
        }
    }

    bytes = readGpgOutput(QStringList("--encrypt"), bytes);
    if ( bytes.isEmpty() ) {
        emitEncryptFailed();
        qCCritical(plugin) << "Failed to read encrypted data";
        return false;
    }

    QDataStream stream(file);
    stream.setVersion(QDataStream::Qt_4_7);
    stream << QString(dataFileHeaderV2);
    stream.writeRawData( bytes.data(), bytes.size() );

    if ( stream.status() != QDataStream::Ok ) {
        emitEncryptFailed();
        qCCritical(plugin) << "Failed to write encrypted data";
        return false;
    }

    return true;
}

void ItemEncryptedSaver::emitEncryptFailed()
{
    emit error( ItemEncryptedLoader::tr("Encryption failed!") );
}

bool ItemEncryptedScriptable::isEncrypted()
{
    const auto args = currentArguments();
    for (const auto &arg : args) {
        bool ok;
        const int row = arg.toInt(&ok);
        if (ok) {
            const auto result = call("read", QVariantList() << "?" << row);
            if ( result.toByteArray().contains(mimeEncryptedData.data()) )
                return true;
        }
    }

    return false;
}

QByteArray ItemEncryptedScriptable::encrypt()
{
    const auto args = currentArguments();
    const auto bytes = args.value(0).toByteArray();
    return encrypt(bytes);
}

QByteArray ItemEncryptedScriptable::decrypt()
{
    const auto args = currentArguments();
    const auto bytes = args.value(0).toByteArray();
    return decrypt(bytes);
}

void ItemEncryptedScriptable::encryptItem()
{
    QVariantMap dataMap;
    const auto formats = call("dataFormats").toList();
    for (const auto &formatValue : formats) {
        const auto format = formatValue.toString();
        if ( !format.startsWith(COPYQ_MIME_PREFIX) ) {
            const auto data = call("data", QVariantList() << format).toByteArray();
            dataMap.insert(format, data);
        }
    }

    const auto bytes = call("pack", QVariantList() << dataMap).toByteArray();
    const auto encryptedBytes = encrypt(bytes);
    if (encryptedBytes.isEmpty())
        return;

    call("setData", QVariantList() << mimeEncryptedData << encryptedBytes);

    for (auto it = dataMap.constBegin(); it != dataMap.constEnd(); ++it)
        call("removeData", QVariantList() << it.key());
}

void ItemEncryptedScriptable::decryptItem()
{
    const auto encryptedBytes = call("data", QVariantList() << mimeEncryptedData).toByteArray();
    const auto itemData = decrypt(encryptedBytes);
    if (itemData.isEmpty())
        return;

    const auto dataMap = call("unpack", QVariantList() << itemData).toMap();
    for (auto it = dataMap.constBegin(); it != dataMap.constEnd(); ++it) {
        const auto &format = it.key();
        call("setData", QVariantList() << format << dataMap[format]);
    }
}

void ItemEncryptedScriptable::encryptItems()
{
    const auto dataValueList = call("selectedItemsData").toList();

    QVariantList dataList;
    for (const auto &itemDataValue : dataValueList) {
        auto itemData = itemDataValue.toMap();

        QVariantMap itemDataToEncrypt;
        const auto formats = itemData.keys();
        for (const auto &format : formats) {
            if ( !format.startsWith(COPYQ_MIME_PREFIX) ) {
                itemDataToEncrypt.insert(format, itemData[format]);
                itemData.remove(format);
            }
        }

        const auto bytes = call("pack", QVariantList() << itemDataToEncrypt).toByteArray();
        const auto encryptedBytes = encrypt(bytes);
        if (encryptedBytes.isEmpty())
            return;
        itemData.insert(mimeEncryptedData, encryptedBytes);

        dataList.append(itemData);
    }

    call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
}

void ItemEncryptedScriptable::decryptItems()
{
    const auto dataValueList = call("selectedItemsData").toList();

    QVariantList dataList;
    for (const auto &itemDataValue : dataValueList) {
        auto itemData = itemDataValue.toMap();

        const auto encryptedBytes = itemData.value(mimeEncryptedData).toByteArray();
        if ( !encryptedBytes.isEmpty() ) {
            itemData.remove(mimeEncryptedData);

            const auto decryptedBytes = decrypt(encryptedBytes);
            if (decryptedBytes.isEmpty())
                return;

            const auto decryptedItemData = call("unpack", QVariantList() << decryptedBytes).toMap();
            for (auto it = decryptedItemData.constBegin(); it != decryptedItemData.constEnd(); ++it)
                itemData.insert(it.key(), it.value());
        }

        dataList.append(itemData);
    }

    call( "setSelectedItemsData", QVariantList() << QVariant(dataList) );
}

void ItemEncryptedScriptable::copyEncryptedItems()
{
    const auto dataValueList = call("selectedItemsData").toList();
    QString text;
    for (const auto &dataValue : dataValueList) {
        if ( !text.isEmpty() )
            text.append('\n');

        const auto data = dataValue.toMap();
        const auto itemTextValue = data.value(mimeText);
        if ( itemTextValue.isValid() ) {
            text.append( getTextData(itemTextValue.toByteArray()) );
        } else {
            const auto encryptedBytes = data.value(mimeEncryptedData).toByteArray();
            if ( !encryptedBytes.isEmpty() ) {
                const auto itemData = decrypt(encryptedBytes);
                if (itemData.isEmpty())
                    return;
                const auto dataMap = call("unpack", QVariantList() << itemData).toMap();
                text.append( getTextData(dataMap) );
            }
        }
    }

    const auto args = QVariantList()
            << mimeText << text
            << mimeHidden << "1";
    call("copy", args);
    call("copySelection", args);
}

void ItemEncryptedScriptable::pasteEncryptedItems()
{
    copyEncryptedItems();
    const auto script =
        R"(
        if (focused()) {
            hide();
            sleep(100);
        }
        paste();
        sleep(2000);
        copy('');
        copySelection('');
        )";
    call("eval", QVariantList() << script);
}

QString ItemEncryptedScriptable::generateTestKeys()
{
    const auto &gpg = gpgExecutable();

    const QStringList keys = gpg.needsSecring()
        ? QStringList{gpg.pubring(), gpg.secring()}
        : QStringList{gpg.pubring()};

    for (const auto &keyFileName : keys) {
        if ( QFile::exists(keyFileName) && !QFile::remove(keyFileName) )
            return QString("Failed to remove \"%1\"").arg(keyFileName);
    }

    QProcess process;
    startGenerateKeysProcess(&process, true);

    if ( !verifyProcess(&process) ) {
        return QString("ItemEncrypt: %1; stderr: %2")
                .arg( process.errorString(),
                      QString::fromUtf8(process.readAllStandardError()) );
    }

    if ( const auto error = exportImportGpgKeys(); !error.isEmpty() )
        return error;

    for (const auto &keyFileName : keys) {
        if ( !QFile::exists(keyFileName) )
            return QString("Failed to create \"%1\"").arg(keyFileName);
    }

    return QString();
}

bool ItemEncryptedScriptable::isGpgInstalled()
{
    return ::isGpgInstalled();
}

QByteArray ItemEncryptedScriptable::encrypt(const QByteArray &bytes)
{
    const auto encryptedBytes = readGpgOutput(QStringList("--encrypt"), bytes);
    if ( encryptedBytes.isEmpty() )
        throwError("Failed to execute GPG!");
    return encryptedBytes;
}

QByteArray ItemEncryptedScriptable::decrypt(const QByteArray &bytes)
{
    importGpgKey();

    const auto decryptedBytes = readGpgOutput(QStringList("--decrypt"), bytes);
    if ( decryptedBytes.isEmpty() )
        throwError("Failed to execute GPG!");
    return decryptedBytes;
}

ItemEncryptedLoader::ItemEncryptedLoader()
    : ui()
    , m_gpgProcessStatus(GpgCheckIfInstalled)
    , m_gpgProcess(nullptr)
{
}

ItemEncryptedLoader::~ItemEncryptedLoader()
{
    terminateGpgProcess();
}

ItemWidget *ItemEncryptedLoader::create(const QVariantMap &data, QWidget *parent, bool) const
{
    if ( data.value(mimeHidden).toBool() )
        return nullptr;

    return data.contains(mimeEncryptedData) ? new ItemEncrypted(parent) : nullptr;
}

QStringList ItemEncryptedLoader::formatsToSave() const
{
    return QStringList(mimeEncryptedData);
}

void ItemEncryptedLoader::applySettings(QSettings &settings)
{
    Q_ASSERT(ui != nullptr);
    settings.setValue( configEncryptTabs, ui->plainTextEditEncryptTabs->toPlainText().split('\n') );
}

void ItemEncryptedLoader::loadSettings(const QSettings &settings)
{
    m_encryptTabs = settings.value(configEncryptTabs).toStringList();
}

QWidget *ItemEncryptedLoader::createSettingsWidget(QWidget *parent)
{
    ui.reset(new Ui::ItemEncryptedSettings);
    QWidget *w = new QWidget(parent);
    ui->setupUi(w);

    ui->plainTextEditEncryptTabs->setPlainText(
        m_encryptTabs.join('\n') );

    if (status() != GpgNotInstalled) {
        const auto &gpg = gpgExecutable();
        ui->labelShareInfo->setTextFormat(Qt::RichText);
        QString text = ItemEncryptedLoader::tr(
            "To share encrypted items on other computer or"
            " session, you'll need these secret key files (keep them in a safe place):"
        );
        if (gpg.needsSecring()) {
            text.append( QStringLiteral(
                "<ul>"
                "<li>%1</li>"
                "<li>%2</li>"
                "</ul>"
                ).arg(quoteString(gpg.pubringNative()), quoteString(gpg.secringNative()))
            );
        } else {
            text.append( QStringLiteral(
                "<ul>"
                "<li>%1</li>"
                "</ul>"
                ).arg(quoteString(gpg.pubringNative()))
            );
        }
        ui->labelShareInfo->setText(text);
    }

    updateUi();

    connect( ui->pushButtonPassword, &QAbstractButton::clicked,
             this, &ItemEncryptedLoader::setPassword );

    return w;
}

bool ItemEncryptedLoader::canLoadItems(QIODevice *file) const
{
    QDataStream stream(file);
    stream.setVersion(QDataStream::Qt_4_7);

    QString header;
    stream >> header;

    return stream.status() == QDataStream::Ok
            && (header == dataFileHeader || header == dataFileHeaderV2);
}

bool ItemEncryptedLoader::canSaveItems(const QString &tabName) const
{
    for (const auto &encryptTabName : m_encryptTabs) {
        if ( encryptTabName.isEmpty() )
            continue;

        QString tabName1 = tabName;

        // Ignore ampersands (usually just for underlining mnemonics) if none is specified.
        if ( !hasKeyHint(encryptTabName) )
            removeKeyHint(&tabName1);

        // Ignore path in tab tree if none path separator is specified.
        if ( !encryptTabName.contains('/') ) {
            const int i = tabName1.lastIndexOf('/');
            tabName1.remove(0, i + 1);
        }

        if ( tabName1 == encryptTabName )
            return true;
    }

    return false;
}

ItemSaverPtr ItemEncryptedLoader::loadItems(const QString &, QAbstractItemModel *model, QIODevice *file, int maxItems)
{
    // This is needed to skip header.
    if ( !canLoadItems(file) )
        return nullptr;

    if (status() == GpgNotInstalled) {
        emit error( ItemEncryptedLoader::tr("GnuPG must be installed to view encrypted tabs.") );
        return nullptr;
    }

    importGpgKey();

    QProcess p;
    startGpgProcess( &p, QStringList("--decrypt"), QIODevice::ReadWrite );

    char encryptedBytes[4096];

    QDataStream stream(file);
    while ( !stream.atEnd() ) {
        const int bytesRead = stream.readRawData(encryptedBytes, 4096);
        if (bytesRead == -1) {
            emitDecryptFailed();
            qCCritical(plugin) << "Failed to read encrypted data";
            return nullptr;
        }
        p.write(encryptedBytes, bytesRead);
    }

    p.closeWriteChannel();

    // Wait for password entry dialog.
    p.waitForFinished(-1);

    if ( !verifyProcess(&p) ) {
        emitDecryptFailed();
        return nullptr;
    }

    const QByteArray bytes = p.readAllStandardOutput();
    if ( bytes.isEmpty() ) {
        emitDecryptFailed();
        qCCritical(plugin) << "Failed to read encrypted data";
        verifyProcess(&p);
        return nullptr;
    }

    QDataStream stream2(bytes);

    quint64 length;
    stream2 >> length;
    if ( stream2.status() != QDataStream::Ok ) {
        emitDecryptFailed();
        qCCritical(plugin) << "Failed to parse item count";
        return nullptr;
    }
    length = qMin(length, static_cast<quint64>(maxItems)) - static_cast<quint64>(model->rowCount());

    const auto count = length < maxItemCount ? static_cast<int>(length) : maxItemCount;
    for ( int i = 0; i < count && stream2.status() == QDataStream::Ok; ++i ) {
        if ( !model->insertRow(i) ) {
            emitDecryptFailed();
            qCCritical(plugin) << "Failed to insert item";
            return nullptr;
        }
        QVariantMap dataMap;
        stream2 >> dataMap;
        model->setData( model->index(i, 0), dataMap, contentType::data );
    }

    if ( stream2.status() != QDataStream::Ok ) {
        emitDecryptFailed();
        qCCritical(plugin) << "Failed to decrypt item";
        return nullptr;
    }

    return createSaver();
}

ItemSaverPtr ItemEncryptedLoader::initializeTab(const QString &, QAbstractItemModel *, int)
{
    if (status() == GpgNotInstalled)
        return nullptr;

    return createSaver();
}

QObject *ItemEncryptedLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
    QObject *tests = new ItemEncryptedTests(test);
    return tests;
#else
    Q_UNUSED(test)
    return nullptr;
#endif
}

ItemScriptable *ItemEncryptedLoader::scriptableObject()
{
    return new ItemEncryptedScriptable();
}

QVector<Command> ItemEncryptedLoader::commands() const
{
    if ( status() == GpgNotInstalled || !keysExist() )
        return QVector<Command>();

    QVector<Command> commands;

    Command c;
    c.internalId = QStringLiteral("copyq_encrypted_encrypt");
    c.name = ItemEncryptedLoader::tr("Encrypt (needs GnuPG)");
    c.icon = fromIconId(IconLock);
    c.input = "!OUTPUT";
    c.output = mimeEncryptedData;
    c.inMenu = true;
    c.cmd = "copyq: plugins.itemencrypted.encryptItems()";
    c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+L")) );
    commands.append(c);

    c = Command();
    c.internalId = QStringLiteral("copyq_encrypted_decrypt");
    c.name = ItemEncryptedLoader::tr("Decrypt");
    c.icon = fromIconId(IconUnlock);
    c.input = mimeEncryptedData;
    c.output = mimeItems;
    c.inMenu = true;
    c.cmd = "copyq: plugins.itemencrypted.decryptItems()";
    c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+L")) );
    commands.append(c);

    c = Command();
    c.internalId = QStringLiteral("copyq_encrypted_decrypt_and_copy");
    c.name = ItemEncryptedLoader::tr("Decrypt and Copy");
    c.icon = fromIconId(IconUnlockKeyhole);
    c.input = mimeEncryptedData;
    c.inMenu = true;
    c.cmd = "copyq: plugins.itemencrypted.copyEncryptedItems()";
    c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Ctrl+Shift+L")) );
    commands.append(c);

    c = Command();
    c.internalId = QStringLiteral("copyq_encrypted_decrypt_and_paste");
    c.name = ItemEncryptedLoader::tr("Decrypt and Paste");
    c.icon = fromIconId(IconUnlockKeyhole);
    c.input = mimeEncryptedData;
    c.inMenu = true;
    c.cmd = "copyq: plugins.itemencrypted.pasteEncryptedItems()";
    c.shortcuts.append( toPortableShortcutText(ItemEncryptedLoader::tr("Enter")) );
    commands.append(c);

    return commands;
}

void ItemEncryptedLoader::setPassword()
{
    if (status() != GpgNotRunning)
        return;

    if ( !keysExist() ) {
        m_gpgProcessStatus = GpgGeneratingKeys;
        m_gpgProcess = new QProcess(this);
        startGenerateKeysProcess(m_gpgProcess);
    } else {
        // Change password.
        m_gpgProcessStatus = GpgChangingPassword;
        m_gpgProcess = new QProcess(this);
        startGpgProcess( m_gpgProcess, QStringList() << "--edit-key" << "copyq" << "passwd" << "save", QIODevice::ReadOnly );
    }

    m_gpgProcess->waitForStarted();
    if ( m_gpgProcess->state() == QProcess::NotRunning ) {
        onGpgProcessFinished( m_gpgProcess->exitCode(), m_gpgProcess->exitStatus() );
    } else {
        connectProcessFinished(m_gpgProcess, this, &ItemEncryptedLoader::onGpgProcessFinished);
        updateUi();
    }
}

void ItemEncryptedLoader::terminateGpgProcess()
{
    if (m_gpgProcess == nullptr)
        return;
    QProcess *p = m_gpgProcess;
    m_gpgProcess = nullptr;
    p->terminate();
    p->waitForFinished();
    p->deleteLater();
    m_gpgProcessStatus = GpgNotRunning;
    updateUi();
}

void ItemEncryptedLoader::onGpgProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    QString error;

    if (m_gpgProcess != nullptr) {
        if (ui != nullptr) {
            if (exitStatus != QProcess::NormalExit)
                error = m_gpgProcess->errorString();
            else if (exitCode != 0)
                error = getTextData(m_gpgProcess->readAllStandardError());
            else if ( m_gpgProcess->error() != QProcess::UnknownError )
                error = m_gpgProcess->errorString();
            else if ( !keysExist() )
                error = ItemEncryptedLoader::tr("Failed to generate keys.");
        }

        m_gpgProcess->deleteLater();
        m_gpgProcess = nullptr;
    }

    // Export and import private key to a file in configuration.
    if ( status() == GpgGeneratingKeys && error.isEmpty() )
        error = exportImportGpgKeys();

    if (!error.isEmpty())
        error = ItemEncryptedLoader::tr("Error: %1").arg(error);

    m_gpgProcessStatus = GpgNotRunning;

    updateUi();
    ui->labelInfo->setText( error.isEmpty() ? ItemEncryptedLoader::tr("Done") : error );
}

void ItemEncryptedLoader::updateUi()
{
    if (ui == nullptr)
        return;

    if (status() == GpgNotInstalled) {
        ui->labelInfo->setText("To use item encryption, install"
                               " <a href=\"http://www.gnupg.org/\">GnuPG</a>"
                               " application and restart CopyQ.");
        ui->pushButtonPassword->hide();
        ui->groupBoxEncryptTabs->hide();
        ui->groupBoxShareInfo->hide();
    } else if (status() == GpgGeneratingKeys) {
        ui->labelInfo->setText( ItemEncryptedLoader::tr("Creating new keys (this may take a few minutes)...") );
        ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Cancel") );
    } else if (status() == GpgChangingPassword) {
        ui->labelInfo->setText( ItemEncryptedLoader::tr("Setting new password...") );
        ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Cancel") );
    } else if ( !keysExist() ) {
        ui->labelInfo->setText( ItemEncryptedLoader::tr(
                    "Encryption keys <strong>must be generated</strong>"
                    " before item encryption can be used.") );
        ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Generate New Keys...") );
    } else {
        ui->pushButtonPassword->setText( ItemEncryptedLoader::tr("Change Password...") );
    }
}

void ItemEncryptedLoader::emitDecryptFailed()
{
    emit error( ItemEncryptedLoader::tr("Decryption failed!") );
}

ItemSaverPtr ItemEncryptedLoader::createSaver()
{
    auto saver = std::make_shared<ItemEncryptedSaver>();
    connect( saver.get(), &ItemEncryptedSaver::error,
             this, &ItemEncryptedLoader::error );
    return saver;
}

ItemEncryptedLoader::GpgProcessStatus ItemEncryptedLoader::status() const
{
    if (m_gpgProcessStatus == GpgCheckIfInstalled) {
        if (isGpgInstalled())
            m_gpgProcessStatus = GpgNotRunning;
        else
            m_gpgProcessStatus = GpgNotInstalled;
    }

    return m_gpgProcessStatus;
}

bool ItemEncryptedLoader::data(QVariantMap *data, const QModelIndex &) const
{
    return !data->contains(mimeEncryptedData) || decryptMimeData(data);
}

bool ItemEncryptedLoader::setData(const QVariantMap &data, const QModelIndex &index, QAbstractItemModel *model) const
{
    if ( !index.data(contentType::data).toMap().contains(mimeEncryptedData) )
        return false;

    return encryptMimeData(data, index, model);
}