summaryrefslogtreecommitdiff
path: root/src/manager-lib/nativeruntime.cpp
blob: 126d597991e7706fbb5d9b50ed0b56bf418d6732 (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
/****************************************************************************
**
** Copyright (C) 2016 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Pelagicore Application Manager.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/

#include <QCoreApplication>
#include <QProcess>
#include <QDBusServer>
#include <QDBusConnection>
#include <QDBusError>
#include <QTimer>
#include <QUuid>

#include "global.h"
#include "application.h"
#include "applicationmanager.h"
#include "nativeruntime.h"
#include "nativeruntime_p.h"
#include "runtimefactory.h"
#include "qtyaml.h"
#include "applicationinterface.h"
#include "applicationipcmanager.h"
#include "applicationipcinterface.h"
#include "utilities.h"
#include "notificationmanager.h"

QT_BEGIN_NAMESPACE_AM

// You can enable this define to get all P2P-bus objects onto the session bus
// within io.qt.ApplicationManager, /Application<pid>/...

// #define EXPORT_P2PBUS_OBJECTS_TO_SESSION_BUS 1

#if defined(AM_MULTI_PROCESS)
QT_END_NAMESPACE_AM
#  include <dbus/dbus.h>
#  include <sys/socket.h>
QT_BEGIN_NAMESPACE_AM

static qint64 getDBusPeerPid(const QDBusConnection &conn)
{
    int socketFd = -1;
    if (dbus_connection_get_socket(static_cast<DBusConnection *>(conn.internalPointer()), &socketFd)) {
        struct ucred ucred;
        socklen_t ucredSize = sizeof(struct ucred);
        if (getsockopt(socketFd, SOL_SOCKET, SO_PEERCRED, &ucred, &ucredSize) == 0)
            return ucred.pid;
    }
    return 0;
}

#else

static qint64 getDBusPeerPid(const QDBusConnection &conn)
{
    Q_UNUSED(conn)
    return 0;
}

#endif

NativeRuntime::NativeRuntime(AbstractContainer *container, const Application *app, NativeRuntimeManager *manager)
    : AbstractRuntime(container, app, manager)
    , m_isQuickLauncher(app == nullptr)
    , m_needsLauncher(manager->identifier() != qL1S("native"))
{ }

NativeRuntime::~NativeRuntime()
{
    delete m_process;
}

bool NativeRuntime::isQuickLauncher() const
{
    return m_isQuickLauncher;
}

bool NativeRuntime::attachApplicationToQuickLauncher(const Application *app)
{
    if (!app || !isQuickLauncher() || !m_needsLauncher)
        return false;

    m_isQuickLauncher = false;
    m_app = app;
    m_app->setCurrentRuntime(this);

    setState(Startup);

    bool ret;
    if (!m_dbusConnection) {
        // we have no D-Bus connection yet, so hope for the best
        ret = true;
    } else {
        onLauncherFinishedInitialization();
        ret = m_launched;
    }

    if (ret)
        setState(Active);

    return ret;
}

bool NativeRuntime::initialize()
{
    if (m_needsLauncher) {
        QFileInfo fi(qSL("%1/appman-launcher-%2").arg(QCoreApplication::applicationDirPath(), manager()->identifier()));
        if (!fi.exists() || !fi.isExecutable())
            return false;
        m_container->setProgram(fi.absoluteFilePath());
        m_container->setBaseDirectory(fi.absolutePath());
    } else {
        if (!m_app)
            return false;

        m_container->setProgram(m_app->absoluteCodeFilePath());
        m_container->setBaseDirectory(m_app->baseDir().absolutePath());
    }
    return true;
}

void NativeRuntime::shutdown(int exitCode, QProcess::ExitStatus status)
{
    qCDebug(LogSystem) << "NativeRuntime (id:" << (m_app ? m_app->id() : qSL("(none)"))
                       << "pid:" << m_process->processId() << ") exited with code:" << exitCode
                       << "status:" << status;

    m_launched = m_launchWhenReady = m_dbusConnection = false;

    // unregister all extension interfaces
    foreach (ApplicationIPCInterface *iface, ApplicationIPCManager::instance()->interfaces()) {
        iface->dbusUnregister(QDBusConnection(m_dbusConnectionName));
    }

    if (m_app)
        m_app->setCurrentRuntime(0);

    emit finished(exitCode, status);
    setState(Inactive);

    deleteLater();
}

bool NativeRuntime::start()
{
    switch (state()) {
    case Startup:
    case Active:
        return true;
    case Shutdown:
        return false;
    case Inactive:
        break;
    }

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert(qSL("QT_QPA_PLATFORM"), qSL("wayland"));
    env.remove(qSL("QT_IM_MODULE"));     // Applications should use wayland text input
    //env.insert(qSL("QT_WAYLAND_DISABLE_WINDOWDECORATION"), "1");
    env.insert(qSL("AM_SECURITY_TOKEN"), qL1S(securityToken().toHex()));
    env.insert(qSL("AM_DBUS_PEER_ADDRESS"), static_cast<NativeRuntimeManager *>(manager())->applicationInterfaceServer()->address());
    env.insert(qSL("AM_DBUS_NOTIFICATION_BUS_ADDRESS"), NotificationManager::instance()->property("_am_dbus_name").toString());
    env.insert(qSL("AM_RUNTIME_CONFIGURATION"), QString::fromUtf8(QtYaml::yamlFromVariantDocuments({ configuration() })));
    env.insert(qSL("AM_RUNTIME_SYSTEM_PROPERTIES"), QString::fromUtf8(QtYaml::yamlFromVariantDocuments({ systemProperties() })));
    env.insert(qSL("AM_BASE_DIR"), QDir::currentPath());
    if (!dltLoggingEnabled)
        env.insert(qSL("AM_NO_DLT_LOGGING"), qSL("1"));

    for (QMapIterator<QString, QVariant> it(configuration().value(qSL("environmentVariables")).toMap()); it.hasNext(); ) {
        it.next();
        QString name = it.key();
        if (!name.isEmpty()) {
            QString value = it.value().toString();
            if (value.isNull())
                env.remove(it.key());
            else
                env.insert(name, value);
        }
    }

    if (m_app && !m_app->environmentVariables().isEmpty()) {
        if (ApplicationManager::instance()->securityChecksEnabled()) {
            qCWarning(LogSystem) << "Due to enabled security checks, the environmentVariables for"
                                 << m_app->id() << "(given in info.yaml) will be ignored";
        } else {
            for (QMapIterator<QString, QVariant> it(m_app->environmentVariables()); it.hasNext(); ) {
                it.next();
                QString name = it.key();
                if (!name.isEmpty()) {
                    QString value = it.value().toString();
                    if (value.isNull())
                        env.remove(it.key());
                    else
                        env.insert(name, value);
                }
            }
        }
    }

    QStringList args;

    if (m_needsLauncher) {
        m_launchWhenReady = true;
    } else {
        if (!m_document.isNull())
            args << qSL("--start-argument") << m_document;
    }

    if (m_isQuickLauncher)
        args << qSL("--quicklaunch");

    m_process = m_container->start(args, env);

    if (!m_process)
        return false;

    QObject::connect(m_process, &AbstractContainerProcess::started,
                     this, &NativeRuntime::onProcessStarted);
    QObject::connect(m_process, &AbstractContainerProcess::errorOccured,
                     this, &NativeRuntime::onProcessError);
    QObject::connect(m_process, &AbstractContainerProcess::finished,
                     this, &NativeRuntime::onProcessFinished);
    QObject::connect(ApplicationIPCManager::instance(), &ApplicationIPCManager::interfaceCreated,
                     this, &NativeRuntime::registerExtensionInterfaces);

    setState(Startup);
    return true;
}

void NativeRuntime::stop(bool forceKill)
{
    if (!m_process)
        return;

    setState(Shutdown);
    emit aboutToStop();

    if (forceKill) {
        m_process->kill();
        deleteLater();
    } else {
        bool ok;
        int qt = configuration().value(qSL("quitTime")).toInt(&ok);
        if (!ok || qt < 0)
            qt = 250;
        QTimer::singleShot(qt, this, [this]() {
            m_process->terminate();
            deleteLater();
        });
    }
}

void NativeRuntime::onProcessStarted()
{
    setState(Active);
}

void NativeRuntime::onProcessError(QProcess::ProcessError error)
{
    Q_UNUSED(error)
    if (m_state != Active && m_state != Shutdown)
        shutdown(-1, QProcess::CrashExit);
}

void NativeRuntime::onProcessFinished(int exitCode, QProcess::ExitStatus status)
{
    shutdown(exitCode, status);
}

void NativeRuntime::onDBusPeerConnection(const QDBusConnection &connection)
{
    // We have a valid connection - ignore all further connection attempts
    if (m_dbusConnection)
        return;

    m_dbusConnection = true;
    m_dbusConnectionName = connection.name();
    QDBusConnection conn = connection;

    m_applicationInterface = new NativeRuntimeApplicationInterface(this);
    if (!conn.registerObject(qSL("/ApplicationInterface"), m_applicationInterface, QDBusConnection::ExportScriptableContents))
        qCWarning(LogSystem) << "ERROR: could not register the /ApplicationInterface object on the peer DBus:" << conn.lastError().name() << conn.lastError().message();

#ifdef EXPORT_P2PBUS_OBJECTS_TO_SESSION_BUS
    QDBusConnection::sessionBus().registerObject(qSL("/Application%1/ApplicationInterface").arg(applicationProcessId()),
                                                 m_applicationInterface, QDBusConnection::ExportScriptableContents);
#endif

    if (m_needsLauncher && m_launchWhenReady && !m_launched) {
        m_runtimeInterface = new NativeRuntimeInterface(this);
        if (!conn.registerObject(qSL("/RuntimeInterface"), m_runtimeInterface, QDBusConnection::ExportScriptableContents))
            qCWarning(LogSystem) << "ERROR: could not register the /RuntimeInterface object on the peer DBus.";

#ifdef EXPORT_P2PBUS_OBJECTS_TO_SESSION_BUS
        QDBusConnection::sessionBus().registerObject(qSL("/Application%1/RuntimeInterface").arg(applicationProcessId()),
                                                     m_runtimeInterface, QDBusConnection::ExportScriptableContents);
#endif
        // we need to delay the actual start call, until the launcher side is ready to
        // listen to the interface
        connect(m_runtimeInterface, &NativeRuntimeInterface::launcherFinishedInitialization,
                this, &NativeRuntime::onLauncherFinishedInitialization);
    }

    // interface availability is dependent on the actual app and we don't
    // have one when quick-launching a runtime
    if (m_app)
        registerExtensionInterfaces();
}

void NativeRuntime::onLauncherFinishedInitialization()
{
    if (m_needsLauncher && m_launchWhenReady && !m_launched && m_app && m_runtimeInterface) {
        registerExtensionInterfaces();

        QString baseDir = m_container->mapHostPathToContainer(m_app->baseDir().absolutePath());
        QString pathInContainer = m_container->mapHostPathToContainer(m_app->absoluteCodeFilePath());
        emit m_runtimeInterface->startApplication(baseDir, pathInContainer, m_document, m_app->toVariantMap());
        m_launched = true;
    }
}

void NativeRuntime::registerExtensionInterfaces()
{
    if (!m_dbusConnection)
        return;

    if (!application())
        return;

    QDBusConnection conn(m_dbusConnectionName);

    // register all extension interfaces
    foreach (ApplicationIPCInterface *iface, ApplicationIPCManager::instance()->interfaces()) {
        if (!iface->isValidForApplication(application()) || m_applicationIPCInterfaces.contains(iface))
            continue;

        if (!iface->dbusRegister(application(), conn)) {
            qCWarning(LogSystem) << "ERROR: could not register the application IPC interface" << iface->interfaceName()
                                 << "at" << iface->pathName() << "on the peer DBus:" << conn.lastError().name() << conn.lastError().message();
        } else {
            m_applicationIPCInterfaces.append(iface);
            emit interfaceCreated(iface->interfaceName());
        }
#ifdef EXPORT_P2PBUS_OBJECTS_TO_SESSION_BUS
        iface->dbusRegister(application(), QDBusConnection::sessionBus());
#endif
    }
}

qint64 NativeRuntime::applicationProcessId() const
{
    return m_process ? m_process->processId() : 0;
}

void NativeRuntime::openDocument(const QString &document)
{
   m_document = document;
   if (m_applicationInterface)
       emit m_applicationInterface->openDocument(document);
}


NativeRuntimeApplicationInterface::NativeRuntimeApplicationInterface(NativeRuntime *runtime)
    : ApplicationInterface(runtime)
    , m_runtime(runtime)
{
    connect(ApplicationManager::instance(), &ApplicationManager::memoryLowWarning,
            this, &ApplicationInterface::memoryLowWarning);
    connect(ApplicationManager::instance(), &ApplicationManager::memoryCriticalWarning,
            this, &ApplicationInterface::memoryCriticalWarning);
    connect(runtime->container(), &AbstractContainer::memoryLowWarning,
            this, &ApplicationInterface::memoryLowWarning);
    connect(runtime->container(), &AbstractContainer::memoryCriticalWarning,
            this, &ApplicationInterface::memoryCriticalWarning);
    connect(runtime, &NativeRuntime::aboutToStop,
            this, &ApplicationInterface::quit);
    connect(runtime, &NativeRuntime::interfaceCreated,
                     this, &ApplicationInterface::interfaceCreated);
}


QString NativeRuntimeApplicationInterface::applicationId() const
{
    if (m_runtime->application())
        return m_runtime->application()->id();
    return QString();
}

QVariantMap NativeRuntimeApplicationInterface::additionalConfiguration() const
{
    return systemProperties();
}

QVariantMap NativeRuntimeApplicationInterface::systemProperties() const
{
    if (m_runtime)
        return m_runtime->systemProperties();
    return QVariantMap();
}

QVariantMap NativeRuntimeApplicationInterface::applicationProperties() const
{
    if (m_runtime && m_runtime->application())
        return m_runtime->application()->allAppProperties();
    return QVariantMap();
}

NativeRuntimeInterface::NativeRuntimeInterface(NativeRuntime *runtime)
    : QObject(runtime)
    , m_runtime(runtime)
{ }

void NativeRuntimeInterface::finishedInitialization()
{
    emit launcherFinishedInitialization();
}


NativeRuntimeManager::NativeRuntimeManager(QObject *parent)
    : NativeRuntimeManager(defaultIdentifier(), parent)
{ }

NativeRuntimeManager::NativeRuntimeManager(const QString &id, QObject *parent)
    : AbstractRuntimeManager(id, parent)
{
    QString dbusAddress = QUuid::createUuid().toString().mid(1,36);
    m_applicationInterfaceServer = new QDBusServer(qSL("unix:path=/tmp/dbus-qtam-") + dbusAddress);

    connect(m_applicationInterfaceServer, &QDBusServer::newConnection,
            this, [this](const QDBusConnection &connection) {
        // If multiple apps are starting in parallel, there will be multiple NativeRuntime objects
        // listening to the newConnection signal from the one and only DBusServer.
        // We have to make sure to forward to the correct runtime object while also handling
        // error conditions.

        qint64 pid = getDBusPeerPid(connection);
        if (pid <= 0) {
            QDBusConnection::disconnectFromPeer(connection.name());
            qCWarning(LogSystem) << "Could not retrieve peer pid on D-Bus connection attempt.";
            return;
        }

        // try direct PID mapping first
        for (NativeRuntime *rt : qAsConst(m_nativeRuntimes)) {
            if (rt->applicationProcessId() == pid) {
                rt->onDBusPeerConnection(connection);
                return;
            }
        }

        // check for sub-processes ... this happens when running the app via gdbserver
        qint64 appmanPid = getpid();

        for (NativeRuntime *rt : qAsConst(m_nativeRuntimes)) {
            qint64 ppid = pid;

            while (ppid > 1 && ppid != appmanPid) {
                ppid = getParentPid(ppid);

                if (rt->applicationProcessId() == ppid) {
                    rt->onDBusPeerConnection(connection);
                    return;
                }
            }
        }

        QDBusConnection::disconnectFromPeer(connection.name());
        qCWarning(LogSystem) << "Connection attempt on peer D-Bus from unknown pid:" << pid;
    });
}

QString NativeRuntimeManager::defaultIdentifier()
{
    return qSL("native");
}

bool NativeRuntimeManager::supportsQuickLaunch() const
{
    return identifier() != qL1S("native");
}

AbstractRuntime *NativeRuntimeManager::create(AbstractContainer *container, const Application *app)
{
    if (!container)
        return nullptr;
    QScopedPointer<NativeRuntime> nrt(new NativeRuntime(container, app, this));
    if (!nrt || !nrt->initialize())
        return nullptr;
    connect(nrt.data(), &QObject::destroyed, this, [this](QObject *o) {
        m_nativeRuntimes.removeOne(static_cast<NativeRuntime *>(o));
    });
    m_nativeRuntimes.append(nrt.data());
    return nrt.take();
}

QDBusServer *NativeRuntimeManager::applicationInterfaceServer() const
{
    return m_applicationInterfaceServer;
}

QT_END_NAMESPACE_AM