summaryrefslogtreecommitdiffstats
path: root/src/b2qt-update-application/main.cpp
blob: 353edd9a60509ab2310fd894400597a30ed39eda (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
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc
** All rights reserved.
** For any questions to Digia, please use the contact form at
** http://qt.digia.com/
**
** 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
** the contact form at http://qt.digia.com/
**
****************************************************************************/

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <unistd.h>
#include <sys/reboot.h>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "update.h"
#include "filewrapper.h"

#define UPDATE_MOUNTPOINT "/mnt/update"

QStringList mounts;

void cleanup()
{
    foreach (const QString &m, mounts) {
        QProcess::execute("umount", QStringList() << m);
    }
    mounts.clear();
}

void error(const QString &message)
{
    fprintf(stderr, "%s\n", message.toLocal8Bit().constData());
    cleanup();
    exit(1);
}

bool execute(const QString &binary, const QStringList &arguments)
{
    int rc = QProcess::execute(binary, arguments);
    if (rc != 0)
        error("Failed to execute command '" + binary + " " + arguments.join(" "));
    return rc == 0;
}

bool mount(const QString &device, const QString &mountpoint, const QString &arguments = QString())
{
    QStringList tmp;
    if (!arguments.isEmpty())
        tmp << "-o" << arguments;

    if (!execute("mount", QStringList() << tmp << device << mountpoint))
        return false;

    if (!arguments.contains("remount"))
        mounts << mountpoint;
    return true;
}

QByteArray readAll(const QString &fileName)
{
    QFile f(fileName);
    if (!f.open(QFile::ReadOnly)) {
        qWarning() << "Could not read" << fileName;
        return QByteArray();
    }

    return f.readAll();
}

bool writeAll(const QString &fileName, const QByteArray &content)
{
    QFile f(fileName);
    if (!f.open(QFile::WriteOnly)) {
        qWarning() << "Could not write" << fileName;
        return false;
    }
    if (f.write(content) != content.size()) {
        qWarning() << "write size mismatch";
        return false;
    }
    f.close();
    return true;
}

QStringList find_usb_storage()
{
    QStringList rc;
    QDir d("/sys/dev/block");

    foreach (QString s, d.entryList()) {
        QFileInfo fi(d.absoluteFilePath(s));
        QString path = fi.canonicalFilePath();
        if (path.contains("/usb"))
            rc += path.mid(path.lastIndexOf('/'));
    }
    return rc;
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    printf("Version %s, SHA1 %s\n", GIT_VERSION, GIT_HASH);

    mount(QString(), "/", "remount,rw");
    execute("mkdir", QStringList() << "-p" << "/mnt/boot");
    execute("mkdir", QStringList() << "-p" << "/mnt/root");
    execute("mkdir", QStringList() << "-p" << UPDATE_MOUNTPOINT);
    mount("/dev/mmcblk0p1", "/mnt/boot", "ro");

    QByteArray update_state = readAll("/mnt/boot/update/state").trimmed();
    if (update_state.isEmpty())
        qFatal("Update state is empty");

    if (update_state == "v")
        qFatal("Update state is 'valid', this should not happen");
    else if (update_state == "t")
        qDebug() << "Update state is 'testing', this should not happen";
    else if (update_state == "u")
        qDebug() << "Update state is 'update'";
    else
        qDebug() << "Unknown update state:" << update_state;

    QStringList usbsticks = find_usb_storage();

    qDebug() << "Found USB storage devices:" << usbsticks;

    bool update_found = false;
    foreach (QString s, usbsticks) {
      if (QProcess::execute("mount", QStringList() << "-o" << "ro" << "/dev/" + s << UPDATE_MOUNTPOINT) == 0) {
          mounts << UPDATE_MOUNTPOINT;
         qDebug() << "mount successful";

         if (QFile::exists(UPDATE_MOUNTPOINT "/b2qt-update")) {
            qDebug() << "update found";
            update_found = true;
            break;
         }
         execute("umount", QStringList() << UPDATE_MOUNTPOINT);
         mounts.removeAt(mounts.lastIndexOf(UPDATE_MOUNTPOINT));
         qDebug() << "no update found";
      } else {
          qDebug() << "mount of" << s << "failed";
      }
    }

    Update update;

    if (update_found) {
          FileWrapper *fw = new FileWrapper(UPDATE_MOUNTPOINT "/b2qt-update", &update);
          if (!fw->open(QFile::ReadOnly))
              qFatal("Failed to open update");
          qDebug() << "Starting update from USB";
          update.setDevice(fw);
    } else {
          QByteArray update_source = readAll("/mnt/boot/update/source").trimmed();
          if (update_source.isEmpty()) {
              execute("umount", QStringList() << "/mnt/boot"); // FIXME
              mounts.removeAt(mounts.lastIndexOf("/mnt/boot"));
              qFatal("Update source is empty");
          }

          execute("udhcpc", QStringList() << "-i" << "eth0");

          QNetworkAccessManager *manager = new QNetworkAccessManager(0);
          QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(update_source)));
          reply->setReadBufferSize(2000000); // 2 MB

          QObject::connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))&QNetworkReply::error,
                     [](QNetworkReply::NetworkError e){qDebug() << "network error" << e;});
          QObject::connect(reply, &QNetworkReply::sslErrors,
                      [](QList<QSslError>){ qDebug() << "ssl errors";});

          qDebug() << "Starting update from Internet" << update_source;
          update.setDevice(reply);
    }

    app.exec();

    qDebug() << "unmount";
    cleanup();

    qDebug() << "sync";
    sync();
    qDebug() << "reboot; waiting 2 seconds";
    sleep(2);
    reboot(RB_AUTOBOOT);
    return 0;
}