summaryrefslogtreecommitdiffstats
path: root/process.cpp
blob: d3d8fdba54be216bc512f464766234a940f145cf (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
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc
** All rights reserved.
** For any questions to Digia, please use contact form at http://www.qt.io
**
** This file is part of Qt Enterprise Embedded.
**
** Licensees holding valid Qt Enterprise licenses may use this file in
** accordance with the Qt Enterprise License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io
**
****************************************************************************/

#include "process.h"
#include <QCoreApplication>
#include <unistd.h>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <QFileInfo>
#include <QTcpSocket>
#include <errno.h>

bool parseConfigFileDirectory(Config *config, const QString &dirName);
static int pipefd[2];

static void signalhandler(int)
{
    write(pipefd[1], " ", 1);
}

static bool analyzeBinary(const QString &binary)
{
    QFileInfo fi(binary);
    if (!fi.exists()) {
        printf("Binary does not exist.\n");
        return false;
    }
    if (!fi.isFile()) {
        printf("Binary is not a file.\n");
        return false;
    }
    if (!fi.isReadable()) {
        printf("Binary is not readable.\n");
        return false;
    }
    if (!fi.isExecutable()) {
        printf("Binary is not executable.\n");
        return false;
    }

    if (fi.size() < 4) {
        printf("Binary is smaller than 4 bytes.\n");
        return false;
    }

    QFile f(binary);
    if (!f.open(QFile::ReadOnly)) {
        printf("Could not open binary to analyze.\n");
        return false;
    }

    QByteArray elfHeader = f.read(4);
    f.close();

    if (elfHeader.size() < 4) {
        printf("Failed to read ELF header.\n");
        return false;
    }

    if (elfHeader != QByteArray::fromHex("7f454C46")) { // 0x7f ELF
        printf("Binary is not an ELF file.\n");
        return false;
    }

    return true;
}

Process::Process()
    : QObject(0)
    , mProcess(new QProcess(this))
    , mDebuggee(0)
    , mDebug(false)
    , mStdoutFd(1)
    , mBeingRestarted(false)
{
    mProcess->setProcessChannelMode(QProcess::SeparateChannels);
    connect(mProcess, &QProcess::readyReadStandardError, this, &Process::readyReadStandardError);
    connect(mProcess, &QProcess::readyReadStandardOutput, this, &Process::readyReadStandardOutput);
    connect(mProcess, (void (QProcess::*)(int, QProcess::ExitStatus))&QProcess::finished, this, &Process::finished);
    connect(mProcess, (void (QProcess::*)(QProcess::ProcessError))&QProcess::error, this, &Process::error);

    if (pipe2(pipefd, O_CLOEXEC) != 0)
        qWarning("Could not create pipe");

    QSocketNotifier *n = new QSocketNotifier(pipefd[0], QSocketNotifier::Read, this);
    connect(n, SIGNAL(activated(int)), this, SLOT(stop()));

    signal(SIGINT, signalhandler);
    signal(SIGTERM, signalhandler);
    signal(SIGHUP, signalhandler);
    signal(SIGPIPE, signalhandler);
}

Process::~Process()
{
    close(pipefd[0]);
    close(pipefd[1]);
}

void Process::forwardProcessOutput(qintptr fd, const QByteArray &data)
{
    const char *constData = data.constData();
    int size = data.size();
    while (size > 0) {
        int written = write(fd, constData, size);
        if (written == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                fd_set outputFdSet;
                FD_ZERO(&outputFdSet);
                FD_SET(fd, &outputFdSet);
                fd_set inputFdSet;
                FD_ZERO(&inputFdSet);
                FD_SET(pipefd[0], &inputFdSet);
                if (select(qMax(fd, static_cast<qintptr>(pipefd[0])) + 1,
                           &inputFdSet, &outputFdSet, NULL, NULL) > 0 &&
                           !FD_ISSET(pipefd[0], &inputFdSet))
                    continue;
                // else fprintf below will output the appropriate errno
            }
            fprintf(stderr, "Cannot forward application output: %d - %s\n", errno, strerror(errno));
            qApp->quit();
            break;
        }
        size -= written;
        constData += written;
    }

    if (mConfig.flags.testFlag(Config::PrintDebugMessages))
        qDebug() << data;
}


void Process::readyReadStandardOutput()
{
    forwardProcessOutput(mStdoutFd, mProcess->readAllStandardOutput());
}

void Process::readyReadStandardError()
{
    QByteArray b = mProcess->readAllStandardError();
    if (mDebug) {
        int index = b.indexOf(" created; pid = ");
        if (index >= 0) {
            mDebuggee = QString::fromLatin1(b.mid(index+16)).toUInt();
        }
        mDebug = false; // only search once
    }
    forwardProcessOutput(2, b);
}

void Process::setDebug()
{
    mDebug = true;
}

void Process::error(QProcess::ProcessError error)
{
    switch (error) {
    case QProcess::FailedToStart:
        printf("Failed to start\n");
        analyzeBinary(mBinary);
        break;
    case QProcess::Crashed:
        printf("Application crashed: %s\n", qPrintable(mBinary));
        break;
    case QProcess::Timedout:
        printf("Timedout\n");
        break;
    case QProcess::WriteError:
        printf("Write error\n");
        break;
    case QProcess::ReadError:
        printf("Read error\n");
        break;
    case QProcess::UnknownError:
        printf("Unknown error\n");
        break;
    }
    if (!mBeingRestarted)
        qApp->quit();
}

void Process::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    if (exitStatus == QProcess::NormalExit)
        printf("Process exited with exit code %d\n", exitCode);
    else
        printf("Process stopped\n");
    if (!mBeingRestarted) {
        qDebug() << "quit";
        qApp->quit();
    }
}

void Process::startup()
{
#ifdef Q_OS_ANDROID
    QProcessEnvironment pe = interactiveProcessEnvironment();
#else
    QProcessEnvironment pe = QProcessEnvironment::systemEnvironment();
#endif
    QStringList args = mStartupArguments;
    mBeingRestarted = false;

    Config actualConfig = mConfig;

    // Parse temporary config files
    // This needs to be done on every startup because those files are expected to change.
    parseConfigFileDirectory(&actualConfig, "/var/lib/b2qt/appcontroller.conf.d");
    parseConfigFileDirectory(&actualConfig, "/tmp/b2qt/appcontroller.conf.d");

    foreach (const QString &key, actualConfig.env.keys()) {
        if (!pe.contains(key)) {
            qDebug() << key << actualConfig.env.value(key);
            pe.insert(key, actualConfig.env.value(key));
        }
    }
    if (!actualConfig.base.isEmpty())
        pe.insert(QLatin1String("B2QT_BASE"), actualConfig.base);
    if (!actualConfig.platform.isEmpty())
        pe.insert(QLatin1String("B2QT_PLATFORM"), actualConfig.platform);

    args.append(actualConfig.args);

    mProcess->setProcessEnvironment(pe);
    mBinary = args.first();
    args.removeFirst();
    qDebug() << mBinary << args;
    mProcess->start(mBinary, args);
}

void Process::start(const QStringList &args)
{
    mStartupArguments = args;
    startup();
}

void Process::stop()
{
    if (mProcess->state() == QProcess::QProcess::NotRunning) {
        printf("No process running\n");
        if (!mBeingRestarted)
            qApp->exit();
        return;
    }

    if (mDebuggee != 0) {
        qDebug() << "Kill debuggee " << mDebuggee;
        if (kill(mDebuggee, SIGKILL) != 0)
            perror("Could not kill debugee");
    }
    if (kill(-getpid(), SIGTERM) != 0)
        perror("Could not kill process group");

    mProcess->terminate();
    if (!mProcess->waitForFinished())
        mProcess->kill();
}

void Process::stopForRestart()
{
    printf("Stopping application for restart\n");
    mBeingRestarted = true;
    stop();
}

void Process::restart()
{
    printf("Restarting application\n");
    mBeingRestarted = true;
    stop();
    startup();
}

void Process::incomingConnection(int i)
{
    int fd = accept(i, NULL, NULL);
    if (fd < 0 ) {
        perror("Could not accept connection");
        stop();
        return;
    }

    QLocalSocket localSocket;
    if (!localSocket.setSocketDescriptor(fd)) {
        fprintf(stderr, "Could not initialize local socket from descriptor.\n");
        close(fd);
        stop();
        return;
    }

    if (!localSocket.waitForReadyRead()) {
        fprintf(stderr, "No command received.\n");
        stop(); // default
        return;
    }

    QByteArray command = localSocket.readAll();

    if (command == "stop")
        stop();
    else if (command == "restart")
        restart();
    else if (command == "stopForRestart")
        stopForRestart();
    else
        stop();
}

void Process::setSocketNotifier(QSocketNotifier *s)
{
    connect(s, &QSocketNotifier::activated, this, &Process::incomingConnection);
}

void Process::setConfig(const Config &config)
{
    mConfig = config;
}

void Process::setStdoutFd(qintptr stdoutFd)
{
    mStdoutFd = stdoutFd;
}

QProcessEnvironment Process::interactiveProcessEnvironment() const
{
    QProcessEnvironment env;

    QProcess process;
    process.start("sh");
    if (!process.waitForStarted(3000)) {
        printf("Could not start shell.\n");
        return env;
    }

    process.write("source /system/etc/mkshrc\n");
    process.write("export -p\n");
    process.closeWriteChannel();

    printf("waiting for process to finish\n");
    if (!process.waitForFinished(1000)) {
        printf("did not finish: terminate\n");
        process.terminate();
        if (!process.waitForFinished(1000)) {
            printf("did not terminate: kill\n");
            process.kill();
            if (!process.waitForFinished(1000)) {
                printf("Could not stop process.\n");
            }
        }
    }

    QList<QByteArray> list = process.readAllStandardOutput().split('\n');
    if (list.isEmpty())
       printf("Failed to read environment output\n");

    foreach (QByteArray entry, list) {
        if (entry.startsWith("export ")) {
            entry = entry.mid(7);
        } else if (entry.startsWith("declare -x ")) {
            entry = entry.mid(11);
        } else {
            continue;
        }

        QByteArray key;
        QByteArray value;
        int index = entry.indexOf('=');

        if (index > 0) {
            key = entry.left(index);
            value = entry.mid(index + 1);
        } else {
            key = entry;
            // value is empty
        }

        // Remove simple escaping.
        // This is not complete.
        if (value.startsWith('\'') and value.endsWith('\''))
            value = value.mid(1, value.size()-2);
        else if (value.startsWith('"') and value.endsWith('"'))
            value = value.mid(1, value.size()-2);

        env.insert(key, value);
    }

    return env;
}