File: kgpginterface.cpp

package info (click to toggle)
kgpg 4:18.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 12,168 kB
  • sloc: cpp: 18,911; xml: 159; makefile: 8; sh: 4
file content (417 lines) | stat: -rw-r--r-- 11,937 bytes parent folder | download | duplicates (4)
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
/*
 * Copyright (C) 2002 Jean-Baptiste Mardelle <bj@altern.org>
 * Copyright (C) 2007,2008,2009,2010,2011,2012,2013,2016,2017
 *               Rolf Eike Beer <kde@opensource.sf-tec.de>
 */
/***************************************************************************
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "kgpginterface.h"

#include "gpgproc.h"
#include "core/convert.h"
#include "core/KGpgKeyNode.h"
#include "core/KGpgSignNode.h"
#include "core/KGpgSubkeyNode.h"
#include "core/KGpgUatNode.h"
#include "core/KGpgUidNode.h"
#include "kgpgsettings.h"

#include <gpgme.h>
#include <KLocalizedString>
#include <KMessageBox>
#include <KProcess>
#include <QFile>
#include <QString>
#include <QTextStream>

using namespace KgpgCore;

QString KgpgInterface::getGpgSetting(const QString &name, const QString &configfile)
{
	const QString tmp = name.simplified() + QLatin1Char(' ');
	QFile qfile(configfile);

	if (qfile.exists() && qfile.open(QIODevice::ReadOnly)) {
		QTextStream t(&qfile);
		while (!t.atEnd()) {
			QString result(t.readLine().simplified());
			if (result.startsWith(tmp)) {
				result = result.mid(tmp.length()).simplified();
				return result.section(QLatin1Char( ' ' ), 0, 0);
			}
		}
		qfile.close();
	}

	return QString();
}

void KgpgInterface::setGpgSetting(const QString &name, const QString &value, const QString &url)
{
	QFile qfile(url);

	if (qfile.exists() && qfile.open(QIODevice::ReadOnly)) {
		const QString temp = name + QLatin1Char(' ');
		QString texttowrite;
		bool found = false;
		QTextStream t(&qfile);

		while (!t.atEnd()) {
			QString result = t.readLine();
			if (result.simplified().startsWith(temp)) {
				if (!value.isEmpty())
					result = temp + QLatin1Char( ' ' ) + value;
				else
					result.clear();
				found = true;
			}

			texttowrite += result + QLatin1Char( '\n' );
		}

		qfile.close();
		if ((!found) && (!value.isEmpty()))
			texttowrite += QLatin1Char( '\n' ) + temp + QLatin1Char( ' ' ) + value;

		if (qfile.open(QIODevice::WriteOnly)) {
			QTextStream t(&qfile);
			t << texttowrite;
			qfile.close();
		}
	}
}

bool KgpgInterface::getGpgBoolSetting(const QString &name, const QString &configfile)
{
	QFile qfile(configfile);
	if (qfile.exists() && qfile.open(QIODevice::ReadOnly)) {
		QTextStream t(&qfile);
		while (!t.atEnd()) {
			if (t.readLine().simplified().startsWith(name))
				return true;
		}
		qfile.close();
	}
	return false;
}

void KgpgInterface::setGpgBoolSetting(const QString &name, const bool enable, const QString &url)
{
	QFile qfile(url);

	if (qfile.exists() && qfile.open(QIODevice::ReadOnly)) {
		QString texttowrite;
		bool found = false;
		QTextStream t(&qfile);

		while (!t.atEnd()) {
			QString result(t.readLine());

			if (result.simplified().startsWith(name)) {
				if (enable)
					result = name;
				else
					result.clear();

				found = true;
			}

			texttowrite += result + QLatin1Char( '\n' );
		}
		qfile.close();

		if ((!found) && (enable))
			texttowrite += name;

		if (qfile.open(QIODevice::WriteOnly)) {
			QTextStream t(&qfile);
			t << texttowrite;
			qfile.close();
		}
	}
}

/**
 * @param p the process that reads the GnuPG data
 * @param readNode the node where the signatures are read for
 */
static KgpgCore::KgpgKeyList
readPublicKeysProcess(GPGProc &p, KGpgKeyNode *readNode)
{
	QStringList lsp;
	int items;
	KgpgCore::KgpgKeyList publiclistkeys;
	KgpgCore::KgpgKey *publickey = nullptr;
	unsigned int idIndex = 0;
	QString log;
	KGpgSignableNode *currentSNode = nullptr;	///< the current (sub)node signatures are read for

	while ((items = p.readln(lsp)) >= 0) {
		if ((lsp.at(0) == QLatin1String( "pub" )) && (items >= 10)) {
			KgpgSubKeyType subtype;
			KgpgSubKeyType keytype;
			bool enabled = true;
			if (items > 11) {
				const QString &caps = lsp.at(11);

				enabled = !caps.contains(QLatin1Char('D'), Qt::CaseSensitive);

				subtype = Convert::toSubType(caps, false);
				keytype = Convert::toSubType(caps, true);
			}

			const QString curve = (items > 16) ? lsp.at(16) : QString();
			publiclistkeys << KgpgKey(lsp.at(4), lsp.at(2).toUInt(), Convert::toTrust(lsp.at(1)),
					Convert::toAlgo(lsp.at(3)), subtype, keytype,
					Convert::toDateTime(lsp.at(5)), curve);

			publickey = &publiclistkeys.last();

			const QString &owTrust = lsp.at(8);
			if (owTrust.isEmpty())
				publickey->setOwnerTrust(GPGME_VALIDITY_UNDEFINED);
			else
				publickey->setOwnerTrust(Convert::toOwnerTrust(owTrust[0]));

			publickey->setExpiration(Convert::toDateTime(lsp.at(6)));

			publickey->setValid(enabled);  // disabled key

			// GnuPG since 2.1 can flag immediately if a key has a secret key
			if (items > 14 && lsp.at(14).contains(QLatin1Char('+')))
				publickey->setSecret(true);

			idIndex = 0;
		} else if (publickey && (lsp.at(0) == QLatin1String("fpr")) && (items >= 10)) {
			const QString &fingervalue = lsp.at(9);

			if ((currentSNode != nullptr) && (currentSNode->getType() == ITYPE_SUB))
				static_cast<KGpgSubkeyNode *>(currentSNode)->setFingerprint(fingervalue);
			else if (publickey->fingerprint().isEmpty())
				publickey->setFingerprint(fingervalue);
		} else if (publickey && (lsp.at(0) == QLatin1String( "sub" )) && (items >= 7)) {
			KgpgSubKeyType subtype;

			if (items > 11)
				subtype = Convert::toSubType(lsp.at(11), false);

			const QString curve = (items > 16) ? lsp.at(16) : QString();
			KgpgKeySub sub(lsp.at(4), lsp.at(2).toUInt(), Convert::toTrust(lsp.at(1)),
					Convert::toAlgo(lsp.at(3)), subtype, Convert::toDateTime(lsp.at(5)),
					curve);

			// FIXME: Please see kgpgkey.h, KgpgSubKey class
			if (items <= 11)
				sub.setValid(true);
			else
				sub.setValid(!lsp.at(11).contains(QLatin1Char( 'D' )));

			sub.setExpiration(Convert::toDateTime(lsp.at(6)));

			publickey->subList()->append(sub);
			if (readNode == nullptr)
				currentSNode = nullptr;
			else
				currentSNode = new KGpgSubkeyNode(readNode, sub);
		} else if (publickey && (lsp.at(0) == QLatin1String( "uat" ))) {
			idIndex++;
			if (readNode != nullptr) {
				currentSNode = new KGpgUatNode(readNode, idIndex, lsp);
			}
		} else if (publickey && (lsp.at(0) == QLatin1String( "uid" )) && (items >= 10)) {
			if (idIndex == 0) {
				QString fullname(lsp.at(9));
				QString kmail;
				if (fullname.contains(QLatin1Char( '<' )) ) {
					kmail = fullname;

					if (fullname.contains(QLatin1Char( ')' )) )
						kmail = kmail.section(QLatin1Char( ')' ), 1);

					kmail = kmail.section(QLatin1Char( '<' ), 1);
					kmail.truncate(kmail.length() - 1);

					if (kmail.contains(QLatin1Char( '<' ))) {
						// several email addresses in the same key
						kmail = kmail.replace(QLatin1Char( '>' ), QLatin1Char( ';' ));
						kmail.remove(QLatin1Char( '<' ));
					}
				}

				QString kname(fullname.section( QLatin1String( " <" ), 0, 0));
				QString comment;
				if (fullname.contains(QLatin1Char( '(' )) ) {
					kname = kname.section( QLatin1String( " (" ), 0, 0);
					comment = fullname.section(QLatin1Char( '(' ), 1, 1);
					comment = comment.section(QLatin1Char( ')' ), 0, 0);
				}

				idIndex++;
				publickey->setEmail(kmail);
				publickey->setComment(comment);
				publickey->setName(kname);

				currentSNode = readNode;
			} else {
				idIndex++;
				if (readNode != nullptr) {
					currentSNode = new KGpgUidNode(readNode, idIndex, lsp);
				}
			}
		} else if (publickey && ((lsp.at(0) == QLatin1String( "sig" )) || (lsp.at(0) == QLatin1String( "rev" ))) && (items >= 11)) {
			// there are no strings here that could have a recoded QLatin1Char( ':' ) in them
			const QString signature = lsp.join(QLatin1String(":"));

			if (currentSNode != nullptr)
				(void) new KGpgSignNode(currentSNode, lsp);
		} else {
			log += lsp.join(QString(QLatin1Char( ':' ))) + QLatin1Char( '\n' );
		}
	}

	if (p.exitCode() != 0) {
		KMessageBox::detailedError(nullptr, i18n("An error occurred while scanning your keyring"), log);
		log.clear();
	}

	return publiclistkeys;
}

KgpgKeyList KgpgInterface::readPublicKeys(const QStringList &ids)
{
	GPGProc process;
	process <<
			QLatin1String("--with-colons") <<
			QLatin1String("--with-fingerprint") <<
			QLatin1String("--fixed-list-mode") <<
			QLatin1String("--list-keys");

	if (GPGProc::gpgVersion(GPGProc::gpgVersionString(KGpgSettings::gpgBinaryPath())) > 0x20100)
		process << QLatin1String("--with-secret");

	process << ids;

	process.setOutputChannelMode(KProcess::MergedChannels);

	process.start();
	process.waitForFinished(-1);
	return readPublicKeysProcess(process, nullptr);
}

void KgpgInterface::readSignatures(KGpgKeyNode *node)
{
	GPGProc process;
	process <<
			QLatin1String("--with-colons") <<
			QLatin1String("--with-fingerprint") <<
			QLatin1String("--fixed-list-mode") <<
			QLatin1String("--list-sigs") <<
			node->getId();

	process.setOutputChannelMode(KProcess::MergedChannels);

	process.start();
	process.waitForFinished(-1);

	readPublicKeysProcess(process, node);
}

static KgpgCore::KgpgKeyList
readSecretKeysProcess(GPGProc &p)
{
	QStringList lsp;
	int items;
	bool hasuid = false;
	KgpgCore::KgpgKeyList result;
	KgpgCore::KgpgKey *secretkey = nullptr;

	while ( (items = p.readln(lsp)) >= 0 ) {
		if ((lsp.at(0) == QLatin1String( "sec" )) && (items >= 10)) {
			KgpgSubKeyType subtype;
			KgpgSubKeyType keytype;

			if (items >= 11) {
				const QString &caps = lsp.at(11);

				subtype = Convert::toSubType(caps, false);
				keytype = Convert::toSubType(caps, true);
			}

			const QString curve = (items > 16) ? lsp.at(16) : QString();
			result << KgpgKey(lsp.at(4), lsp.at(2).toUInt(), Convert::toTrust(lsp.at(1)),
				Convert::toAlgo(lsp.at(3)), subtype, keytype,
				Convert::toDateTime(lsp.at(5)), curve);

			secretkey = &result.last();

			secretkey->setSecret(true);

			secretkey->setExpiration(Convert::toDateTime(lsp.at(6)));

			hasuid = true;
		} else if ((lsp.at(0) == QLatin1String( "uid" )) && (items >= 10)) {
			if (hasuid)
				continue;

			hasuid = true;

			const QString &fullname = lsp.at(9);
			if (fullname.contains(QLatin1Char( '<' ) )) {
				QString kmail(fullname);

				if (fullname.contains(QLatin1Char( ')' ) ))
					kmail = kmail.section(QLatin1Char( ')' ), 1);

				kmail = kmail.section(QLatin1Char( '<' ), 1);
				kmail.truncate(kmail.length() - 1);

				if (kmail.contains(QLatin1Char( '<' ) )) { // several email addresses in the same key
					kmail = kmail.replace(QLatin1Char( '>' ), QLatin1Char( ';' ));
					kmail.remove(QLatin1Char( '<' ));
				}

				secretkey->setEmail(kmail);
			} else {
				secretkey->setEmail(QString());
			}

			QString kname(fullname.section( QLatin1String( " <" ), 0, 0));
			if (fullname.contains(QLatin1Char( '(' ) )) {
				kname = kname.section( QLatin1String( " (" ), 0, 0);
				QString comment = fullname.section(QLatin1Char( '(' ), 1, 1);
				comment = comment.section(QLatin1Char( ')' ), 0, 0);

				secretkey->setComment(comment);
			} else {
				secretkey->setComment(QString());
			}
			secretkey->setName(kname);
		} else if ((lsp.at(0) == QLatin1String( "fpr" )) && (items >= 10)) {
			secretkey->setFingerprint(lsp.at(9));
		}
	}

	return result;
}

KgpgKeyList KgpgInterface::readSecretKeys(const QStringList &ids)
{
	GPGProc process;
	process <<
			QLatin1String("--with-colons") <<
			QLatin1String("--list-secret-keys") <<
			QLatin1String("--with-fingerprint") <<
			QLatin1String("--fixed-list-mode") <<
			ids;

	process.start();
	process.waitForFinished(-1);
	return readSecretKeysProcess(process);
}