-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathpatchmanagerobject.cpp
2955 lines (2516 loc) · 104 KB
/
patchmanagerobject.cpp
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
/*
* Copyright (C) 2013 Lucien XU <sfietkonstantin@free.fr>
* Copyright (C) 2016 Andrey Kozhevnikov <coderusinbox@gmail.com>
* Copyright (c) 2021, Patchmanager for SailfishOS contributors:
* - olf "Olf0" </~https://github.com/Olf0>
* - Peter G. "nephros" <sailfish@nephros.org>
* - Vlad G. "b100dian" </~https://github.com/b100dian>
*
* You may use this file under the terms of the 3-clause BSD license,
* as follows:
*
* "Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
*/
#include "patchmanagerobject.h"
#include "patchmanager_adaptor.h"
#include <QLocalSocket>
#include <QLocalServer>
#include <algorithm>
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QEvent>
#include <QtCore/QFile>
#include <QtCore/QJsonDocument>
#include <QtCore/QProcess>
#include <QtCore/QTimer>
#include <QtCore/QUrlQuery>
#include <QtCore/QVector>
#include <QProcessEnvironment>
#include <QtDBus/QDBusArgument>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusMetaType>
#include <QtDBus/QDBusVariant>
#include <QtDBus/QDBusConnectionInterface>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <nemonotifications-qt5/notification.h>
#include "inotifywatcher.h"
#include <unistd.h>
#include <sys/stat.h>
#include <rpm/rpmlib.h>
#include <rpm/header.h>
#include <rpm/rpmdb.h>
#include <rpm/rpmts.h>
#define NAME(x) #x
#define DBUS_GUARD(x) \
if (!calledFromDBus()) {\
qWarning() << Q_FUNC_INFO << "This function should be only called from D-Bus!";\
return x;\
}
// locations
static const QString PATCHES_DIR = QStringLiteral("/usr/share/patchmanager/patches");
static const QString PATCHES_WORK_DIR_PREFIX= QStringLiteral("/tmp/patchmanager3");
static const QString PATCHES_WORK_DIR = QStringLiteral("%1/%2").arg(PATCHES_WORK_DIR_PREFIX, "work");
static const QString PATCHES_ADDITIONAL_DIR = QStringLiteral("%1/%2").arg(PATCHES_WORK_DIR_PREFIX, "patches");
static const QString PATCH_METADATA_FILE = QStringLiteral("patch.json");
static const QString MANGLE_CONFIG_FILE = QStringLiteral("/etc/patchmanager/manglelist.conf");
static const QString AUSMT_BACKUP_DIR = QStringLiteral("/var/lib/patchmanager/ausmt/patches");
static const QString AUSMT_INSTALLED_LIST_FILE = QStringLiteral("/var/lib/patchmanager/ausmt/packages");
static const QString s_newConfigLocation = QStringLiteral("/etc/patchmanager2.conf");
static const QString s_oldConfigLocation = QStringLiteral("/home/nemo/.config/patchmanager2.conf");
static const QString s_patchmanagerSocket = QStringLiteral("/tmp/patchmanager-socket");
static const QString s_patchmanagerCacheRoot = QStringLiteral("/tmp/patchmanager");
static const QString s_sessionBusConnection = QStringLiteral("pm3connection");
// helpers
static const QString PM_APPLY = QStringLiteral("/usr/libexec/pm_apply");
static const QString PM_UNAPPLY = QStringLiteral("/usr/libexec/pm_unapply");
// external binaries
static const QString BIN_UNZIP = QStringLiteral("/usr/bin/unzip");
static const QString BIN_TAR = QStringLiteral("/bin/tar");
static const QString BIN_PKCON = QStringLiteral("/usr/bin/pkcon");
static const QString BIN_SYSTEMCTL_U = QStringLiteral("/usr/bin/systemctl-user");
static const QString BIN_RPM = QStringLiteral("/bin/rpm");
// map key constants: states
static const QString NAME_KEY = QStringLiteral("name");
static const QString DESCRIPTION_KEY = QStringLiteral("description");
static const QString CATEGORY_KEY = QStringLiteral("category");
static const QString INFOS_KEY = QStringLiteral("infos");
static const QString PATCH_KEY = QStringLiteral("patch");
static const QString RPM_KEY = QStringLiteral("rpm");
static const QString AVAILABLE_KEY = QStringLiteral("available");
static const QString SECTION_KEY = QStringLiteral("section");
static const QString PATCHED_KEY = QStringLiteral("patched");
static const QString VERSION_KEY = QStringLiteral("version");
static const QString COMPATIBLE_KEY = QStringLiteral("compatible");
static const QString ISCOMPATIBLE_KEY = QStringLiteral("isCompatible");
static const QString CONFLICTS_KEY = QStringLiteral("conflicts");
// map key constants: patch categories
static const QString BROWSER_CODE = QStringLiteral("browser");
static const QString CAMERA_CODE = QStringLiteral("camera");
static const QString CALENDAR_CODE = QStringLiteral("calendar");
static const QString CLOCK_CODE = QStringLiteral("clock");
static const QString CONTACTS_CODE = QStringLiteral("contacts");
static const QString EMAIL_CODE = QStringLiteral("email");
static const QString GALLERY_CODE = QStringLiteral("gallery");
static const QString HOMESCREEN_CODE = QStringLiteral("homescreen");
static const QString MEDIA_CODE = QStringLiteral("media");
static const QString MESSAGES_CODE = QStringLiteral("messages");
static const QString PHONE_CODE = QStringLiteral("phone");
static const QString SILICA_CODE = QStringLiteral("silica");
static const QString SETTINGS_CODE = QStringLiteral("settings");
static const QString KEYBOARD_CODE = QStringLiteral("keyboard");
/*!
\class PatchManagerObject
\inmodule PatchManagerDaemon
\brief The Patchmanager daemon.
A D-Bus activated background service which manages patch un/installation,
listing, de/actvation, and communication with the preload library.
Patchmanager is usually launched by its D-Bus service.
The binary can also serve as a simple command-line client to a running
daemon. See the output of \c{patchmanager --help} for more information.
*/
/*!
\enum PatchManagerObject::NotifyAction
\relates PatchManagerObject::notify()
This enum specifies the type of notification to emit through \c
PatchManagerObject::notify()
\value NotifyActionSuccessApply
applying was successful
\value NotifyActionSuccessUnapply
unapplying was successful
\value NotifyActionFailedApply
applying was not successful
\value NotifyActionFailedUnapply
unapplying was not successful
\value NotifyActionUpdateAvailable
one of the Patches has an update
*/
QString getLang()
{
QString lang = QStringLiteral("en_US.utf8");
QStringList locales = {
QStringLiteral("/etc/locale.conf"),
QStringLiteral("/var/lib/environment/nemo/locale.conf"),
};
for (const QString &localePath : locales) {
QFile localeConfig(localePath);
if (!localeConfig.exists() || !localeConfig.open(QFile::ReadOnly)) {
continue;
}
while (!localeConfig.atEnd()) {
QString line = localeConfig.readLine().trimmed();
if (line.startsWith(QStringLiteral("LANG="))) {
lang = line.mid(5);
break;
}
}
}
qDebug() << Q_FUNC_INFO << lang;
return lang;
}
bool PatchManagerObject::makePatch(const QDir &root, const QString &patchPath, QVariantMap &patch, bool available)
{
QDir patchDir(root);
if (!patchDir.cd(patchPath)) {
return false;
}
QFile file(patchDir.absoluteFilePath(PATCH_METADATA_FILE));
if (!file.open(QIODevice::ReadOnly)) {
return false;
}
QJsonParseError error;
QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error);
file.close();
if (error.error != QJsonParseError::NoError) {
qWarning() << Q_FUNC_INFO << error.errorString();
return false;
}
QVariantMap json = document.toVariant().toMap();
if (!json.contains(NAME_KEY) || !json.contains(DESCRIPTION_KEY) || !json.contains(CATEGORY_KEY)) {
return false;
}
json[PATCH_KEY] = patchPath;
json[RPM_KEY] = QString();
json[AVAILABLE_KEY] = available;
// json[CATEGORY_KEY] = json[CATEGORY_KEY];
// json[SECTION_KEY] = QStringLiteral("Other");
json[PATCHED_KEY] = m_appliedPatches.contains(patchPath);
if (!json.contains(VERSION_KEY)) {
json[VERSION_KEY] = QStringLiteral("0.0.0");
}
if (!json.contains(COMPATIBLE_KEY)) {
json[COMPATIBLE_KEY] = QStringList();
json[ISCOMPATIBLE_KEY] = true;
} else {
json[ISCOMPATIBLE_KEY] = json[COMPATIBLE_KEY].toStringList().contains(m_osRelease);
}
json[CONFLICTS_KEY] = QStringList();
patch = json;
return true;
}
/*!
Sends a notification to the user. \a patch is the Patch name, \a action one of:
\sa PatchManagerObject::NotifyAction
*/
void PatchManagerObject::notify(const QString &patch, NotifyAction action)
{
qDebug() << Q_FUNC_INFO << patch << action;
Notification notification;
QString summary;
QString body;
QVariantList remoteActions;
switch (action) {
case NotifyActionSuccessApply:
summary = qApp->translate("", "Patch activated");
body = qApp->translate("", "Patch %1 activated").arg(patch);
if (getToggleServices()) {
body.append( ", " );
body.append( qApp->translate("", "some service(s) should be restarted.") );
notification.setHintValue("icon", "icon-lock-warning");
} else {
body.append( "." );
}
break;
case NotifyActionSuccessUnapply:
summary = qApp->translate("", "Patch deactivated");
body = qApp->translate("", "Patch %1 is now inactive.").arg(patch);
if (getToggleServices()) {
body.append( ", " );
body.append( qApp->translate("", "some service(s) should be restarted.") );
notification.setHintValue("icon", "icon-lock-warning");
} else {
body.append( "." );
}
break;
case NotifyActionFailedApply:
summary = qApp->translate("", "Failed to activate Patch");
body = qApp->translate("", "Activating Patch %1 failed!").arg(patch);
break;
case NotifyActionFailedUnapply:
summary = qApp->translate("", "Failed to deactivate Patch");
body = qApp->translate("", "Deactivating Patch %1 failed!").arg(patch);
break;
case NotifyActionUpdateAvailable:
summary = qApp->translate("", "Update available");
body = qApp->translate("", "An update for Patch %1 is available.").arg(patch);
remoteActions << Notification::remoteAction(
QStringLiteral("default"),
QStringLiteral("patchmanager"),
QStringLiteral("com.jolla.settings"),
QStringLiteral("/com/jolla/settings/ui"),
QStringLiteral("com.jolla.settings.ui"),
QStringLiteral("showPage"),
{ QStringLiteral("system_settings/look_and_feel/patchmanager") }
);
break;
default:
qWarning() << Q_FUNC_INFO << "Unknown, hence unhandled action" << action;
}
qDebug() << Q_FUNC_INFO << summary << body;
notification.setAppName(qApp->translate("", "Patchmanager"));
notification.setHintValue("app_icon", "icon-m-patchmanager2");
notification.setTimestamp(QDateTime::currentDateTime());
if (!remoteActions.isEmpty()) {
qDebug() << Q_FUNC_INFO << remoteActions;
notification.setRemoteActions(remoteActions);
}
notification.setSummary(summary);
notification.setBody(body);
notification.setPreviewSummary(summary);
notification.setPreviewBody(body);
notification.publish();
qDebug() << Q_FUNC_INFO << notification.replacesId();
}
/*!
Returns the list of applied \a patches via \c getSettings().
\sa putSettings(), setAppliedPatches()
*/
QSet<QString> PatchManagerObject::getAppliedPatches() const
{
return getSettings(QStringLiteral("applied"), QStringList()).toStringList().toSet();
}
/*!
Stores a list of applied \a patches via \c putSettings().
\sa getSettings(), getAppliedPatches()
*/
void PatchManagerObject::setAppliedPatches(const QSet<QString> &patches)
{
putSettings(QStringLiteral("applied"), QStringList(patches.toList()));
}
/*!
Returns the list of successfully auto-applied \a patches via \c getSettings().
\sa putSettings(), setWorkingPatches()
*/
QSet<QString> PatchManagerObject::getWorkingPatches() const
{
return getSettings(QStringLiteral("workingPatches"), QStringList()).toStringList().toSet();
}
/*!
Stores a list of successfully auto-applied \a patches via \c putSettings().
\sa getSettings(), getWorkingPatches()
*/
void PatchManagerObject::setWorkingPatches(const QSet<QString> &patches)
{
putSettings(QStringLiteral("workingPatches"), QStringList(patches.toList()));
}
/*!
Stores a list of currently applied \a patches as "last-known-good" / working via \c setWorkingPatches().
\sa getSettings(), getWorkingPatches()
*/
void PatchManagerObject::setWorking()
{
setWorkingPatches(getAppliedPatches());
}
QStringList PatchManagerObject::getMangleCandidates()
{
if (m_mangleCandidates.empty()) {
qDebug() << Q_FUNC_INFO;
auto mangleCandidates = QSettings(MANGLE_CONFIG_FILE, QSettings::IniFormat).value("MANGLE_CANDIDATES", "").toString();
m_mangleCandidates = mangleCandidates.split(' ', QString::SplitBehavior::SkipEmptyParts);
qDebug() << "Loaded mangle candidates:" << m_mangleCandidates;
}
return m_mangleCandidates;
}
/*!
Reads operating system (\c{VERSION_ID}) version from \c /etc/os-release and sets \c m_osRelease to its value.
Calls lateInitialize() afterwards.
\sa lateInitialize()
*/
void PatchManagerObject::getVersion()
{
qDebug() << Q_FUNC_INFO;
m_osRelease = QSettings("/etc/os-release", QSettings::IniFormat).value("VERSION_ID").toString();
qDebug() << "Installed SailfishOS release is" << m_osRelease;
lateInitialize();
}
void PatchManagerObject::lateInitialize()
{
qDebug() << Q_FUNC_INFO;
QFile file (AUSMT_INSTALLED_LIST_FILE);
if (file.exists()) {
qWarning() << Q_FUNC_INFO << "Found extant AUSMT package list, importing list as enabled Patches.";
if (file.open(QFile::ReadOnly)) {
while (!file.atEnd()) {
const QString line = QString::fromLatin1(file.readLine());
const QStringList splitted = line.split(QChar(' '));
if (splitted.count() == 2) {
m_appliedPatches.insert(splitted.first());
qDebug() << Q_FUNC_INFO << splitted.first();
}
}
file.close();
}
qWarning() << Q_FUNC_INFO << "Removing AUSMT package list." <<
file.remove();
setAppliedPatches(m_appliedPatches);
}
bool needClear = false;
QDir ausmtBackup(AUSMT_BACKUP_DIR);
QDir oldpm3cache(QStringLiteral("/var/lib/patchmanager3/patches"));
if (ausmtBackup.exists()) {
qWarning() << Q_FUNC_INFO << "Found AUSMT backup directory, hence cleansing fakeroot.";
ausmtBackup.removeRecursively();
needClear = true;
}
if (oldpm3cache.exists()) {
qWarning() << Q_FUNC_INFO << "Found old backup directory, hence cleansing fakeroot.";
oldpm3cache.removeRecursively();
needClear = true;
}
if (needClear) {
clearFakeroot();
}
refreshPatchList();
QDir cache(PATCHES_ADDITIONAL_DIR);
if ((cache.exists() && cache.entryList(QDir::NoDotAndDotDot | QDir::Dirs).count() > 0)
|| getSettings(QStringLiteral("applyOnBoot"), false).toBool()) {
prepareCacheRoot();
startLocalServer();
}
INotifyWatcher *mainWatcher = new INotifyWatcher(this);
mainWatcher->addPaths({ PATCHES_DIR });
connect(mainWatcher, &INotifyWatcher::contentChanged, [this](const QString &path, bool created) {
qDebug() << Q_FUNC_INFO << "Content in" << path << "changed; is newly created (bool):" << created;
refreshPatchList();
if (m_adaptor) {
emit m_adaptor->patchAltered(path, created);
}
});
// INotifyWatcher *additionalWatcher = new INotifyWatcher(this);
// additionalWatcher->addPaths({ PATCHES_ADDITIONAL_DIR });
// connect(additionalWatcher, &INotifyWatcher::contentChanged, [this](const QString &path, bool created) {
// qDebug() << Q_FUNC_INFO << "Content in" << path << "changed; is newly created (bool):" << created;
// refreshPatchList();
// });
registerDBus();
checkForUpdates();
}
QList<QVariantMap> PatchManagerObject::listPatchesFromDir(const QString &dir, QSet<QString> &existingPatches, bool existing)
{
QList<QVariantMap> patches;
QDir root (dir);
for (const QString &patchPath : root.entryList(QDir::AllDirs | QDir::NoDotAndDotDot)) {
if (existingPatches.contains(patchPath)) {
continue;
}
QVariantMap patch;
bool ok = makePatch(root, patchPath, patch, existing);
if (!ok) {
continue;
}
patches.append(patch);
existingPatches.insert(patchPath);
}
return patches;
}
PatchManagerObject::PatchManagerObject(QObject *parent)
: QObject(parent)
, m_sbus(s_sessionBusConnection)
{
}
PatchManagerObject::~PatchManagerObject()
{
if (m_dbusRegistered) {
QDBusConnection connection = QDBusConnection::systemBus();
connection.unregisterService(DBUS_SERVICE_NAME);
connection.unregisterObject(DBUS_PATH_NAME);
}
}
void PatchManagerObject::registerDBus()
{
qDebug() << Q_FUNC_INFO;
QMetaObject::invokeMethod(this, NAME(doRegisterDBus), Qt::QueuedConnection);
}
void PatchManagerObject::waitForLipstick()
{
qDebug() << Q_FUNC_INFO;
}
void PatchManagerObject::startLocalServer()
{
qDebug() << Q_FUNC_INFO;
QMetaObject::invokeMethod(this, NAME(doStartLocalServer), Qt::QueuedConnection);
}
void PatchManagerObject::doRegisterDBus()
{
qDebug() << Q_FUNC_INFO;
if (m_dbusRegistered) {
return;
}
QDBusConnection connection = QDBusConnection::systemBus();
if (connection.interface()->isServiceRegistered(DBUS_SERVICE_NAME)) {
qWarning() << Q_FUNC_INFO << "D-Bus service was already registered" << DBUS_SERVICE_NAME;
return;
}
if (!connection.registerObject(DBUS_PATH_NAME, this)) {
qCritical() << Q_FUNC_INFO << "Cannot register D-Bus object" << DBUS_PATH_NAME;
QCoreApplication::quit();
return;
}
qInfo() << "Patchmanager: Successfully registered D-Bus object" << DBUS_PATH_NAME;
if (!connection.registerService(DBUS_SERVICE_NAME)) {
qCritical() << Q_FUNC_INFO << "Cannot register D-Bus service" << DBUS_SERVICE_NAME;
QCoreApplication::quit();
return;
}
m_adaptor = new PatchManagerAdaptor(this);
if (qEnvironmentVariableIsSet("PM_DEBUG_EVENTFILTER")) {
m_adaptor->installEventFilter(this);
}
qInfo() << "Patchmanager: Successfully registered D-Bus service" << DBUS_SERVICE_NAME;
m_dbusRegistered = true;
}
/*!
\fn void PatchManagerObject::prepareCacheRoot()
Despite its name, it does not actually prepare the cache root!
Instead, this is the main "auto-apply" function.
\list
\li First, apply all enabled Patches which are listend in the \l{order}{inifile} settings key.
\li Second, apply all enabled Patches which remain (if any).
\li If applying any Patch fails, the local \c success variable will be set to \c false, but the applying run will continue.
\li At the end of the process, if \c success is \c true, calls setWorkingPatches()
\li At the end of the process, if \c success is \c false, calls refreshPatchList()
\endlist
()
Emits signals \c autoApplyingStarted(), \c autoApplyingPatch(), \c autoApplyingFailed(), autoApplyingFinished(), depending on state.
\sa PatchManagerObject::doPrepareCache(), {Patchmanager Configuration Files}, inifile, refreshPatchList(), setWorkingPatches()
*/
void PatchManagerObject::doPrepareCacheRoot()
{
qDebug() << Q_FUNC_INFO;
// TODO: think about security issues here
QStringList order = getSettings(QStringLiteral("order"), QStringList()).toStringList();
bool success = true;
if (m_adaptor) {
emit m_adaptor->autoApplyingStarted(m_appliedPatches.count());
}
for (const QString &patchName : order) {
if (m_appliedPatches.contains(patchName)) {
if (m_adaptor) {
emit m_adaptor->autoApplyingPatch(getPatchName(patchName));
}
if (!doPatch(patchName, true)) {
if (m_adaptor) {
emit m_adaptor->autoApplyingFailed(getPatchName(patchName));
}
m_appliedPatches.remove(patchName);
success = false;
}
}
}
for (const QString &patchName : QSet<QString>(m_appliedPatches)) {
if (!order.contains(patchName)) {
if (m_adaptor) {
emit m_adaptor->autoApplyingPatch(getPatchName(patchName));
}
if (!doPatch(patchName, true)) {
if (m_adaptor) {
emit m_adaptor->autoApplyingFailed(getPatchName(patchName));
}
m_appliedPatches.remove(patchName);
success = false;
}
}
}
if (m_adaptor) {
emit m_adaptor->autoApplyingFinished(success);
}
if (success) {
setWorkingPatches(m_appliedPatches);
}
if (!success) {
setAppliedPatches(m_appliedPatches);
refreshPatchList();
}
}
/*!
\fn void PatchManagerObject::doPrepareCache(const QString &patchName, bool apply = true)
Creates the cache directory where patched files will be stored
and read from when passed to the preload library.
\c It will create the cache for the Patch \a patchName, and optionally \a apply it.
\sa PatchManagerObject::prepareCacheRoot()
*/
void PatchManagerObject::doPrepareCache(const QString &patchName, bool apply)
{
qDebug() << Q_FUNC_INFO << patchName << apply;
if (!m_patchFiles.contains(patchName)) {
qWarning() << Q_FUNC_INFO << "Patch is not installed" << patchName;
return;
}
qDebug() << Q_FUNC_INFO << "Patch changes the following files:\n\t" << m_patchFiles.value(patchName).join("\n\t");
for (const QString &fileName : m_patchFiles.value(patchName)) {
qDebug() << Q_FUNC_INFO << "Processing file" << fileName;
QFileInfo fi(fileName);
QDir fakeDir(QStringLiteral("%1%2").arg(s_patchmanagerCacheRoot, fi.absoluteDir().absolutePath()));
if (apply && !fakeDir.exists()) {
qDebug() << Q_FUNC_INFO << "Creating faking directory" << fakeDir.absolutePath();
QDir::root().mkpath(fakeDir.absolutePath());
}
if (apply && !fi.absoluteDir().exists()) {
if (tryToLinkFakeParent(fi.absoluteDir().absolutePath())) {
continue;
}
}
if (apply && checkIsFakeLinked(fi.absoluteDir().absolutePath())) {
continue;
}
const QString fakeFileName = QStringLiteral("%1/%2").arg(fakeDir.absolutePath(), fi.fileName());
if (apply && !fi.exists()) {
bool link_ret = QFile::link(fakeFileName, fi.absoluteFilePath());
qDebug() << Q_FUNC_INFO << "Symlinking" << fileName << "to" << fakeFileName << link_ret;
continue;
}
if (!apply && fi.isSymLink()) {
bool remove_ret = QFile::remove(fi.absoluteFilePath());
qDebug() << Q_FUNC_INFO << "Removing symlink" << fileName << "to" << fakeFileName << remove_ret;
}
if (QFileInfo::exists(fakeFileName)) {
if (apply) {
m_originalWatcher->addPath(fileName);
continue;
}
if (m_fileToPatch.value(fileName).length() > 1) { // TODO: should check only applied patches?
continue;
}
m_originalWatcher->removePath(fileName);
bool remove_ret = QFile::remove(fakeFileName);
qDebug() << Q_FUNC_INFO << "Removing" << fakeFileName << remove_ret;
} else {
if (!apply) {
tryToUnlinkFakeParent(fi.absoluteDir().absolutePath());
continue;
}
struct stat fileStat;
if (stat(fileName.toLatin1().constData(), &fileStat) < 0) {
qWarning() << Q_FUNC_INFO << "Failed to stat" << fileName;
continue;
}
bool copy_ret = QFile::copy(fileName, fakeFileName);
qDebug() << Q_FUNC_INFO << "Copying" << fileName << "to" << fakeFileName << copy_ret;
m_originalWatcher->addPath(fileName);
chmod(fakeFileName.toLatin1().constData(), fileStat.st_mode);
int chown_ret = chown(fakeFileName.toLatin1().constData(), fileStat.st_uid, fileStat.st_gid);
if (chown_ret) {
perror(fakeFileName.toLatin1().constData());
}
}
}
}
/*!
\fn void PatchManagerObject::doStartLocalServer()
\fn void PatchManagerObject::startLocalServer()
Starts the internal server thread if not already started.
Emits \c loadedChanged if successful.
*/
void PatchManagerObject::doStartLocalServer()
{
qDebug() << Q_FUNC_INFO;
if (!getLoaded()) {
m_serverThread->start();
if (m_adaptor) {
emit m_adaptor->loadedChanged(true);
}
}
}
/*!
\fn void PatchManagerObject::initialize()
\fn void PatchManagerObject::lateInitialize()
Initialise the engines.
The initialisation sequence comprises:
- setting up the patch translator
- checking configuration constants and environment
- setting up D-Bus connections to Lipstick and the Store client
*/
void PatchManagerObject::initialize()
{
qInfo() << "Patchmanager: Initialized version " << qApp->applicationVersion();
QTranslator *translator = new QTranslator(this);
bool success = translator->load(QLocale(getLang()),
QStringLiteral("settings-patchmanager"),
QStringLiteral("-"),
QStringLiteral("/usr/share/translations/"),
QStringLiteral(".qm"));
qDebug() << Q_FUNC_INFO << "Translator loaded" << success;
success = qApp->installTranslator(translator);
qDebug() << Q_FUNC_INFO << "Translator installed" << success;
m_nam = new QNetworkAccessManager(this);
m_settings = new QSettings(s_newConfigLocation, QSettings::IniFormat, this);
qDebug() << Q_FUNC_INFO << "Environment:";
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
for (const QString &key : env.keys()) {
qDebug() << Q_FUNC_INFO << key << "=" << env.value(key);
}
QFile preload(QStringLiteral("/etc/ld.so.preload"));
if (preload.exists()) {
qDebug() << Q_FUNC_INFO << "ld.so.preload";
if (!preload.open(QFile::ReadOnly)) {
qCritical() << Q_FUNC_INFO << "Failed to access ld.so.preload!";
}
qDebug().noquote() << Q_FUNC_INFO << preload.readAll();
} else {
qWarning() << Q_FUNC_INFO << "Failed to find ld.so.preload!";
}
qDebug() << Q_FUNC_INFO << PM_APPLY;
QFileInfo pa(PM_APPLY);
if (pa.exists()) {
qDebug() << Q_FUNC_INFO << pa.permissions();
} else {
qWarning() << Q_FUNC_INFO << "Failed to access pm_apply!";
}
qDebug() << Q_FUNC_INFO << PM_UNAPPLY;
QFileInfo pu(PM_UNAPPLY);
if (pu.exists()) {
qDebug() << Q_FUNC_INFO << pu.permissions();
} else {
qWarning() << Q_FUNC_INFO << "Failed to access pm_unapply!";
}
if (!QFileInfo::exists(s_newConfigLocation) && QFileInfo::exists(s_oldConfigLocation)) {
QFile::copy(s_oldConfigLocation, s_newConfigLocation);
}
if (Q_UNLIKELY(qEnvironmentVariableIsSet("PM_DEBUG_EVENTFILTER"))) {
installEventFilter(this);
}
if (Q_UNLIKELY(qEnvironmentVariableIsEmpty("DBUS_SESSION_BUS_ADDRESS"))) {
qCritical() << Q_FUNC_INFO << "D-Bus session address is not set! Please check the environment configuration.";
qDebug() << Q_FUNC_INFO << "Injecting DBUS_SESSION_BUS_ADDRESS...";
qputenv("DBUS_SESSION_BUS_ADDRESS", QByteArrayLiteral("unix:path=/run/user/100000/dbus/user_bus_socket"));
}
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &PatchManagerObject::onTimerAction);
m_timer->setSingleShot(false);
m_timer->setTimerType(Qt::VeryCoarseTimer);
m_timer->setInterval(60 * 60 * 1000); // 60 min
m_timer->start();
m_sessionBusConnector = new QTimer(this);
connect(m_sessionBusConnector, &QTimer::timeout, this, [this]() {
QDBusConnection test = QDBusConnection::connectToBus(QDBusConnection::SessionBus, s_sessionBusConnection);
if (!test.isConnected()) {
QDBusConnection::disconnectFromBus(s_sessionBusConnection);
} else {
m_sbus = test;
m_sessionBusConnector->stop();
qDebug() << Q_FUNC_INFO << "Successfully connected to D-Bus session bus.";
m_sbus.connect(QString(),
QStringLiteral("/org/freedesktop/systemd1/unit/lipstick_2eservice"),
QStringLiteral("org.freedesktop.DBus.Properties"),
QStringLiteral("PropertiesChanged"), this, SLOT(onLipstickChanged(QString,QVariantMap,QStringList)));
m_sbus.connect(QString(),
QStringLiteral("/StoreClient"),
QStringLiteral("com.jolla.jollastore"),
QStringLiteral("osUpdateProgressChanged"), this, SLOT(onOsUpdateProgress(int)));
}
});
m_sessionBusConnector->setSingleShot(false);
m_sessionBusConnector->setTimerType(Qt::VeryCoarseTimer);
m_sessionBusConnector->setInterval(1000); // 1 second
m_sessionBusConnector->start();
m_originalWatcher = new QFileSystemWatcher(this);
connect(m_originalWatcher, &QFileSystemWatcher::fileChanged, this, &PatchManagerObject::onOriginalFileChanged);
m_localServer = new QLocalServer(nullptr); // controlled by a separate thread
m_localServer->setSocketOptions(QLocalServer::WorldAccessOption);
m_localServer->setMaxPendingConnections(2147483647);
m_serverThread = new QThread(this);
connect(m_serverThread, &QThread::finished, this, [this](){
m_localServer->close();
});
connect(m_localServer, &QLocalServer::newConnection, this, &PatchManagerObject::startReadingLocalServer, Qt::DirectConnection);
connect(m_serverThread, &QThread::started, this, [this](){
bool listening = m_localServer->listen(s_patchmanagerSocket);
if (!listening // not listening
&& m_localServer->serverError() == QAbstractSocket::AddressInUseError // because of AddressInUseError
&& QFileInfo::exists(s_patchmanagerSocket) // socket file already exists
&& QFile::remove(s_patchmanagerSocket)) { // and successfully removed it
qWarning() << Q_FUNC_INFO << "Successfully removed old, stale socket.";
listening = m_localServer->listen(s_patchmanagerSocket); // try to start listening again
}
qDebug() << Q_FUNC_INFO << "Local server listening (bool):" << listening;
if (!listening) {
qCritical() << Q_FUNC_INFO << "Local server error:" << m_localServer->serverError() << m_localServer->errorString();
}
}, Qt::DirectConnection);
m_localServer->moveToThread(m_serverThread);
m_journal = new Journal(this);
connect(m_journal, &Journal::matchFound, this, &PatchManagerObject::onFailureOccured);
m_journal->init();
static bool rpmConfigRead = false;
if (!rpmConfigRead) {
rpmReadConfigFiles(NULL, NULL);
rpmConfigRead = true;
}
getVersion();
}
/*! Returns a pretty name (the \c display_name field) from the metadata of \a patch. */
QString PatchManagerObject::getPatchName(const QString patch) const
{
if (!m_metadata.contains(patch)) {
return patch;
}
const QVariantMap patchData = m_metadata[patch];
return (patchData.contains("display_name") ? patchData["display_name"] : patchData[NAME_KEY]).toString();
}
/*!
\fn void PatchManagerObject::restartLipstick()
\fn void PatchManagerObject::doRestartLipstick()
Invokes PatchManagerObject::doRestartLipstick() to restart Lipstick
\sa PatchManagerObject::restartService(const QString &serviceName)
*/
void PatchManagerObject::restartLipstick()
{
qDebug() << Q_FUNC_INFO;
QMetaObject::invokeMethod(this, NAME(doRestartLipstick), Qt::QueuedConnection);
}
void PatchManagerObject::doRestartLipstick()
{
qDebug() << Q_FUNC_INFO;
restartService(QStringLiteral("lipstick.service"));
}
/*!
Invokes ManagerObject::doRestartKeyboard() to restart Maliit
\sa PatchManagerObject::doRestartKeyboard()
*/
void PatchManagerObject::restartKeyboard()
{
qDebug() << Q_FUNC_INFO;
QMetaObject::invokeMethod(this, NAME(doRestartKeyboard), Qt::QueuedConnection);
}
void PatchManagerObject::doRestartKeyboard()
{
qDebug() << Q_FUNC_INFO;
restartService(QStringLiteral("maliit-server.service"));
}
/*!
Stops, restarts, or kills running processes belonging to a category which
has been marked as to-be-restarted.
For regular processes, \c killall will be performed on them.
Systemd services will be restarted via D-Bus call, or if that fails, via \c systemctl-user.
*/
void PatchManagerObject::restartService(const QString &serviceName)
{
qDebug() << Q_FUNC_INFO << serviceName;
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.systemd1"),
QStringLiteral("/org/freedesktop/systemd1"),
QStringLiteral("org.freedesktop.systemd1.Manager"),
QStringLiteral("RestartUnit"));
m.setArguments({ serviceName, QStringLiteral("replace") });
if (!m_sbus.send(m)) {
qWarning() << Q_FUNC_INFO << "Error sending message";
qDebug() << Q_FUNC_INFO << "Invoking systemctl:" <<
QProcess::execute(BIN_SYSTEMCTL_U, { QStringLiteral("--no-block"), QStringLiteral("restart"), serviceName });
}
}
void PatchManagerObject::resetSystem()
{
qDebug() << Q_FUNC_INFO;
unapplyAllPatches();
QStringList patchedFiles;
QDir patchesDir(PATCHES_DIR);
for (const QString &patchFolder : patchesDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
qDebug() << Q_FUNC_INFO << "Processing Patch" << patchFolder;
QFile patchFile(QStringLiteral("%1/%2/unified_diff.patch").arg(PATCHES_DIR, patchFolder));