Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Plugins.cpp « mumble « src - github.com/mumble-voip/mumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fca8876bffb260f92f108820e88f7cb9b7070414 (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
// Copyright 2005-2019 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#include "Plugins.h"

#include "Log.h"
#include "MainWindow.h"
#include "Message.h"
#include "ServerHandler.h"
#include "../../plugins/mumble_plugin.h"
#include "WebFetch.h"
#include "MumbleApplication.h"
#include "ManualPlugin.h"
#include "Utils.h"

#include <QtCore/QLibrary>
#include <QtCore/QUrlQuery>

#ifdef Q_OS_WIN
# include <QtCore/QTemporaryFile>
#endif

#include <QtWidgets/QMessageBox>
#include <QtXml/QDomDocument>

#ifdef Q_OS_WIN
# include <softpub.h>
# include <tlhelp32.h>
#endif

// We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include.
#include "Global.h"

static ConfigWidget *PluginConfigDialogNew(Settings &st) {
	return new PluginConfig(st);
}

static ConfigRegistrar registrar(5000, PluginConfigDialogNew);

struct PluginInfo {
	bool locked;
	bool enabled;
	QLibrary lib;
	QString filename;
	QString description;
	QString shortname;
	MumblePlugin *p;
	MumblePlugin2 *p2;
	MumblePluginQt *pqt;
	PluginInfo();
};

PluginInfo::PluginInfo() {
	locked = false;
	enabled = false;
	p = NULL;
	p2 = NULL;
	pqt = NULL;
}

struct PluginFetchMeta {
	QString hash;
	QString path;
	
	PluginFetchMeta(const QString &hash_ = QString(), const QString &path_ = QString())
		: hash(hash_)
		, path(path_) { /* Empty */ }
};


PluginConfig::PluginConfig(Settings &st) : ConfigWidget(st) {
	setupUi(this);

#if QT_VERSION >= 0x050000
	qtwPlugins->header()->setSectionResizeMode(0, QHeaderView::Stretch);
	qtwPlugins->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
#else
	qtwPlugins->header()->setResizeMode(0, QHeaderView::Stretch);
	qtwPlugins->header()->setResizeMode(1, QHeaderView::ResizeToContents);
#endif

	refillPluginList();
}

QString PluginConfig::title() const {
	return tr("Plugins");
}

QIcon PluginConfig::icon() const {
	return QIcon(QLatin1String("skin:config_plugin.png"));
}

void PluginConfig::load(const Settings &r) {
	loadCheckBox(qcbTransmit, r.bTransmitPosition);
}

void PluginConfig::save() const {
	QReadLocker lock(&g.p->qrwlPlugins);

	s.bTransmitPosition = qcbTransmit->isChecked();
	s.qmPositionalAudioPlugins.clear();

	QList<QTreeWidgetItem *> list = qtwPlugins->findItems(QString(), Qt::MatchContains);
	foreach(QTreeWidgetItem *i, list) {
		bool enabled = (i->checkState(1) == Qt::Checked);

		PluginInfo *pi = pluginForItem(i);
		if (pi) {
			s.qmPositionalAudioPlugins.insert(pi->filename, enabled);
			pi->enabled = enabled;
		}
	}
}

PluginInfo *PluginConfig::pluginForItem(QTreeWidgetItem *i) const {
	if (i) {
		foreach(PluginInfo *pi, g.p->qlPlugins) {
			if (pi->filename == i->data(0, Qt::UserRole).toString())
				return pi;
		}
	}
	return NULL;
}

void PluginConfig::on_qpbConfig_clicked() {
	PluginInfo *pi;
	{
		QReadLocker lock(&g.p->qrwlPlugins);
		pi = pluginForItem(qtwPlugins->currentItem());
	}

	if (! pi)
		return;

	if (pi->pqt && pi->pqt->config) {
		pi->pqt->config(this);
	} else if (pi->p->config) {
		pi->p->config(0);
	} else {
		QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no configure function."), QMessageBox::Ok, QMessageBox::NoButton);
	}
}

void PluginConfig::on_qpbAbout_clicked() {
	PluginInfo *pi;
	{
		QReadLocker lock(&g.p->qrwlPlugins);
		pi = pluginForItem(qtwPlugins->currentItem());
	}

	if (! pi)
		return;

	if (pi->pqt && pi->pqt->about) {
		pi->pqt->about(this);
	} else if (pi->p->about) {
		pi->p->about(0);
	} else {
		QMessageBox::information(this, QLatin1String("Mumble"), tr("Plugin has no about function."), QMessageBox::Ok, QMessageBox::NoButton);
	}
}

void PluginConfig::on_qpbReload_clicked() {
	g.p->rescanPlugins();
	refillPluginList();
}

void PluginConfig::refillPluginList() {
	QReadLocker lock(&g.p->qrwlPlugins);
	qtwPlugins->clear();

	foreach(PluginInfo *pi, g.p->qlPlugins) {
		QTreeWidgetItem *i = new QTreeWidgetItem(qtwPlugins);
		i->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
		i->setCheckState(1, pi->enabled ? Qt::Checked : Qt::Unchecked);
		i->setText(0, pi->description);
		if (pi->p->longdesc)
			i->setToolTip(0, Qt::escape(QString::fromStdWString(pi->p->longdesc())));
		i->setData(0, Qt::UserRole, pi->filename);
	}
	qtwPlugins->setCurrentItem(qtwPlugins->topLevelItem(0));
	on_qtwPlugins_currentItemChanged(qtwPlugins->topLevelItem(0), NULL);
}

void PluginConfig::on_qtwPlugins_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) {
	QReadLocker lock(&g.p->qrwlPlugins);

	PluginInfo *pi=pluginForItem(current);
	if (pi) {
		bool showAbout = false;
		if (pi->p->about) {
			showAbout = true;
		}
		if (pi->pqt && pi->pqt->about) {
			showAbout = true;
		}
		qpbAbout->setEnabled(showAbout);

		bool showConfig = false;
		if (pi->p->config) {
			showConfig = true;
		}
		if (pi->pqt && pi->pqt->config) {
			showConfig = true;
		}
		qpbConfig->setEnabled(showConfig);
	} else {
		qpbAbout->setEnabled(false);
		qpbConfig->setEnabled(false);
	}
}

Plugins::Plugins(QObject *p) : QObject(p) {
	QTimer *timer=new QTimer(this);
	timer->setObjectName(QLatin1String("Timer"));
	timer->start(500);
	locked = prevlocked = NULL;
	bValid = false;
	iPluginTry = 0;
	for (int i=0;i<3;i++)
		fPosition[i]=fFront[i]=fTop[i]= 0.0;
	QMetaObject::connectSlotsByName(this);

#ifdef QT_NO_DEBUG
#ifndef PLUGIN_PATH
	qsSystemPlugins=QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath());
#ifdef Q_OS_MAC
	qsSystemPlugins=QString::fromLatin1("%1/../Plugins").arg(qApp->applicationDirPath());
#endif
#else
	qsSystemPlugins=QLatin1String(MUMTEXT(PLUGIN_PATH));
#endif

	qsUserPlugins = g.qdBasePath.absolutePath() + QLatin1String("/Plugins");
#else
	qsSystemPlugins = QString::fromLatin1("%1/plugins").arg(MumbleApplication::instance()->applicationVersionRootPath());
	qsUserPlugins = QString();
#endif

#ifdef Q_OS_WIN
	// According to MS KB Q131065, we need this to OpenProcess()

	hToken = NULL;

	if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) {
		if (GetLastError() == ERROR_NO_TOKEN) {
			ImpersonateSelf(SecurityImpersonation);
			OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken);
		}
	}

	TOKEN_PRIVILEGES tp;
	LUID luid;
	cbPrevious=sizeof(TOKEN_PRIVILEGES);

	LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

	tp.PrivilegeCount           = 1;
	tp.Privileges[0].Luid       = luid;
	tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

	AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious);
#endif
}

Plugins::~Plugins() {
	clearPlugins();

#ifdef Q_OS_WIN
	AdjustTokenPrivileges(hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL);
	CloseHandle(hToken);
#endif
}

void Plugins::clearPlugins() {
	QWriteLocker lock(&g.p->qrwlPlugins);
	foreach(PluginInfo *pi, qlPlugins) {
		if (pi->locked)
			pi->p->unlock();
		pi->lib.unload();
		delete pi;
	}
	qlPlugins.clear();
}

void Plugins::rescanPlugins() {
	clearPlugins();

	QWriteLocker lock(&g.p->qrwlPlugins);
	prevlocked = locked = NULL;
	bValid = false;

	QDir qd(qsSystemPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable);
#ifdef QT_NO_DEBUG
	QDir qud(qsUserPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable);
	QFileInfoList libs = qud.entryInfoList() + qd.entryInfoList();
#else
	QFileInfoList libs = qd.entryInfoList();
#endif

	QSet<QString> evaluated;
	foreach(const QFileInfo &libinfo, libs) {
		QString fname = libinfo.fileName();
		QString libname = libinfo.absoluteFilePath();
		if (!evaluated.contains(fname) && QLibrary::isLibrary(libname)) {
			PluginInfo *pi = new PluginInfo();
			pi->lib.setFileName(libname);
			pi->filename = fname;
			if (pi->lib.load()) {
				mumblePluginFunc mpf = reinterpret_cast<mumblePluginFunc>(pi->lib.resolve("getMumblePlugin"));
				if (mpf) {
					evaluated.insert(fname);
					pi->p = mpf();

					// Check whether the plugin has a valid plugin magic and that it's not retracted.
					// A retracted plugin is a plugin that clients should disregard, typically because
					// the game the plugin was written for now provides positional audio via the
					// link plugin (see null_plugin.cpp).
					if (pi->p && pi->p->magic == MUMBLE_PLUGIN_MAGIC && pi->p->shortname != L"Retracted") {

						pi->description = QString::fromStdWString(pi->p->description);
						pi->shortname = QString::fromStdWString(pi->p->shortname);
						pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true);

						mumblePlugin2Func mpf2 = reinterpret_cast<mumblePlugin2Func>(pi->lib.resolve("getMumblePlugin2"));
						if (mpf2) {
							pi->p2 = mpf2();
							if (pi->p2->magic != MUMBLE_PLUGIN_MAGIC_2) {
								pi->p2 = NULL;
							}
						}

						mumblePluginQtFunc mpfqt = reinterpret_cast<mumblePluginQtFunc>(pi->lib.resolve("getMumblePluginQt"));
						if (mpfqt) {
							pi->pqt = mpfqt();
							if (pi->pqt->magic != MUMBLE_PLUGIN_MAGIC_QT) {
								pi->pqt = NULL;
							}
						}

						qlPlugins << pi;
						continue;
					}
				}
				pi->lib.unload();
			} else {
				qWarning("Plugins: Failed to load %s: %s", qPrintable(pi->filename), qPrintable(pi->lib.errorString()));
			}
			delete pi;
		}
	}

	// Handle built-in plugins
	{
#if defined(USE_MANUAL_PLUGIN)
		// Manual plugin
		PluginInfo *pi = new PluginInfo();
		pi->filename = QLatin1String("manual.builtin");
		pi->p = ManualPlugin_getMumblePlugin();
		pi->pqt = ManualPlugin_getMumblePluginQt();
		pi->description = QString::fromStdWString(pi->p->description);
		pi->shortname = QString::fromStdWString(pi->p->shortname);
		pi->enabled = g.s.qmPositionalAudioPlugins.value(pi->filename, true);
		qlPlugins << pi;
#endif
	}
}

bool Plugins::fetch() {
	if (g.bPosTest) {
		fPosition[0] = fPosition[1] = fPosition[2] = 0.0f;
		fFront[0] = 0.0f;
		fFront[1] = 0.0f;
		fFront[2] = 1.0f;
		fTop[0] = 0.0f;
		fTop[1] = 1.0f;
		fTop[2] = 0.0f;

		for (int i=0;i<3;++i) {
			fCameraPosition[i] = fPosition[i];
			fCameraFront[i] = fFront[i];
			fCameraTop[i] = fTop[i];
		}

		bValid = true;
		return true;
	}

	if (! locked) {
		bValid = false;
		return bValid;
	}

	QReadLocker lock(&qrwlPlugins);
	if (! locked) {
		bValid = false;
		return bValid;
	}

	if (!locked->enabled)
		bUnlink = true;

	bool ok;
	{
		QMutexLocker mlock(&qmPluginStrings);
		ok = locked->p->fetch(fPosition, fFront, fTop, fCameraPosition, fCameraFront, fCameraTop, ssContext, swsIdentity);
	}
	if (! ok || bUnlink) {
		lock.unlock();
		QWriteLocker wlock(&qrwlPlugins);

		if (locked) {
			locked->p->unlock();
			locked->locked = false;
			prevlocked = locked;
			locked = NULL;
			for (int i=0;i<3;i++)
				fPosition[i]=fFront[i]=fTop[i]=fCameraPosition[i]=fCameraFront[i]=fCameraTop[i] = 0.0f;
		}
	}
	bValid = ok;
	return bValid;
}

void Plugins::on_Timer_timeout() {
	fetch();

	QReadLocker lock(&qrwlPlugins);

	if (prevlocked) {
		g.l->log(Log::Information, tr("%1 lost link.").arg(Qt::escape(prevlocked->shortname)));
		prevlocked = NULL;
	}


	{
		QMutexLocker mlock(&qmPluginStrings);

		if (! locked) {
			ssContext.clear();
			swsIdentity.clear();
		}

		std::string context;
		if (locked)
			context.assign(u8(QString::fromStdWString(locked->p->shortname)) + static_cast<char>(0) + ssContext);

		if (! g.uiSession) {
			ssContextSent.clear();
			swsIdentitySent.clear();
		} else if ((context != ssContextSent) || (swsIdentity != swsIdentitySent)) {
			MumbleProto::UserState mpus;
			mpus.set_session(g.uiSession);
			if (context != ssContextSent) {
				ssContextSent.assign(context);
				mpus.set_plugin_context(context);
			}
			if (swsIdentity != swsIdentitySent) {
				swsIdentitySent.assign(swsIdentity);
				mpus.set_plugin_identity(u8(QString::fromStdWString(swsIdentitySent)));
			}
			if (g.sh)
				g.sh->sendMessage(mpus);
		}
	}

	if (locked) {
		return;
	}

	if (! g.s.bTransmitPosition)
		return;

	lock.unlock();
	QWriteLocker wlock(&qrwlPlugins);

	if (qlPlugins.isEmpty())
		return;

	++iPluginTry;
	if (iPluginTry >= qlPlugins.count())
		iPluginTry = 0;

	std::multimap<std::wstring, unsigned long long int> pids;
#if defined(Q_OS_WIN)
	PROCESSENTRY32 pe;

	pe.dwSize = sizeof(pe);
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnap != INVALID_HANDLE_VALUE) {
		BOOL ok = Process32First(hSnap, &pe);

		while (ok) {
			pids.insert(std::pair<std::wstring, unsigned long long int>(std::wstring(pe.szExeFile), pe.th32ProcessID));
			ok = Process32Next(hSnap, &pe);
		}
		CloseHandle(hSnap);
	}
#elif defined(Q_OS_LINUX)
	QDir d(QLatin1String("/proc"));
	QStringList entries = d.entryList();
	bool ok;
	foreach (const QString &entry, entries) {
		// Check if the entry is a PID
		// by checking whether it's a number.
		// If it is not, skip it.
		unsigned long long int pid = static_cast<unsigned long long int>(entry.toLongLong(&ok, 10));
		if (!ok) {
			continue;
		}

		QString exe = QFile::symLinkTarget(QString(QLatin1String("/proc/%1/exe")).arg(entry));
		QFileInfo fi(exe);
		QString firstPart = fi.baseName();
		QString completeSuffix = fi.completeSuffix();
		QString baseName;
		if (completeSuffix.isEmpty()) {
			baseName = firstPart;
		} else {
			baseName = firstPart + QLatin1String(".") + completeSuffix;
		}

		if (baseName == QLatin1String("wine-preloader") || baseName == QLatin1String("wine64-preloader")) {
			QFile f(QString(QLatin1String("/proc/%1/cmdline")).arg(entry));
			if (f.open(QIODevice::ReadOnly)) {
				QByteArray cmdline = f.readAll();
				f.close();

				int nul = cmdline.indexOf('\0');
				if (nul != -1) {
					cmdline.truncate(nul);
				}

				QString exe = QString::fromUtf8(cmdline);
				if (exe.contains(QLatin1String("\\"))) {
					int lastBackslash = exe.lastIndexOf(QLatin1String("\\"));
					if (exe.count() > lastBackslash + 1) {
						baseName = exe.mid(lastBackslash + 1);
					}
				}
			}
		}

		if (!baseName.isEmpty()) {
			pids.insert(std::pair<std::wstring, unsigned long long int>(baseName.toStdWString(), pid));
		}
	}
#endif

	PluginInfo *pi = qlPlugins.at(iPluginTry);
	if (pi->enabled) {
		if (pi->p2 ? pi->p2->trylock(pids) : pi->p->trylock()) {
			pi->shortname = QString::fromStdWString(pi->p->shortname);
			g.l->log(Log::Information, tr("%1 linked.").arg(Qt::escape(pi->shortname)));
			pi->locked = true;
			bUnlink = false;
			locked = pi;
		}
	}
}

void Plugins::checkUpdates() {
	QUrl url;
	url.setPath(QLatin1String("/v1/pa-plugins"));

	QList<QPair<QString, QString> > queryItems;
	queryItems << qMakePair(QString::fromUtf8("ver"), QString::fromUtf8(QUrl::toPercentEncoding(QString::fromUtf8(MUMBLE_RELEASE))));
#if defined(Q_OS_WIN)
# if defined(Q_OS_WIN64)
	queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("WinX64"));
# else
	queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("Win32"));
# endif
	queryItems << qMakePair(QString::fromUtf8("abi"), QString::fromUtf8(MUMTEXT(_MSC_VER)));
#elif defined(Q_OS_MAC)
# if defined(USE_MAC_UNIVERSAL)
	queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("MacOSX-Universal"));
# else
	queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("MacOSX"));
# endif
#else
	queryItems << qMakePair(QString::fromUtf8("os"), QString::fromUtf8("Unix"));
#endif


#ifdef QT_NO_DEBUG
#if QT_VERSION >= 0x050000
	QUrlQuery query;
	query.setQueryItems(queryItems);
	url.setQuery(query);
#else
	for (int i = 0; i < queryItems.size(); i++) {
		const QPair<QString, QString> &queryPair = queryItems.at(i);
		url.addQueryItem(queryPair.first, queryPair.second);
	}
#endif
	WebFetch::fetch(QLatin1String("update"), url, this, SLOT(fetchedUpdatePAPlugins(QByteArray,QUrl)));
#else
	g.mw->msgBox(tr("Skipping plugin update in debug mode."));
#endif
}

void Plugins::fetchedUpdatePAPlugins(QByteArray data, QUrl) {
	if (data.isNull())
		return;

	bool rescan = false;
	qmPluginFetchMeta.clear();
	QDomDocument doc;
	doc.setContent(data);

	QDomElement root=doc.documentElement();
	QDomNode n = root.firstChild();
	while (!n.isNull()) {
		QDomElement e = n.toElement();
		if (!e.isNull()) {
			if (e.tagName() == QLatin1String("plugin")) {
				QString name = QFileInfo(e.attribute(QLatin1String("name"))).fileName();
				QString hash = e.attribute(QLatin1String("hash"));
				QString path = e.attribute(QLatin1String("path"));
				qmPluginFetchMeta.insert(name, PluginFetchMeta(hash, path));
			}
		}
		n = n.nextSibling();
	}

	QDir qd(qsSystemPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable);
	QDir qdu(qsUserPlugins, QString(), QDir::Name, QDir::Files | QDir::Readable);

	QFileInfoList libs = qd.entryInfoList();
	foreach(const QFileInfo &libinfo, libs) {
		QString libname = libinfo.absoluteFilePath();
		QString filename = libinfo.fileName();
		PluginFetchMeta pfm = qmPluginFetchMeta.value(filename);
		QString wanthash = pfm.hash;
		if (! wanthash.isNull() && QLibrary::isLibrary(libname)) {
			QFile f(libname);
			if (wanthash.isEmpty()) {
				// Outdated plugin
				if (f.exists()) {
					clearPlugins();
					f.remove();
					rescan=true;
				}
			} else if (f.open(QIODevice::ReadOnly)) {
				QString h = QLatin1String(sha1(f.readAll()).toHex());
				f.close();
				if (h == wanthash) {
					if (qd != qdu) {
						QFile qfuser(qsUserPlugins + QString::fromLatin1("/") + filename);
						if (qfuser.exists()) {
							clearPlugins();
							qfuser.remove();
							rescan=true;
						}
					}
					// Mark for removal from userplugins
					qmPluginFetchMeta.insert(filename, PluginFetchMeta());
				}
			}
		}
	}

	if (qd != qdu) {
		libs = qdu.entryInfoList();
		foreach(const QFileInfo &libinfo, libs) {
			QString libname = libinfo.absoluteFilePath();
			QString filename = libinfo.fileName();
			PluginFetchMeta pfm = qmPluginFetchMeta.value(filename);
			QString wanthash = pfm.hash;
			if (! wanthash.isNull() && QLibrary::isLibrary(libname)) {
				QFile f(libname);
				if (wanthash.isEmpty()) {
					// Outdated plugin
					if (f.exists()) {
						clearPlugins();
						f.remove();
						rescan=true;
					}
				} else if (f.open(QIODevice::ReadOnly)) {
					QString h = QLatin1String(sha1(f.readAll()).toHex());
					f.close();
					if (h == wanthash) {
						qmPluginFetchMeta.remove(filename);
					}
				}
			}
		}
	}
	QMap<QString, PluginFetchMeta>::const_iterator i;
	for (i = qmPluginFetchMeta.constBegin(); i != qmPluginFetchMeta.constEnd(); ++i) {
		PluginFetchMeta pfm = i.value();
		if (! pfm.hash.isEmpty()) {
			QUrl pluginDownloadUrl;
			if (pfm.path.isEmpty()) {
				pluginDownloadUrl.setPath(QString::fromLatin1("%1").arg(i.key()));
			} else {
				pluginDownloadUrl.setPath(pfm.path);
			}

			WebFetch::fetch(QLatin1String("pa-plugin-dl"), pluginDownloadUrl, this, SLOT(fetchedPAPluginDL(QByteArray,QUrl)));
		}
	}

	if (rescan)
		rescanPlugins();
}

void Plugins::fetchedPAPluginDL(QByteArray data, QUrl url) {
	if (data.isNull())
		return;

	bool rescan = false;

	const QString &urlPath = url.path();
	QString fname = QFileInfo(urlPath).fileName();
	if (qmPluginFetchMeta.contains(fname)) {
		PluginFetchMeta pfm = qmPluginFetchMeta.value(fname);
		if (pfm.hash == QLatin1String(sha1(data).toHex())) {
			bool verified = true;
#ifdef Q_OS_WIN
			verified = false;
			QString tempname;
			std::wstring tempnative;
			{
				QTemporaryFile temp(QDir::tempPath() + QLatin1String("/plugin_XXXXXX.dll"));
				if (temp.open()) {
					tempname = temp.fileName();
					tempnative = QDir::toNativeSeparators(tempname).toStdWString();
					temp.write(data);
					temp.setAutoRemove(false);
				}
			}
			if (! tempname.isNull()) {
				WINTRUST_FILE_INFO file;
				ZeroMemory(&file, sizeof(file));
				file.cbStruct = sizeof(file);
				file.pcwszFilePath = tempnative.c_str();

				WINTRUST_DATA data;
				ZeroMemory(&data, sizeof(data));
				data.cbStruct = sizeof(data);
				data.dwUIChoice = WTD_UI_NONE;
				data.fdwRevocationChecks = WTD_REVOKE_NONE;
				data.dwUnionChoice = WTD_CHOICE_FILE;
				data.pFile = &file;
				data.dwProvFlags = WTD_SAFER_FLAG | WTD_USE_DEFAULT_OSVER_CHECK;
				data.dwUIContext = WTD_UICONTEXT_INSTALL;

				static GUID guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;

				LONG ts = WinVerifyTrust(0, &guid , &data);

				QFile deltemp(tempname);
				deltemp.remove();
				verified = (ts == 0);
			}
#endif
			if (verified) {
				clearPlugins();

				QFile f;
				f.setFileName(qsSystemPlugins + QLatin1String("/") + fname);
				if (f.open(QIODevice::WriteOnly)) {
					f.write(data);
					f.close();
					g.mw->msgBox(tr("Downloaded new or updated plugin to %1.").arg(Qt::escape(f.fileName())));
				} else {
					f.setFileName(qsUserPlugins + QLatin1String("/") + fname);
					if (f.open(QIODevice::WriteOnly)) {
						f.write(data);
						f.close();
						g.mw->msgBox(tr("Downloaded new or updated plugin to %1.").arg(Qt::escape(f.fileName())));
					} else {
						g.mw->msgBox(tr("Failed to install new plugin to %1.").arg(Qt::escape(f.fileName())));
					}
				}

				rescan=true;
			}
		}
	}

	if (rescan)
		rescanPlugins();
}