forked from Stremio/stremio-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoupdater.cpp
353 lines (283 loc) · 12.1 KB
/
autoupdater.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
#include <autoupdater.h>
#ifdef Q_OS_MACOS
#include <sys/types.h>
#include <sys/sysctl.h>
#include <QDebug>
#endif
AutoUpdater::AutoUpdater(): manager(new QNetworkAccessManager(this)) {
init_public_key();
}
// HANDLE FATAL ERRORS
void AutoUpdater::emitFatalError(QString msg, QVariant err = QVariant()) {
this->abort();
emit error(msg, err);
}
// IS INSTALLED?
bool AutoUpdater::isInstalled() {
QString dirPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath());
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
// Windows
if (env.contains("LOCALAPPDATA") && dirPath.startsWith(env.value("LOCALAPPDATA"))) return true;
if (env.contains("ProgramFiles") && dirPath.startsWith(env.value("ProgramFiles"))) return true;
if (env.contains("ProgramFiles(x86)") && dirPath.startsWith(env.value("ProgramFiles(x86)"))) return true;
// macOS
if (dirPath.contains("/Applications") && dirPath.contains(".app")) return true;
// Rosetta2
#ifdef Q_OS_MACOS
int ret = 0;
size_t size = sizeof(ret);
if (sysctlbyname("sysctl.proc_translated", &ret, &size, NULL, 0) >= 0 && ret) {
QDir pathDir("/Applications/Stremio.app");
qDebug() << "AUTOUPDATER: Installed on Rosetta!";
return pathDir.exists();
}
#endif
// Linux - appImage
if (dirPath.startsWith("/tmp/.mount_")) return true;
// Other UNIX
// Disabled, because we cannot update those cases
//if (dirPath.contains("/usr/bin") || dir.contains("/usr/local") || dir.contains("/opt")) return true;
return false;
}
// WRAPPERS for public slots to make sure we execute on our thread
void AutoUpdater::checkForUpdates(QString endpoint, QString userAgent) {
if (inProgress) return;
inProgress = true;
QMetaObject::invokeMethod(this, "checkForUpdatesPerform", Qt::QueuedConnection, Q_ARG(QString, endpoint), Q_ARG(QString, userAgent));
}
void AutoUpdater::updateFromVersionDesc(QUrl versionDesc, QByteArray base64Sig) {
if (inProgress) return;
inProgress = true;
QMetaObject::invokeMethod(this, "updateFromVersionDescPerform", Qt::QueuedConnection, Q_ARG(QUrl, versionDesc),
Q_ARG(QByteArray, base64Sig));
}
void AutoUpdater::abort() {
QMetaObject::invokeMethod(this, "abortPerform", Qt::QueuedConnection);
}
// SETTINGS
void AutoUpdater::setForceFullUpdate(bool force) {
forceFullUpdate = force;
}
// UTILS
bool AutoUpdater::moveFileToAppDir(QString from) {
QDir dir;
QFileInfo oldFile = QFileInfo(from);
QString dest = QCoreApplication::applicationDirPath() + QDir::separator() + oldFile.fileName();
if (! QFile::exists(from)) return false;
if (QFile::exists(dest)) {
if (! QFile::remove(dest)) return false;
}
return dir.rename(from, dest);
}
int AutoUpdater::executeCmd(QString cmd, QStringList args, bool noWait = false) {
QProcess proc;
proc.setProcessChannelMode(QProcess::ForwardedChannels);
if (noWait) {
proc.startDetached(cmd, args);
return -1;
}
proc.start(cmd, args);
// We mostly need quick commands executed, and waiting for them in that func removes a huge layer of complexity
if (! proc.waitForFinished(5 * 60 * 1000)) return -1;
return proc.exitCode();
}
// CHECK FOR UPDATES
void AutoUpdater::checkForUpdatesPerform(QString endpoint, QString userAgent)
{
QByteArray serverHash = getFileChecksum(QCoreApplication::applicationDirPath() + QDir::separator() + SERVER_FNAME);
QByteArray asarHash = getFileChecksum(QCoreApplication::applicationDirPath() + QDir::separator() + ASAR_FNAME);
QUrl url = QUrl(endpoint);
QUrlQuery query = QUrlQuery(url);
query.addQueryItem("serverSum", serverHash.toHex());
query.addQueryItem("asarSum", asarHash.toHex());
query.addQueryItem("shellVersion", QCoreApplication::applicationVersion());
url.setQuery(query);
auto request = QNetworkRequest(QUrl(url));
request.setRawHeader("User-Agent", userAgent.toUtf8());
currentCheck = manager->get(request);
QObject::connect(currentCheck, &QNetworkReply::finished, this, &AutoUpdater::checkForUpdatesFinished);
}
void AutoUpdater::checkForUpdatesFinished()
{
if (currentCheck == NULL) {
emitFatalError("internal error - currentCheck NULL on checkForUpdatesFinished");
return;
}
QNetworkReply* reply = currentCheck;
reply->deleteLater();
currentCheck = NULL;
if (reply->error() == QNetworkReply::NoError) {
QJsonParseError *error = NULL;
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), error);
emit checkFinished(jsonResponse.toVariant());
if (jsonResponse.isObject()) {
QJsonObject obj = jsonResponse.object();
if (obj.value("upToDate").toBool()) {
// NO NEW VERSION, DO NOTHING
inProgress = false;
} else {
updateFromVersionDescPerform(
QUrl(obj.value("versionDesc").toString()),
QByteArray::fromBase64(obj.value("signature").toString().toUtf8())
);
}
} else if (error) {
emitFatalError("JSON parse error on checkForUpdates "+error->errorString());
} else {
emitFatalError("Unable to understand response from checkForUpdates");
}
delete error;
} else if (reply->error() != QNetworkReply::OperationCanceledError) {
emitFatalError("Network error on checkForUpdates "+reply->url().toString(), reply->error());
}
}
// GET & VERIFY (SIGNATURE) VERSION DESC
void AutoUpdater::updateFromVersionDescPerform(QUrl versionDesc, QByteArray base64Sig) {
currentCheck = manager->get(QNetworkRequest(versionDesc));
currentCheck->setProperty("signature", base64Sig);
QObject::connect(currentCheck, &QNetworkReply::finished, this, &AutoUpdater::updateFromVersionDescFinished);
}
void AutoUpdater::updateFromVersionDescFinished() {
if (currentCheck == NULL) {
emitFatalError("internal error - currentCheck NULL on updateFromVersionDescFinished");
return;
}
QNetworkReply* reply = currentCheck;
reply->deleteLater();
currentCheck = NULL;
if (reply->error() == QNetworkReply::NoError) {
QByteArray dataReply = reply->readAll();
QByteArray sig = reply->property("signature").toByteArray();
if (verify_sig(
(const byte*)dataReply.data(), dataReply.size(),
(const byte*)sig.data(), sig.length()
) != 0) {
emitFatalError("Unable to verify update signature");
} else {
QJsonParseError *error = NULL;
QJsonDocument jsonResponse = QJsonDocument::fromJson(dataReply, error);
if (jsonResponse.isObject()) {
prepareUpdate(jsonResponse);
} else if (error) {
emitFatalError("JSON parse error on updateFromVersionDesc "+error->errorString());
} else {
emitFatalError("Unable to understand response from updateFromVersionDesc");
}
delete error;
}
} else if (reply->error() != QNetworkReply::OperationCanceledError) {
emitFatalError("Network error on updateFromVersionDesc "+reply->url().toString(), reply->error());
}
}
// DETERMINE WHAT TO DOWNLOAD FROM versionDesc
void AutoUpdater::prepareUpdate(QJsonDocument versionDescDoc) {
currentVersionDesc = versionDescDoc;
QJsonObject versionDesc = versionDescDoc.object();
QJsonObject files = versionDesc.value("files").toObject();
QVector<QString> toDownload;
if (forceFullUpdate
|| versionDesc.value("shellVersion").toString() != QCoreApplication::applicationVersion()
) {
toDownload = FULL_UPDATE_FILES;
} else {
toDownload = PARTIAL_UPDATE_FILES;
}
if (! toDownload.length()) {
emitFatalError("internal error - no files to download. Unsupported OS?");
return;
}
foreach (const QString &prop, toDownload) {
QJsonObject file = files.value(prop).toObject();
if (! (file.contains("url") && file.contains("checksum"))) continue;
enqueueDownload(
QUrl(file.value("url").toString()),
QByteArray::fromHex(file.value("checksum").toString().toUtf8())
);
}
startNextDownload();
}
// DOWNLOAD & VERIFY (CHECKSUM)
QByteArray AutoUpdater::getFileChecksum(QString path) {
QCryptographicHash crypto(QCryptographicHash::Sha256);
QFile file(path);
file.open(QFile::ReadOnly);
while (!file.atEnd()) { crypto.addData(file.read(FILE_READ_CHUNK)); }
return crypto.result();
}
void AutoUpdater::enqueueDownload(QUrl from, QByteArray checksum) {
downloadQueue.enqueue(fDownload(from, checksum));
}
void AutoUpdater::startNextDownload() {
if (downloadQueue.isEmpty()) {
inProgress = false;
emit prepared(preparedFiles, QVariant(currentVersionDesc.object()));
return;
}
fDownload next = downloadQueue.dequeue();
QUrl url = next.first;
QByteArray checksum = next.second;
// WARNING: TODO: do we want to make a separate dir inside tempPath? ; we should ensure downloadFile always overrides
QString dest = QDir::tempPath() + QDir::separator() + url.fileName();
// Check if the download is already downloaded - could happen if we try to do a full upgrade when we've
// already prepared one
// Sketchy case: if the file does not exist, getFileChecksum would return the default sha256 hash; -
// this would actually prevent a case where the version descriptor is generated from empty files from breaking
// the system - because this check would return true, and then the file wouldn't exist at all, emitting an error
// (this shouldn't be able to happen, but still...)
if (checksum == getFileChecksum(dest)) {
preparedFiles.push_back(dest);
startNextDownload();
return;
}
// Start the download
output.setFileName(dest);
if (!output.open(QIODevice::WriteOnly)) {
emitFatalError("error opening file "+dest+" for download: "+output.errorString());
return;
}
currentDownload = manager->get(QNetworkRequest(url));
currentDownload->setProperty("checksum", checksum);
QObject::connect(currentDownload, &QNetworkReply::readyRead, this, &AutoUpdater::downloadReadyRead);
QObject::connect(currentDownload, &QNetworkReply::finished, this, &AutoUpdater::downloadFinished);
}
void AutoUpdater::downloadReadyRead()
{
output.write(currentDownload->readAll());
}
void AutoUpdater::downloadFinished()
{
output.close();
if (currentDownload == NULL) {
emitFatalError("internal error - currentDownload NULL on downloadFinished");
return;
}
QNetworkReply* reply = currentDownload;
reply->deleteLater();
currentDownload = NULL;
if (reply->error() == QNetworkReply::NoError) {
QString dest = output.fileName();
QByteArray checksum = reply->property("checksum").toByteArray();
if (checksum == getFileChecksum(dest)) {
preparedFiles.push_back(dest);
startNextDownload();
} else {
emitFatalError("Unable to verify checksum for file "+dest);
}
} else if (reply->error() != QNetworkReply::OperationCanceledError) {
emitFatalError("Network error on downloadFinished "+reply->url().toString(), reply->error());
}
}
// ABORT
void AutoUpdater::abortPerform() {
// EXPLANATION: those will be aborted, and then in the 'finished' handler, they will be deleted via ->deleteLater()
// since the event handlers are executed in the event loop, one might think calling .checkForVer() right after
// .abort() will re-set currentCheck before the 'finished' handler is executed
// This is not a problem, because all public methods call the internal ones with invokeMethod and queuedConnection
if (currentCheck) currentCheck->abort();
if (currentDownload) currentDownload->abort();
currentVersionDesc = QJsonDocument();
downloadQueue = QQueue<fDownload>();
preparedFiles = QVariantList();
output.close();
inProgress = false;
}