File: command.cpp

package info (click to toggle)
kleopatra 4%3A18.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 21,544 kB
  • sloc: cpp: 51,822; ansic: 382; xml: 119; sh: 51; makefile: 8
file content (718 lines) | stat: -rw-r--r-- 19,159 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
/* -*- mode: c++; c-basic-offset:4 -*-
    command.cpp

    This file is part of KleopatraClient, the Kleopatra interface library
    Copyright (c) 2008 Klarälvdalens Datakonsult AB

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

    KleopatraClient is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <config-kleopatra.h>

#include "command.h"
#include "command_p.h"

#include <QtGlobal> // Q_OS_WIN

#ifdef Q_OS_WIN // HACK: AllowSetForegroundWindow needs _WIN32_WINDOWS >= 0x0490 set
# ifndef _WIN32_WINDOWS
#  define _WIN32_WINDOWS 0x0500
#  define _WIN32_WINNT 0x0500 // good enough for Vista too
# endif
# include <utils/gnupg-registry.h>
# include <windows.h>
#endif

#include <QMutexLocker>
#include <QFile>
#include "libkleopatraclientcore_debug.h"
#include <QDir>
#include <QProcess>
#include <KLocalizedString>

#include <assuan.h>
#include <gpg-error.h>

#include <algorithm>
#include <string>
#include <sstream>
#include <memory>
#include <type_traits>

using namespace KleopatraClientCopy;

// copied from kleopatra/utils/hex.cpp
static std::string hexencode(const std::string &in)
{
    std::string result;
    result.reserve(3 * in.size());

    static const char hex[] = "0123456789ABCDEF";

    for (std::string::const_iterator it = in.begin(), end = in.end(); it != end; ++it)
        switch (const unsigned char ch = *it) {
        default:
            if ((ch >= '!' && ch <= '~') || ch > 0xA0) {
                result += ch;
                break;
            }
            Q_FALLTHROUGH();
        // else fall through
        case ' ':
            result += '+';
            break;
        case '"':
        case '#':
        case '$':
        case '%':
        case '\'':
        case '+':
        case '=':
            result += '%';
            result += hex[(ch & 0xF0) >> 4 ];
            result += hex[(ch & 0x0F)      ];
            break;
        }

    return result;
}

#ifdef UNUSED
static std::string hexencode(const char *in)
{
    if (!in) {
        return std::string();
    }
    return hexencode(std::string(in));
}
#endif

// changed from returning QByteArray to returning std::string
static std::string hexencode(const QByteArray &in)
{
    if (in.isNull()) {
        return std::string();
    }
    return hexencode(std::string(in.data(), in.size()));
}
// end copied from kleopatra/utils/hex.cpp

Command::Command(QObject *p)
    : QObject(p), d(new Private(this))
{
    d->init();
}

Command::Command(Private *pp, QObject *p)
    : QObject(p), d(pp)
{
    d->init();
}

Command::~Command()
{
    delete d; d = nullptr;
}

void Command::Private::init()
{
    connect(this, &QThread::started,  q, &Command::started);
    connect(this, &QThread::finished, q, &Command::finished);
}

void Command::setParentWId(WId wid)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.parentWId = wid;
}

WId Command::parentWId() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.parentWId;
}

void Command::setServerLocation(const QString &location)
{
    const QMutexLocker locker(&d->mutex);
    d->outputs.serverLocation = location;
}

QString Command::serverLocation() const
{
    const QMutexLocker locker(&d->mutex);
    return d->outputs.serverLocation;
}

bool Command::waitForFinished()
{
    return d->wait();
}

bool Command::waitForFinished(unsigned long ms)
{
    return d->wait(ms);
}

bool Command::error() const
{
    const QMutexLocker locker(&d->mutex);
    return !d->outputs.errorString.isEmpty();
}

bool Command::wasCanceled() const
{
    const QMutexLocker locker(&d->mutex);
    return d->outputs.canceled;
}

QString Command::errorString() const
{
    const QMutexLocker locker(&d->mutex);
    return d->outputs.errorString;
}

qint64 Command::serverPid() const
{
    const QMutexLocker locker(&d->mutex);
    return d->outputs.serverPid;
}

void Command::start()
{
    d->start();
}

void Command::cancel()
{
    qCDebug(LIBKLEOPATRACLIENTCORE_LOG) << "Sorry, not implemented: KleopatraClient::Command::Cancel";
}

void Command::setOptionValue(const char *name, const QVariant &value, bool critical)
{
    if (!name || !*name) {
        return;
    }
    const Private::Option opt = {
        value,
        true,
        critical
    };
    const QMutexLocker locker(&d->mutex);
    d->inputs.options[name] = opt;
}

QVariant Command::optionValue(const char *name) const
{
    if (!name || !*name) {
        return QVariant();
    }
    const QMutexLocker locker(&d->mutex);

    const std::map<std::string, Private::Option>::const_iterator it = d->inputs.options.find(name);
    if (it == d->inputs.options.end()) {
        return QVariant();
    } else {
        return it->second.value;
    }
}

void Command::setOption(const char *name, bool critical)
{
    if (!name || !*name) {
        return;
    }
    const QMutexLocker locker(&d->mutex);

    if (isOptionSet(name)) {
        unsetOption(name);
    }

    const Private::Option opt = {
        QVariant(),
        false,
        critical
    };

    d->inputs.options[name] = opt;
}

void Command::unsetOption(const char *name)
{
    if (!name || !*name) {
        return;
    }
    const QMutexLocker locker(&d->mutex);
    d->inputs.options.erase(name);
}

bool Command::isOptionSet(const char *name) const
{
    if (!name || !*name) {
        return false;
    }
    const QMutexLocker locker(&d->mutex);
    return d->inputs.options.count(name);
}

bool Command::isOptionCritical(const char *name) const
{
    if (!name || !*name) {
        return false;
    }
    const QMutexLocker locker(&d->mutex);
    const std::map<std::string, Private::Option>::const_iterator it = d->inputs.options.find(name);
    return it != d->inputs.options.end() && it->second.isCritical;
}

void Command::setFilePaths(const QStringList &filePaths)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.filePaths = filePaths;
}

QStringList Command::filePaths() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.filePaths;
}

void Command::setRecipients(const QStringList &recipients, bool informative)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.recipients = recipients;
    d->inputs.areRecipientsInformative = informative;
}

QStringList Command::recipients() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.recipients;
}

bool Command::areRecipientsInformative() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.areRecipientsInformative;
}

void Command::setSenders(const QStringList &senders, bool informative)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.senders = senders;
    d->inputs.areSendersInformative = informative;
}

QStringList Command::senders() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.senders;
}

bool Command::areSendersInformative() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.areSendersInformative;
}

void Command::setInquireData(const char *what, const QByteArray &data)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.inquireData[what] = data;
}

void Command::unsetInquireData(const char *what)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.inquireData.erase(what);
}

QByteArray Command::inquireData(const char *what) const
{
    const QMutexLocker locker(&d->mutex);
    const std::map<std::string, QByteArray>::const_iterator it = d->inputs.inquireData.find(what);
    if (it == d->inputs.inquireData.end()) {
        return QByteArray();
    } else {
        return it->second;
    }
}

bool Command::isInquireDataSet(const char *what) const
{
    const QMutexLocker locker(&d->mutex);
    const std::map<std::string, QByteArray>::const_iterator it = d->inputs.inquireData.find(what);
    return it != d->inputs.inquireData.end();
}

QByteArray Command::receivedData() const
{
    const QMutexLocker locker(&d->mutex);
    return d->outputs.data;
}

void Command::setCommand(const char *command)
{
    const QMutexLocker locker(&d->mutex);
    d->inputs.command = command;
}

QByteArray Command::command() const
{
    const QMutexLocker locker(&d->mutex);
    return d->inputs.command;
}

//
// here comes the ugly part
//

#ifdef HAVE_ASSUAN2
static void my_assuan_release(assuan_context_t ctx)
{
    if (ctx) {
        assuan_release(ctx);
    }
}
#endif

typedef std::shared_ptr<std::remove_pointer<assuan_context_t>::type > AssuanContextBase;
namespace
{
struct AssuanClientContext : AssuanContextBase {
    AssuanClientContext() : AssuanContextBase() {}
#ifndef HAVE_ASSUAN2
    explicit AssuanClientContext(assuan_context_t ctx) : AssuanContextBase(ctx, &assuan_disconnect) {}
    void reset(assuan_context_t ctx = nullptr)
    {
        AssuanContextBase::reset(ctx, &assuan_disconnect);
    }
#else
    explicit AssuanClientContext(assuan_context_t ctx) : AssuanContextBase(ctx, &my_assuan_release) {}
    void reset(assuan_context_t ctx = nullptr)
    {
        AssuanContextBase::reset(ctx, &my_assuan_release);
    }
#endif
};
}

#ifdef HAVE_ASSUAN2
// compatibility typedef - remove when we require assuan v2...
typedef gpg_error_t assuan_error_t;
#endif

static assuan_error_t
my_assuan_transact(const AssuanClientContext &ctx,
                   const char *command,
                   assuan_error_t (*data_cb)(void *, const void *, size_t) = nullptr,
                   void *data_cb_arg = nullptr,
                   assuan_error_t (*inquire_cb)(void *, const char *) = nullptr,
                   void *inquire_cb_arg = nullptr,
                   assuan_error_t (*status_cb)(void *, const char *) = nullptr,
                   void *status_cb_arg = nullptr)
{
    return assuan_transact(ctx.get(), command, data_cb, data_cb_arg, inquire_cb, inquire_cb_arg, status_cb, status_cb_arg);
}

static QString to_error_string(int err)
{
    char buffer[1024];
    gpg_strerror_r(static_cast<gpg_error_t>(err),
                   buffer, sizeof buffer);
    buffer[sizeof buffer - 1] = '\0';
    return QString::fromLocal8Bit(buffer);
}

static QString gnupg_home_directory()
{
#ifdef Q_OS_WIN
    return QFile::decodeName(default_homedir());
#else
    const QByteArray gnupgHome = qgetenv("GNUPGHOME");
    if (!gnupgHome.isEmpty()) {
        return QFile::decodeName(gnupgHome);
    } else {
        return QDir::homePath() + QLatin1String("/.gnupg");
    }
#endif
}

static QString get_default_socket_name()
{
    const QString homeDir = gnupg_home_directory();
    if (homeDir.isEmpty()) {
        return QString();
    }
    return QDir(homeDir).absoluteFilePath(QStringLiteral("S.uiserver"));
}

static QString default_socket_name()
{
    static QString name = get_default_socket_name();
    return name;
}

static QString uiserver_executable()
{
    return QStringLiteral("kleopatra");
}

static QString start_uiserver()
{
    if (!QProcess::startDetached(uiserver_executable(), QStringList() << QStringLiteral("--daemon"))) {
        return i18n("Failed to start uiserver %1", uiserver_executable());
    } else {
        return QString();
    }
}

static assuan_error_t getinfo_pid_cb(void *opaque, const void *buffer, size_t length)
{
    qint64 &pid = *static_cast<qint64 *>(opaque);
    pid = QByteArray(static_cast<const char *>(buffer), length).toLongLong();
    return 0;
}

static assuan_error_t command_data_cb(void *opaque, const void *buffer, size_t length)
{
    QByteArray &ba = *static_cast<QByteArray *>(opaque);
    ba.append(QByteArray(static_cast<const char *>(buffer), length));
    return 0;
}

namespace
{
struct inquire_data {
    const std::map<std::string, QByteArray> *map;
    const AssuanClientContext *ctx;
};
}

static assuan_error_t command_inquire_cb(void *opaque, const char *what)
{
    if (!opaque) {
        return 0;
    }
    const inquire_data &id = *static_cast<const inquire_data *>(opaque);
    const std::map<std::string, QByteArray>::const_iterator it = id.map->find(what);
    if (it != id.map->end()) {
        const QByteArray &v = it->second;
        assuan_send_data(id.ctx->get(), v.data(), v.size());
    }
    return 0;
}

static inline std::ostream &operator<<(std::ostream &s, const QByteArray &ba)
{
    return s << std::string(ba.data(), ba.size());
}

static assuan_error_t send_option(const AssuanClientContext &ctx, const char *name, const QVariant &value)
{
    std::stringstream ss;
    ss << "OPTION " << name;
    if (value.isValid()) {
        ss << '=' << value.toString().toUtf8();
    }
    return my_assuan_transact(ctx, ss.str().c_str());
}

static assuan_error_t send_file(const AssuanClientContext &ctx, const QString &file)
{
    std::stringstream ss;
    ss << "FILE " << hexencode(QFile::encodeName(file));
    return my_assuan_transact(ctx, ss.str().c_str());
}

static assuan_error_t send_recipient(const AssuanClientContext &ctx, const QString &recipient, bool info)
{
    std::stringstream ss;
    ss << "RECIPIENT ";
    if (info) {
        ss << "--info ";
    }
    ss << "--" << hexencode(recipient.toUtf8());
    return my_assuan_transact(ctx, ss.str().c_str());
}

static assuan_error_t send_sender(const AssuanClientContext &ctx, const QString &sender, bool info)
{
    std::stringstream ss;
    ss << "SENDER ";
    if (info) {
        ss << "--info ";
    }
    ss << "--" << hexencode(sender.toUtf8());
    return my_assuan_transact(ctx, ss.str().c_str());
}

void Command::Private::run()
{

    // Take a snapshot of the input data, and clear the output data:
    Inputs in;
    Outputs out;
    {
        const QMutexLocker locker(&mutex);
        in = inputs;
        outputs = out;
    }

    out.canceled = false;

    if (out.serverLocation.isEmpty()) {
        out.serverLocation = default_socket_name();
    }

#ifndef HAVE_ASSUAN2
    assuan_context_t naked_ctx = 0;
#endif
    AssuanClientContext ctx;
    assuan_error_t err = 0;

    inquire_data id = { &in.inquireData, &ctx };

    const QString socketName = out.serverLocation;
    if (socketName.isEmpty()) {
        out.errorString = i18n("Invalid socket name!");
        goto leave;
    }

#ifndef HAVE_ASSUAN2
    err = assuan_socket_connect(&naked_ctx, QFile::encodeName(socketName).constData(), -1);
#else
    {
        assuan_context_t naked_ctx = nullptr;
        err = assuan_new(&naked_ctx);
        if (err) {
            out.errorString = i18n("Could not allocate resources to connect to Kleopatra UI server at %1: %2"
                                   , socketName, to_error_string(err));
            goto leave;
        }

        ctx.reset(naked_ctx);
    }

    err = assuan_socket_connect(ctx.get(), QFile::encodeName(socketName).constData(), -1, 0);
#endif
    if (err) {
        qDebug("UI server not running, starting it");

        const QString errorString = start_uiserver();
        if (!errorString.isEmpty()) {
            out.errorString = errorString;
            goto leave;
        }

        // give it a bit of time to start up and try a couple of times
        for (int i = 0; err && i < 20; ++i) {
            msleep(500);
#ifndef HAVE_ASSUAN2
            err = assuan_socket_connect(&naked_ctx, QFile::encodeName(socketName).constData(), -1);
#else
            err = assuan_socket_connect(ctx.get(), QFile::encodeName(socketName).constData(), -1, 0);
#endif
        }
    }

    if (err) {
        out.errorString = i18n("Could not connect to Kleopatra UI server at %1: %2",
                               socketName, to_error_string(err));
        goto leave;
    }

#ifndef HAVE_ASSUAN2
    ctx.reset(naked_ctx);
    naked_ctx = 0;
#endif

    out.serverPid = -1;
    err = my_assuan_transact(ctx, "GETINFO pid", &getinfo_pid_cb, &out.serverPid);
    if (err || out.serverPid <= 0) {
        out.errorString = i18n("Could not get the process-id of the Kleopatra UI server at %1: %2", socketName, to_error_string(err));
        goto leave;
    }

    qCDebug(LIBKLEOPATRACLIENTCORE_LOG) << "Server PID =" << out.serverPid;

#if defined(Q_OS_WIN)
    if (!AllowSetForegroundWindow((pid_t)out.serverPid)) {
        qCDebug(LIBKLEOPATRACLIENTCORE_LOG) << "AllowSetForegroundWindow(" << out.serverPid << ") failed: " << GetLastError();
    }
#endif

    if (in.command.isEmpty()) {
        goto leave;
    }

    if (in.parentWId) {
#if defined(Q_OS_WIN32)
        err = send_option(ctx, "window-id", QString().sprintf("%lx", reinterpret_cast<quintptr>(in.parentWId)));
#else
        err = send_option(ctx, "window-id", QString().sprintf("%lx", static_cast<unsigned long>(in.parentWId)));
#endif
        if (err) {
            qDebug("sending option window-id failed - ignoring");
        }
    }

    for (std::map<std::string, Option>::const_iterator it = in.options.begin(), end = in.options.end(); it != end; ++it)
        if ((err = send_option(ctx, it->first.c_str(), it->second.hasValue ? it->second.value.toString() : QVariant()))) {
            if (it->second.isCritical) {
                out.errorString = i18n("Failed to send critical option %1: %2", QString::fromLatin1(it->first.c_str()), to_error_string(err));
                goto leave;
            } else {
                qCDebug(LIBKLEOPATRACLIENTCORE_LOG) << "Failed to send non-critical option" << it->first.c_str() << ":" << to_error_string(err);
            }
        }

    Q_FOREACH (const QString &filePath, in.filePaths)
        if ((err = send_file(ctx, filePath))) {
            out.errorString = i18n("Failed to send file path %1: %2", filePath, to_error_string(err));
            goto leave;
        }

    Q_FOREACH (const QString &sender, in.senders)
        if ((err = send_sender(ctx, sender, in.areSendersInformative))) {
            out.errorString = i18n("Failed to send sender %1: %2", sender, to_error_string(err));
            goto leave;
        }

    Q_FOREACH (const QString &recipient, in.recipients)
        if ((err = send_recipient(ctx, recipient, in.areRecipientsInformative))) {
            out.errorString = i18n("Failed to send recipient %1: %2", recipient, to_error_string(err));
            goto leave;
        }

#if 0
    setup I / O;
#endif

    err = my_assuan_transact(ctx, in.command.constData(), &command_data_cb, &out.data, &command_inquire_cb, &id);
    if (err) {
        if (gpg_err_code(err) == GPG_ERR_CANCELED) {
            out.canceled = true;
        } else {
            out.errorString = i18n("Command (%1) failed: %2", QString::fromLatin1(in.command.constData()), to_error_string(err));
        }
        goto leave;
    }

leave:
    const QMutexLocker locker(&mutex);
    // copy outputs to where Command can see them:
    outputs = out;
}