Debian Codegraph @

src/installer.cpp

raw symbols SCIP
1 // Copyright (C) 2014 Sacha Refshauge
2
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, version 3.0.
6
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // GNU General Public License 3.0 for more details.
11
12 // A copy of the GPL 3.0 should have been included with the program.
13 // If not, see http://www.gnu.org/licenses/
14
15 // Official GIT repository and contact information can be found at
16 // http://github.com/xsacha/Sachesi
17
18 #define DEBUG_LOG 0
19
20 #include "installer.h"
21 #include "ports.h"
22 #include <QAbstractListModel>
23 #include <QDebug>
24 #include <QMessageBox>
25 #include <QNetworkInterface>
26
27 InstallNet::InstallNet( QObject* parent) : QObject(parent),
28 device(nullptr), manager(nullptr), reply(nullptr), cookieJar(nullptr),
29 _wrongPass(false), _loginBlock(false),
30 _state(0), _dlBytes(0), _dlTotal(0), _dgProgress(-1), _curDGProgress(-1),
31 _completed(false), _extractInstallZip(false), _allowDowngrades(false), _installing(false), _restoring(false), _backing(false),
32 _hadPassword(true), currentBackupZip(nullptr), _zipFile(nullptr)
33 {
34 #ifdef _MSC_VER
35 WSAStartup(MAKEWORD(2,0), &wsadata);
36 #endif
37 connectTimer = new QTimer();
38 connectTimer->setInterval(3000);
39 connectTimer->start();
40 connect(connectTimer, SIGNAL(timeout()), this, SLOT(login()));
41 QSettings settings("Qtness","Sachesi");
42 connect(&_back, SIGNAL(curModeChanged()), this, SIGNAL(backStatusChanged()));
43 connect(&_back, SIGNAL(curSizeChanged()), this, SIGNAL(backCurProgressChanged()));
44 connect(&_back, SIGNAL(numMethodsChanged()), this, SIGNAL(backMethodsChanged()));
45
46 logFile = new QTemporaryFile("XXXXXXXX.txt");
47 logFile->open(); // This will autoclose and autoremove by default when ~InstallNet
48
49 QByteArray hashedPass = settings.value("pass", "").toByteArray();
50
51 if (hashedPass.isEmpty()) {
52 _password = "";
53 } else {
54 int passSize = QByteArray::fromBase64(hashedPass.left(4))[0];
55 hashedPass = QByteArray::fromBase64(hashedPass.mid(4));
56
57 char * decPass = new char[passSize+1];
58 for (int i = 0; i < passSize; i++) {
59 decPass[i] = hashedPass[i] ^ ((0x40 + 5 * i - passSize) % 127);
60 }
61 decPass[passSize] = 0;
62 _password = QString(decPass);
63 delete decPass;
64 }
65 emit newPassword(_password);
66 login();
67 }
68 InstallNet::~InstallNet()
69 {
70 // Windows has issues autoremoving logFile
71 logFile->close();
72 logFile->remove();
73 #ifdef _MSC_VER
74 WSACleanup();
75 #endif
76 }
77
78 QNetworkRequest InstallNet::setData(QString page, QString contentType) {
79 QNetworkRequest request = QNetworkRequest();
80 request.setUrl(QUrl("https://" + _ip + "/cgi-bin/" + page));
81 request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, "QNXWebClient/1.0");
82 request.setHeader(QNetworkRequest::ContentTypeHeader, "application/" + contentType);
83 return request;
84 }
85
86 QNetworkReply* InstallNet::postQuery(QString page, QString contentType, const QUrlQuery& query) {
87 reply = manager->post(setData(page, contentType), query.encodedQuery());
88 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
89 this, SLOT(restoreError(QNetworkReply::NetworkError)));
90 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
91 return reply;
92 }
93
94 QNetworkReply* InstallNet::getQuery(QString page, QString contentType) {
95 reply = manager->get(setData(page, contentType));
96 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
97 this, SLOT(restoreError(QNetworkReply::NetworkError)));
98 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
99 return reply;
100 }
101
102 void InstallNet::scanProps()
103 {
104 if (checkLogin())
105 {
106 QUrlQuery postData;
107 postData.addQueryItem("Get Dynamic Properties","Get Dynamic Properties");
108 postQuery("dynamicProperties.cgi", "x-www-form-urlencoded", postData);
109 }
110 }
111
112 BarInfo InstallNet::checkInstallableInfo(QString name, bool blitz)
113 {
114 BarInfo barInfo = {name, "", "", NotInstallableType};
115 // Check if it's a 'hidden' file as we use these for temporary file downloads.
116 if (QFileInfo(name).fileName().startsWith('.'))
117 return barInfo;
118
119 QuaZipFile manifest(name, "META-INF/MANIFEST.MF", QuaZip::csSensitive);
120 if (!manifest.open(QIODevice::ReadOnly))
121 return barInfo;
122 QString appName, type;
123 while (!manifest.atEnd()) {
124 QByteArray newLine = manifest.readLine();
125 if (newLine.startsWith("Package-Name:") || newLine.startsWith("Patch-Package-Name:")) {
126 appName = newLine.split(':').last().simplified();
127 if (newLine.startsWith("Patch") && type == "system") {
128 if (appName.contains("radio"))
129 barInfo.type = RadioType;
130 else
131 barInfo.type = OSType;
132 }
133 }
134 else if (newLine.startsWith("Package-Type:") || newLine.startsWith("Patch-Package-Type:")) {
135 type = newLine.split(':').last().simplified();
136 if (type == "system" && barInfo.type == NotInstallableType)
137 barInfo.type = OSType;
138 }
139 else if (newLine.startsWith("Package-Version:")) {
140 barInfo.version = newLine.split(':').last().simplified();
141 }
142 else if (newLine.startsWith("Package-Id:")) {
143 barInfo.packageid = newLine.split(':').last().simplified();
144 }
145 else if (newLine.startsWith("System-Type:")) {
146 if (newLine.split(':').last().simplified() == "radio")
147 barInfo.type = RadioType;
148 } else if (newLine.startsWith("Archive-Asset-Name:")) {
149 // A sign we need to get out of here when it is listing assets
150 break;
151 }
152 }
153
154 // Check if we are about to make a huge mistake!
155 if (barInfo.type == OSType) {
156 if (!_allowDowngrades && isVersionNewer(device->os, barInfo.version, true)) {
157 setNewLine(QString("OS %1 skipped. Newer version is installed(%2)").arg(barInfo.version).arg(device->os));
158 barInfo.type = NotInstallableType;
159 return barInfo;
160 }
161
162 QString installableOS = appName.split("os.").last().remove(".desktop").replace("verizon", "factory");
163 if (_knownConnectedOSType != "" && installableOS != _knownConnectedOSType && !(installableOS.contains("8974") && _knownConnectedOSType.contains("8974"))) {
164 if (blitz) {
165 barInfo.type = NotInstallableType;
166 return barInfo;
167 } else {
168 int choice = QMessageBox::critical(nullptr, "WARNING", "The OS file you have selected to install is for a different device!\nOS Type: " + installableOS + "\nYour Device: " + _knownConnectedOSType, "Ignore Warning [Stupid]", "Skip OS", "Cancel Install", 2);
169 if (choice == 1) {
170 barInfo.type = NotInstallableType;
171 return barInfo;
172 }
173 if (choice == 2) {
174 barInfo.name = "EXIT";
175 return barInfo;
176 }
177 }
178 }
179 } else if (barInfo.type == RadioType) {
180 if (!_allowDowngrades && isVersionNewer(device->radio, barInfo.version, true)) {
181 setNewLine(QString("Radio %1 skipped. Newer version is installed(%2)").arg(barInfo.version).arg(device->radio));
182 barInfo.type = NotInstallableType;
183 return barInfo;
184 }
185 QString installableRadio = appName.split("radio.").last().remove(".omadm");
186 if (_knownConnectedRadioType != "" && installableRadio != _knownConnectedRadioType) {
187 if (blitz) {
188 barInfo.type = NotInstallableType;
189 return barInfo;
190 } else {
191 int choice = QMessageBox::critical(nullptr, "WARNING", "The Radio file you have selected to install is for a different device!\nRadio Type: " + installableRadio + "\nYour Device: " + _knownConnectedRadioType, "Ignore Warning [Stupid]", "Skip Radio", "Cancel Install", 2);
192 if (choice == 1) {
193 barInfo.type = NotInstallableType;
194 return barInfo;
195 }
196 if (choice == 2) {
197 barInfo.name = "EXIT";
198 return barInfo;
199 }
200 }
201 }
202 }
203
204 // Check if we are upgrading firmware or just installing apps.
205 if (type == "system") {
206 // Only if installing
207 setNewLine(QString("<b>Installing ") + (barInfo.type == OSType ? "OS: " : "Radio: " ) + barInfo.version + "</b>");
208 setFirmwareUpdate(true);
209 } else if (!type.isEmpty())
210 barInfo.type = AppType;
211
212 manifest.close();
213 return barInfo;
214 }
215
216 void InstallNet::install(QList<QUrl> files)
217 {
218 _installInfo.clear();
219 setFirmwareUpdate(false);
220 QList<QString> filenames;
221
222 // Zip install
223 if (files.count() == 1 && files.first().toLocalFile().endsWith(".zip")) {
224 // First, ensure it is a real zip
225 QFile testZip(files.first().toLocalFile());
226 testZip.open(QIODevice::ReadOnly);
227 if (testZip.read(2).toHex() != "504b") {
228 QMessageBox::information(nullptr, "Error", "The selected .zip file is, in fact, not a zip file.");
229 return;
230 }
231 testZip.close();
232 // A collection of bars
233 _extractInstallZip = true; emit extractInstallZipChanged();
234 QuaZip zip(files.first().toLocalFile());
235 zip.open(QuaZip::mdUnzip);
236
237 QuaZipFile file(&zip);
238 QFileInfo zipInfo(zip.getZipName());
239
240 QString baseName = zipInfo.absolutePath() + "/" + zipInfo.completeBaseName();
241
242 if (!QDir(baseName).mkpath("."))
243 QMessageBox::information(nullptr, "Error", "Was unable to extract the zip container.");
244
245 for(bool f=zip.goToFirstFile(); f; f=zip.goToNextFile()) {
246 QString thisFile = baseName + "/" + zip.getCurrentFileName().split('/').last();
247 if (QFile::exists(thisFile)) {
248 QuaZipFileInfo info;
249 zip.getCurrentFileInfo(&info);
250 if (QFile(thisFile).size() == info.uncompressedSize) {
251 filenames.append(thisFile);
252 continue;
253 } else {
254 QFile(thisFile).remove();
255 }
256 }
257 if (!file.open(QIODevice::ReadOnly))
258 continue;
259 // Check we have a zip
260 if (file.read(2).toHex() == "504b") {
261 QFile writeFile(thisFile);
262 if (!writeFile.open(QIODevice::WriteOnly)) {
263 file.close();
264 continue;
265 }
266 writeFile.write(QByteArray::fromHex("504b"));
267 while (!file.atEnd()) {
268 qApp->processEvents();
269 writeFile.write(file.read(8192000));
270 }
271 filenames.append(thisFile);
272 }
273 file.close();
274 }
275 _extractInstallZip = false; emit extractInstallZipChanged();
276 } else {
277
278 // Grab file names (first pass)
279 foreach(QUrl url, files)
280 {
281 if (!url.isLocalFile())
282 continue;
283 QString name = url.toLocalFile();
284 if (QFileInfo(name).isDir())
285 {
286 QStringList barFiles = QDir(name).entryList(QStringList("*.bar"));
287 foreach (QString barFile, barFiles) {
288 filenames.append(name + "/" + barFile);
289 }
290 } else {
291 filenames.append(name);
292 }
293 }
294 }
295
296 // Detect Blitz files (second pass)
297 BlitzInfo blitz(filenames, _knownConnectedOSType, _knownConnectedRadioType);
298
299 if (blitz.isBlitz()) {
300 setNewLine(QString("%1 Blitz detected. %2 OSes and %3 Radios")
301 .arg(blitz.isSafe() ? "Safe " : "Unsafe")
302 .arg(blitz.osCount)
303 .arg(blitz.radioCount));
304 if (_knownConnectedRadioType == "" && blitz.radioCount > 1) {
305 QMessageBox::critical(nullptr, "Error", "Your device is reporting no Radio. The blitz install is unable to detect the correct Radio for your system and cannot continue.");
306 return;
307 } else if (_knownConnectedOSType == "" && blitz.osCount > 1) {
308 QMessageBox::critical(nullptr, "Error", "Your device is reporting no OS. The blitz install is unable to detect the correct OS for your system and cannot continue.");
309 return;
310 }
311 if (!blitz.isSafe()) {
312 QMessageBox::critical(nullptr, "Error", QString("The blitz file does not contain compatible firmware.") + (!blitz.osIsSafe ? "\nNo compatible OS" : "") + (!blitz.radioIsSafe ? "\nNo compatible Radio" : ""));
313 return;
314 }
315 }
316
317 int skipCount = 0;
318 // Detect everything (third pass)
319 foreach(QString barFile, filenames)
320 {
321 BarInfo info = checkInstallableInfo(barFile, blitz.isBlitz());
322 if (info.name == "EXIT")
323 return setNewLine("Install aborted.");
324 else if (info.type == AppType) {
325 foreach(Apps* app, _appList) {
326 if (!_allowDowngrades && info.packageid == app->packageId()) {
327 if (isVersionNewer(app->version(), info.version, true)) {
328 setNewLine(QString("%1 was skipped. Version %2 already installed").arg(QFileInfo(info.name).completeBaseName()).arg(app->version()));
329 info.type = NotInstallableType;
330 }
331
332 break;
333 }
334 }
335 }
336 if (info.type != NotInstallableType)
337 _installInfo.append(info);
338 else
339 skipCount++;
340 }
341 if (_installInfo.isEmpty()) {
342 setNewLine(QString("None of the selected files were installable. Skipped %2.")
343 .arg(skipCount));
344 return;
345 }
346 setNewLine(QString("Installing <b>%1</b> .bar(s).%2.")
347 .arg(_installInfo.count())
348 .arg(skipCount > 0 ? QString(" Skipped %1").arg(skipCount) : ""));
349 install();
350 }
351
352 void InstallNet::install()
353 {
354 setInstalling(true);
355 if (checkLogin())
356 {
357 QUrlQuery postData;
358 _downgradePos = 0;
359 _downgradeInfo.clear();
360 foreach (auto filePair, _installInfo)
361 _downgradeInfo.append(filePair.name);
362
363 emit dgPosChanged();
364 emit dgMaxPosChanged();
365 _dlDoneBytes = 0;
366 _dlOverallTotal = 0;
367 for(QString filename : _downgradeInfo)
368 _dlOverallTotal += QFile(filename).size();
369 if (_dlOverallTotal * 1.5 > device->freeSpace) {
370 QMessageBox::critical(nullptr, "Free Space", QString("Sachesi has determined you may not have enough free space on your device to continue this update.\n"
371 "It is estimated that you would need %1 GB but you only have %2 GB. Please free up some space.")
372 .arg(QString::number((_dlOverallTotal * 1.5) / 1024 / 1024 / 1024, 'g', 3))
373 .arg(QString::number((device->freeSpace * 1.0) / 1024 / 1024 / 1024, 'g', 3)));
374 setNewLine("Install aborted. No free space.");
375 setInstalling(false);
376 return;
377 }
378
379 postData.addQueryItem("mode", _firmwareUpdate ? "os" : "bar");
380 postData.addQueryItem("size", QString::number(_dlOverallTotal));
381 postQuery("update.cgi", "x-www-form-urlencoded", postData);
382 }
383 }
384
385 void InstallNet::uninstall(QStringList packageids, bool firmwareUpdate)
386 {
387 Q_UNUSED(firmwareUpdate) // Dangerous!
388 // Tested with OS and it removed the old OS. Not entirely what I wanted.
389 if (packageids.isEmpty())
390 return;
391 setInstalling(true);
392 if (checkLogin())
393 {
394 QUrlQuery postData;
395 _installInfo.clear();
396 _downgradePos = 0;
397 _downgradeInfo = packageids;
398 emit dgPosChanged();
399 emit dgMaxPosChanged();
400 postData.addQueryItem("mode", "app");
401 postData.addQueryItem("size", "0");
402
403 postQuery("update.cgi", "x-www-form-urlencoded", postData);
404 }
405 }
406
407 bool InstallNet::uninstallMarked()
408 {
409 QStringList marked;
410 bool firmwareUpdate = false;
411 for(Apps* app : _appList) {
412 if (app->isMarked()) {
413 marked.append(app->packageId());
414 app->setIsMarked(false);
415 if (app->type() != "application")
416 firmwareUpdate = true;
417 app->setType("");
418 }
419 }
420 if (marked.isEmpty())
421 return false;
422 uninstall(marked, firmwareUpdate);
423 return true;
424 }
425
426 // For finding Blackberry Link backup path
427 /*#ifdef _WIN32
428 QFile linkSettings(QDir::homePath()+"/AppData/Roaming/Research In Motion/BlackBerry 10 Desktop/Settings.config");
429 linkSettings.open(QIODevice::WriteOnly);
430 QXmlStreamReader xml(&linkSettings);
431 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
432 if (xml.isStartElement()) {
433 if (xml.name() == "Configuration" && xml.attributes().count() > 1 && xml.attributes().at(0).value() == "BackupFolderLocation") {
434 dir = xml.attributes().at(1).value().toString();
435 }
436 }
437 }
438 linkSettings.close();
439 #endif*/
440
441 void InstallNet::backup()
442 {
443 setBacking(true);
444 if (checkLogin())
445 {
446 currentBackupZip = new QuaZip(_backupFileName);
447 currentBackupZip->setZip64Enabled(true);
448 currentBackupZip->open(QuaZip::mdCreate);
449 if (!currentBackupZip->isOpen()) {
450 QMessageBox::critical(nullptr, "Error", "Unable to write backup. Please ensure you have permission to write to " + _backupFileName);
451 delete currentBackupZip;
452 currentBackupZip = nullptr;
453 setBacking(false);
454 return;
455 }
456
457 QuaZipFile* manifest;
458 manifest = new QuaZipFile(currentBackupZip);
459 QuaZipNewInfo newInfo("Manifest.xml");
460 newInfo.setPermissions(QFileDevice::Permission(0x7774));
461 manifest->open(QIODevice::WriteOnly, newInfo);
462 QString manifestXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
463 "<BlackBerry_Backup><Version>3.0</Version><Client platform=\"SachESI\" osversion=\"Microsoft Windows NT 6.1.7601 Service Pack 1\" dtmversion=\"2.0.0.0\"/>"
464 "<SourceDevice pin=\"" + device->pin + "\"><Platform type=\"QNX\" version=\"10.0.0.0\"/></SourceDevice>"
465 "<QnxOSDevice><Archives>";
466 foreach(BackupCategory* cat, _back.categories) {
467 if (_back.modeString().contains(cat->id))
468 manifestXML.append("<Archive id=\"" + cat->id + "\" name=\"" + cat->name + "\" count=\"" + cat->count + "\" bytesize=\"" + cat->bytesize + "\" keyid=\"" + device->bbid + "\" perimetertype=\"" + cat->perimetertype + "\"/>");
469 }
470 manifestXML.append("</Archives></QnxOSDevice></BlackBerry_Backup>");
471 manifest->write(manifestXML.toStdString().c_str());
472 manifest->close();
473 delete manifest;
474
475 QUrlQuery postData;
476 //postData.addQueryItem("action", "backup");
477 if (_back.rev() == 2) {
478 /*QString packageXML = "<Packages>";
479 packageXML += "<Package category=\"app\" pkgid=\"gYABgGhMIKEe6t-zx-otuOtK1JM\" type=\"data\"/>";
480 packageXML += "<Package category=\"app\" pkgid=\"andrBnWwO_pMnqtLJ4heAlnaufQ\" type=\"data\"/>";
481 packageXML += "</Packages>";
482 QNetworkRequest request = setData("backup.cgi?opt=rev2&mode=" + _back.modeString(), "x-www-form-urlencoded");
483 reply = manager->post(request, packageXML.toLatin1());
484
485 //connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(installProgress(qint64,qint64)));
486 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
487 this, SLOT(restoreError(QNetworkReply::NetworkError)));
488 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));*/
489 postData.addQueryItem("mode", _back.modeString());
490 postData.addQueryItem("opt", "rev2");
491 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
492 } else {
493 postData.addQueryItem("mode", _back.modeString());
494 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
495 }
496 }
497 }
498
499 void InstallNet::backup(QUrl url, int options)
500 {
501 if (!url.isLocalFile())
502 return;
503 _backupFileName = url.toLocalFile();
504 if(!_backupFileName.endsWith(".bbb"))
505 _backupFileName.append(".bbb");
506 if (_backupFileName.isEmpty())
507 return;
508 _back.setMode(options);
509 _back.setCurMode(0);
510 backup();
511 }
512
513 void InstallNet::backupQuery() {
514 if (checkLogin())
515 {
516 QUrlQuery postData;
517 //postData.addQueryItem("action", "backup");
518 postData.addQueryItem("query", "list");
519 if (_back.rev() == 2)
520 postData.addQueryItem("opt", "rev2"); // Per-app backups
521 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
522 }
523 }
524
525 void InstallNet::restore()
526 {
527 setRestoring(true);
528 if (checkLogin())
529 {
530 QUrlQuery postData;
531 postData.addQueryItem("action", "restore");
532 postData.addQueryItem("mode", _back.modeString());
533 postData.addQueryItem("totalsize", QString::number(_back.maxSize()));
534 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
535 }
536 }
537
538 void InstallNet::restore(QUrl url, int options)
539 {
540 if (!url.isLocalFile())
541 return;
542 _backupFileName = url.toLocalFile();
543 if (!QFile::exists(_backupFileName))
544 return;
545 currentBackupZip = new QuaZip(_backupFileName);
546 currentBackupZip->open(QuaZip::mdUnzip);
547 if (!currentBackupZip->isOpen()) {
548 QMessageBox::critical(nullptr, "Error", "Could not open backup file.");
549 delete currentBackupZip;
550 currentBackupZip = nullptr;
551 return;
552 }
553 for (int i = 0; i < _back.numMethods(); i++) {
554 if (options & (1 << i)) {
555 // We want to restore this file
556 currentBackupZip->setCurrentFile(QString("Archive/" + _back.stringFromMode(i) + ".tar"));
557 if (!currentBackupZip->hasCurrentFile()) {
558 // But this file doesn't exist?
559 options &= ~(1 << i);
560 } else {
561 // Set the size from this file
562 QuaZipFileInfo info;
563 currentBackupZip->getCurrentFileInfo(&info);
564 _back.setCurMaxSize(i, info.uncompressedSize);
565 qint64 startSize = (_back.maxSize() > 1) ? _back.maxSize() : 0;
566 _back.setMaxSize(startSize + info.uncompressedSize);
567 }
568 }
569 }
570 if (!options)
571 return;
572 _back.setMode(options);
573 _back.setCurMode(0);
574 restore();
575 }
576
577 void InstallNet::wipe() {
578 if (QMessageBox::critical(nullptr, "Loss of data", "Are you sure you want to wipe your device?\nThis will result in a permanent loss of data.", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
579 return;
580 QUrlQuery postData;
581 postData.addQueryItem("wipe", "wipe");
582 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
583 }
584
585 void InstallNet::startRTAS() {
586 QUrlQuery postData;
587 postData.addQueryItem("wipe", "start_rtas");
588 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
589 }
590
591 void InstallNet::newPin(QString pin) {
592 QUrlQuery postData;
593 postData.addQueryItem("wipe", "pin");
594 postData.addQueryItem("newpin", pin.left(8));
595 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
596 }
597
598 void InstallNet::resignNVRAM() {
599 QUrlQuery postData;
600 postData.addQueryItem("wipe", "re_sign");
601 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
602 }
603
604 void InstallNet::factorywipe() {
605 if (QMessageBox::critical(nullptr, "Loss of data", "Are you sure you want to wipe your device?\nThis will result in a permanent loss of data.", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
606 return;
607 QUrlQuery postData;
608 postData.addQueryItem("wipe", "wipe");
609 postData.addQueryItem("factorywipe", "1");
610 postData.addQueryItem("nopoweroff", "1");
611 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
612 }
613
614 void InstallNet::reboot() {
615 QUrlQuery postData;
616 postData.addQueryItem("reset", "true");
617 postQuery("reset.cgi", "x-www-form-urlencoded", postData);
618 }
619
620 void InstallNet::getPIN() {
621 QUrlQuery postData;
622 postData.addQueryItem("wipe", "getpin");
623 postQuery("wipe.cgi", "x-www-form-urlencoded", postData);
624 }
625
626 void InstallNet::dumpLogs() {
627 QUrlQuery postData;
628 postData.addQueryItem("facility", "dumplog");
629 postQuery("support.cgi", "x-www-form-urlencoded", postData);
630 }
631
632 void InstallNet::setActionProperty(QString name, QString value) {
633 QUrlQuery postData;
634 postData.addQueryItem("action", "set");
635 postData.addQueryItem("name", name);
636 postData.addQueryItem("value", value);
637 postQuery("dynamicProperties.cgi", "x-www-form-urlencoded", postData);
638 }
639
640 void InstallNet::login()
641 {
642 if (_loginBlock || _wrongPass)
643 return;
644
645 // How did we get here?
646 if (_state) {
647 checkLogin();
648 return;
649 }
650
651 QStringList ips;
652
653 int flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning | QNetworkInterface::CanBroadcast | QNetworkInterface::CanMulticast;
654 foreach(QNetworkInterface inter, QNetworkInterface::allInterfaces())
655 {
656 if ((inter.flags() & (flags | QNetworkInterface::IsLoopBack)) == flags)
657 {
658 foreach(QNetworkAddressEntry addr, inter.addressEntries())
659 {
660 if (addr.ip().protocol() == QAbstractSocket::IPv4Protocol)
661 {
662 QList<quint8> addrParts;
663 foreach(QString addrString, addr.ip().toString().split('.'))
664 addrParts.append(addrString.toInt());
665
666 if (addrParts.at(0) > 100) {
667 int masked = addrParts.at(3) - 1;
668 if (masked == 0)
669 masked = 128;
670 ips.append(QString("%1.%2.%3.%4").arg(addrParts.at(0)).arg(addrParts.at(1)).arg(addrParts.at(2)).arg(masked));
671 }
672 }
673 }
674 }
675 }
676 ips.removeDuplicates();
677
678 // Keep the user updated with how many potential devices we are dealing with here.
679 setPossibleDevices(ips.count());
680 if (ips.isEmpty())
681 return;
682
683 if (manager == nullptr) {
684 manager = new SslNetworkAccessManager();
685 manager->setProxy(QNetworkProxy::NoProxy);
686 }
687 if (cookieJar == nullptr) {
688 cookieJar = new QNetworkCookieJar(this);
689 manager->setCookieJar(cookieJar);
690 }
691 for(QString ip_addr : ips) {
692 QNetworkRequest request;
693 request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, "QNXWebClient/1.0");
694 request.setAttribute(QNetworkRequest::CustomVerbAttribute, ip_addr);
695 request.setUrl(QUrl("http://"+ip_addr+"/cgi-bin/discovery.cgi"));
696 QNetworkReply* replyTemp = manager->get(request);
697 connect(replyTemp, SIGNAL(error(QNetworkReply::NetworkError)),
698 this, SLOT(restoreError(QNetworkReply::NetworkError)));
699 connect(replyTemp, SIGNAL(finished()), this, SLOT(discoveryReply()));
700 }
701 }
702
703 void InstallNet::discoveryReply() {
704 QNetworkReply* replyTemp = (QNetworkReply*)sender();
705 QNetworkRequest request = replyTemp->request();
706 QString ip_addr = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
707 // Just to prevent fighting between two devices
708 if (_state /*&& ip_addr != _ip*/)
709 return;
710 QByteArray data = replyTemp->readAll();
711 //qDebug() << "Message:\n" << QString(data).simplified().left(3500);
712 QXmlStreamReader xml(data);
713 xml.readNextStartElement(); // RimTabletResponse
714 xml.readNextStartElement();
715 if (xml.name() == "DeviceCharacteristics") {
716 // Valid device
717 setIp(ip_addr);
718 setState(1);
719 if (device != nullptr)
720 device->deleteLater();
721 device = new DeviceInfo(); emit deviceChanged();
722 while (!xml.atEnd())
723 {
724 xml.readNext();
725 if (xml.isStartElement())
726 {
727 if (xml.name() == "BbPin") {
728 device->setPin(QString::number(xml.readElementText().toInt(),16).toUpper());
729 } else if (xml.name() == "SystemMachine") {
730 device->setName(xml.readElementText().replace("_", " "));
731 setNewLine(QString("Connected to %1 at %2.").arg(device->name).arg(_ip));
732 } else if (xml.name() == "OsType") {
733 if (xml.readElementText() == "BlackBerry PlayBook OS") {
734 device->setName("Playbook QNX6.6.0");
735 setNewLine(QString("Connected to Playbook at %1.").arg(_ip));
736 }
737 } else if (xml.name() == "PlatformVersion") {
738 device->setOs(xml.readElementText());
739 } else if (xml.name() == "ModelName") {
740 device->setHw(xml.readElementText());
741 } else if (xml.name() == "MinSupportedProtocolVersion") {
742 // Min comes before max
743 if (xml.readElementText().toInt() == 1)
744 device->setProtocol(1);
745 } else if (xml.name() == "MaxSupportedProtocolVersion") {
746 if (xml.readElementText().toInt() >= 3)
747 device->setProtocol(3);
748 } else if (xml.name() == "DeveloperModeEnabled") {
749 device->setDevMode(xml.readElementText().toUInt());
750 } else if (xml.name() == "OobeCompleted") {
751 device->setSetupComplete(xml.readElementText().toUInt());
752 if (!device->setupComplete) {
753 QMessageBox::information(nullptr, tr("Warning"), tr("You have not completed setup on your device. Due to this issue, it will not allow communication."));
754 }
755 }
756 }
757 }
758 emit deviceChanged();
759 setCompleted(false);
760 // Don't even attempt because it will kick us
761 if (!device->setupComplete)
762 checkLogin();
763 }
764 sender()->deleteLater();
765 }
766
767 bool InstallNet::checkLogin() {
768 if (!_state)
769 return false;
770
771 if (!_completed) {
772 getQuery(QString("login.cgi?request_version=%1").arg(QString::number(device->protocol)), "x-www-form-urlencoded");
773 return false;
774 }
775 return true;
776 }
777
778 void InstallNet::installProgress(qint64 pread, qint64)
779 {
780 if (pread == 0)
781 return;
782 _dlBytes = 50*pread;
783 setCurDGProgress(qMin((int)50, (int)(_dlBytes / _dlTotal)));
784 }
785
786 void InstallNet::backupProgress(qint64 pread, qint64)
787 {
788 _back.setCurSize(100*pread);
789 _back.setProgress(qMin((int)100, (int)(_back.curSize() / _back.curMaxSize())));
790 }
791
792 void InstallNet::restoreProgress(qint64 pwrite, qint64) {
793 _back.setCurSize(100*pwrite);
794 _back.setProgress(qMin((int)100, (int)(_back.curSize() / _back.curMaxSize())));
795 }
796
797 void InstallNet::backupFileFinish()
798 {
799 _zipFile->close();
800 _zipFile->deleteLater();
801 _zipFile = nullptr;
802
803 _back.setCurMode(1);
804
805 QUrlQuery postData;
806 postData.addQueryItem("action", "backup");
807 if (_back.curMode() != "complete") {
808 _back.setProgress(0);
809 postData.addQueryItem("type", _back.curMode());
810 }
811 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
812 }
813
814 QPair<QString,QString> InstallNet::getConnected(int downloadDevice, bool specialQ30) {
815 if (downloadDevice == 0) {
816 if (device != nullptr && device->hw != "" && device->hw != "Unknown") {
817 return qMakePair(_knownConnectedOSType, _knownConnectedRadioType);
818 }
819 return {"", ""};
820 }
821 return getFamilyFromDevice(downloadDevice, specialQ30);
822 }
823
824 void InstallNet::determineDeviceFamily()
825 {
826 QString radio = _knownConnectedRadioType;
827 if (radio == "qc8960.wtr5") {
828 device->setHwFamily(Z30Family);
829 } else if (radio == "m5730") {
830 device->setHwFamily(OMAPFamily);
831 } else if (radio == "qc8960") {
832 device->setHwFamily(Z10Family);
833 } else if (radio == "qc8930.wtr5") {
834 device->setHwFamily(Z3Family);
835 } else if (radio == "qc8960.wtr") {
836 device->setHwFamily(Q10Family);
837 } else if (radio == "qc8974.wtr2") {
838 device->setHwFamily(Q30Family);
839 } else {
840 device->setHwFamily(UnknownFamily);
841 }
842 }
843
844 void InstallNet::restoreReply()
845 {
846 if (reply == nullptr)
847 return;
848
849 QByteArray data = reply->readAll();
850 #if DEBUG_LOG
851 for (int s = 0; s < data.size(); s+=3500) qDebug() << "Message:\n" << QString(data).simplified().mid(s, 3500);
852 #endif
853 if (data.size() == 0) {
854 if (_restoring) {
855 QMessageBox::information(nullptr, "Restore Error", "There was an error loading the backup file.\nThe device encountered an unrecoverable bug.\nIt is not designed to restore this backup.");
856 qIoSafeFree(_zipFile);
857 ioSafeFree(currentBackupZip);
858 setRestoring(false);
859 }
860 }
861 QUrlQuery postData;
862 QString element;
863 QXmlStreamReader xml(data);
864 xml.readNextStartElement(); // RimTabletResponse
865 xml.readNextStartElement();
866 QString hwid;
867 if (xml.name() == "Rev") {
868 xml.readNextStartElement();
869 xml.readNextStartElement();
870 }
871
872 if (xml.name() == "AuthChallenge")
873 { // We need to verify
874 QString salt, challenge;
875 int iCount = 0;
876 while (xml.readNextStartElement()) {
877 element = xml.readElementText();
878 if (xml.name() == "Salt")
879 salt = element;
880 else if (xml.name() == "Challenge")
881 challenge = element;
882 else if (xml.name() == "ICount")
883 iCount = element.toInt();
884 else if (xml.name() == "ErrorDescription")
885 {
886 setLoginBlock(true);
887 return;
888 }
889 }
890 QByteArray saltHex(salt.toLatin1());
891 QByteArray challenger(challenge.toLatin1());
892 QByteArray result = HashPass(challenger, QByteArray::fromHex(saltHex), iCount);
893
894 QNetworkRequest request = reply->request();
895 request.setUrl(QUrl("https://"+ _ip +":443/cgi-bin/login.cgi?challenge_data=" + result.toHex().toUpper() + "&request_version=" + QString::number(device->protocol)));
896
897 reply = manager->get(request);
898 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
899 this, SLOT(restoreError(QNetworkReply::NetworkError)));
900 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
901 }
902 else if (xml.name() == "Auth")
903 { // We are authenticated
904 while (!xml.atEnd())
905 {
906 xml.readNext();
907 if (xml.isStartElement())
908 {
909 QString name = xml.name().toString();
910 if (name == "Error")
911 { //No we aren't!
912 return;
913 }
914 else if (name == "Status")
915 {
916 if (xml.readElementText() == "Denied")
917 {
918 if (!data.contains("Attempts>0")) {
919 setWrongPass(true);
920 setCompleted(false);
921 setState(false);
922 } else {
923 setLoginBlock(true);
924 setCompleted(false);
925 setState(false);
926 }
927 return;
928 }
929 }
930 }
931 }
932 setCompleted(true);
933
934 if (_installing)
935 install();
936 else if (_backing)
937 backup();
938 else if (_restoring)
939 restore();
940 else /*if (_hadPassword)*/
941 scanProps();
942 // This can take up to 40 seconds to respond and all communication on device is Blocking!
943 // backupQuery();
944 }
945 else if (xml.name() == "DynamicProperties")
946 {
947 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
948 if (xml.isStartElement())
949 {
950 QString name = xml.name().toString();
951
952 if (name == "ErrorDescription")
953 {
954 QMessageBox::information(nullptr, "Error", xml.readElementText(), QMessageBox::Ok);
955 } else if (name == "DeviceSoftware") {
956 // About to get the apps
957 _appList.clear();
958 _appRemList.clear();
959 } else if (name == "Application") {
960 Apps* newApp = new Apps();
961 while(!xml.atEnd())
962 {
963 xml.readNext();
964 if (xml.isStartElement()) {
965 if (xml.name() == "Name")
966 {
967 QString longName = xml.readElementText();
968 newApp->setName(longName);
969 if (longName.contains(".test"))
970 longName = longName.split(".test").first();
971 else if (longName.contains(".andrB"))
972 longName = longName.split(".andrB").first();
973 else
974 longName = longName.split(".gY").first();
975
976 QStringList newLineParts = longName.split('.');
977 if (newLineParts.last().isEmpty())
978 newLineParts.removeLast();
979 longName = "";
980 for (int i = 0; i < newLineParts.size() - 1; i++)
981 longName += newLineParts.at(i) + ".";
982 longName += "<b>" + newLineParts.last() + "</b>";
983 newApp->setObjectName(newLineParts.last().toLower());
984 newApp->setFriendlyName(longName);
985 }
986 else if (xml.name() == "Type")
987 newApp->setType(xml.readElementText());
988 else if (xml.name() == "PackageId")
989 newApp->setPackageId(xml.readElementText());
990 else if (xml.name() == "PackageVersionId")
991 newApp->setVersionId(xml.readElementText());
992 else if (xml.name() == "PackageVersion")
993 newApp->setVersion(xml.readElementText());
994 else if (xml.name() == "Fingerprint")
995 newApp->setChecksum(xml.readElementText());
996 } else if (xml.isEndElement() && xml.name() == "Application")
997 break;
998 }
999 if (newApp->type() != "")
1000 _appList.append(newApp);
1001 else
1002 _appRemList.append(newApp);
1003 if (newApp->type() == "os") {
1004 _knownConnectedOSType = newApp->name().split("os.").last().remove(".desktop").replace("verizon", "factory").replace("qc8974.factory_sfi","qc8960.factory_sfi_hybrid_qc8974");
1005 device->setOs(newApp->version());
1006 } else if (newApp->type() == "radio") {
1007 _knownConnectedRadioType = newApp->name().split("radio.").last().remove(".omadm");
1008 device->setRadio(newApp->version());
1009 }
1010 }
1011 // These give the wrong result some times. Installed apps are a better indication.
1012 // Although they also sometimes don't match Settings -> About (eg. from a Core/Radio Autoloader).
1013 // else if (name == "PlatformVersion")
1014 // else if (name == "RadioVersion")
1015 else if (name == "BatteryLevel")
1016 device->setBattery(xml.readElementText().toInt());
1017 else if (name == "HardwareID") {
1018 // If the firmware reports the device as unknown (eg. Dev Alpha on 10.3), show the Hardware ID
1019 if (device->hw == "Unknown") {
1020 hwid = xml.readElementText().remove(0, 2);
1021 // If we already know the name, make it nicer
1022 if (hwid == "8d00270a")
1023 hwid = "Alpha C";
1024 else if (hwid == "4002607")
1025 hwid = "Alpha B";
1026 device->setHw(hwid);
1027 }
1028 } else if (name == "Bbid") {
1029 device->setBbid(xml.readElementText());
1030 }
1031 else if (name == "DeviceName")
1032 {
1033 // name that the user calls their phone
1034 device->setFriendlyName(xml.readElementText());
1035 }
1036 else if (name == "PolicyRestrictions") {
1037 device->setRestrictions(xml.readElementText().simplified());
1038 }
1039 else if (xml.name() == "RefurbDate") {
1040 device->setRefurbDate(xml.readElementText());
1041 } else if (xml.name() == "FreeApplicationSpace") {
1042 device->setFreeSpace(xml.readElementText().toLongLong());
1043 } else if (xml.name() == "BoardSerialNumber") {
1044 device->setBsn(xml.readElementText());
1045 }
1046 }
1047 }
1048 // We do have the radio type but we don't entirely trust it. The user could have installed anything or nothing!
1049 QString temporaryRadioType = _knownConnectedRadioType;
1050 _knownConnectedRadioType = "";
1051 // Not future-proof, but will work for most. Families # hardcoded to 7
1052 for (int i = 1; i < (7 * 2) && _knownConnectedRadioType.isEmpty(); i+=2) {
1053 for (int j = 0; j < dev[i].count(); j++) {
1054 if (dev[i][j] == hwid.toUpper()) {
1055 // Q30 OS status doesn't matter, so we set 0
1056 _knownConnectedRadioType = getFamilyFromDevice(j + 1, 0).second;
1057 break;
1058 }
1059 }
1060 }
1061 // Well, our detection failed, so let's trust the current system.
1062 if (_knownConnectedRadioType.isEmpty()) {
1063 _knownConnectedRadioType = temporaryRadioType;
1064 }
1065 // Now we can work out the real family
1066 determineDeviceFamily();
1067 std::sort(_appList.begin(), _appList.end(),
1068 [=](const Apps* i, const Apps* j) {
1069 if (i->type() != "application" && j->type() == "application")
1070 return true;
1071 if (j->type() != "application" && i->type() == "application")
1072 return false;
1073 return (i->objectName() < j->objectName());
1074 }
1075 );
1076 emit deviceChanged();
1077 emit appListChanged();
1078 }
1079 else if (xml.name() == "RTASChallenge") {
1080 QFile rtasData(getSaveDir() + "rtasdata.txt");
1081 rtasData.open(QIODevice::WriteOnly | QIODevice::Text);
1082 rtasData.write(QByteArray("Use these values for RLT:\n\n"));
1083 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
1084 if (xml.isStartElement())
1085 {
1086 if (xml.name() == "Challenge")
1087 rtasData.write(QString("Challenge: "+xml.readElementText()+"\n").toLocal8Bit());
1088 else if (xml.name() == "ProcessorInfo")
1089 rtasData.write(QString("Processor Info: "+xml.readElementText()+"\n").toLocal8Bit());
1090 else if (xml.name() == "ProcessorId")
1091 rtasData.write(QString("Processor Id: "+xml.readElementText()+"\n").toLocal8Bit());
1092 else if (xml.name() == "BSN")
1093 rtasData.write(QString("BSN: "+xml.readElementText()+"\n").toLocal8Bit());
1094 else if (xml.name() == "IMEI")
1095 rtasData.write(QString("IMEI: "+xml.readElementText()+"\n\n").toLocal8Bit());
1096 else if (xml.name() == "Log")
1097 rtasData.write(QString(xml.readElementText()+"\n").toLocal8Bit());
1098 }
1099 }
1100 setCompleted(false);
1101 setState(false);
1102 QMessageBox::information(nullptr, "Success", "RTAS has been started.\nSachesi will now terminate its connection.", QMessageBox::Ok);
1103 openFile(rtasData.fileName());
1104 rtasData.close();
1105 }
1106 else if (xml.name() == "DevicePIN") {
1107 while (!xml.atEnd())
1108 {
1109 xml.readNext();
1110 if (xml.isStartElement())
1111 {
1112 if (xml.name() == "PIN") {
1113 device->setPin(xml.readElementText().split('X').last());
1114 emit deviceChanged();
1115 }
1116 }
1117 }
1118 }
1119 else if (xml.name() == "Wipe") {
1120 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
1121 if (xml.isStartElement())
1122 {
1123 if (xml.name() == "ErrorDescription") {
1124 QMessageBox::critical(nullptr, "Error", xml.readElementText(), QMessageBox::Ok);
1125 }
1126 }
1127 }
1128 }
1129 else if (xml.name() == "re_pin" || xml.name() == "re_sign" || xml.name() == "start_rtas") {
1130 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
1131 if (xml.isStartElement())
1132 {
1133 if (xml.name() == "Log") {
1134 QMessageBox::critical(nullptr, "Error", xml.readElementText(), QMessageBox::Ok);
1135 }
1136 }
1137 }
1138 }
1139 else if (xml.name() == "DeleteRequest")
1140 {
1141 postData.addQueryItem("type", "bar");
1142 postData.addQueryItem("packageid", _downgradeInfo.at(_downgradePos));
1143 postQuery("update.cgi", "x-www-form-urlencoded", postData);
1144 }
1145 else if (xml.name() == "DeleteProgress")
1146 {
1147 _downgradePos++;
1148 emit dgPosChanged();
1149 postData.addQueryItem("type", "bar");
1150 // Send another packageid if more to delete or update.
1151 if (_downgradePos == _downgradeInfo.count())
1152 postData.addQueryItem("status", "success");
1153 else
1154 postData.addQueryItem("packageid", _downgradeInfo.at(_downgradePos));
1155 postQuery("update.cgi", "x-www-form-urlencoded", postData);
1156 }
1157 else if (xml.name() == "UpdateStart")
1158 {
1159 if (_installInfo.count()) {
1160 compressedFile = new QFile(_downgradeInfo.at(_downgradePos));
1161 compressedFile->open(QIODevice::ReadOnly);
1162 _dlBytes = 0;
1163 _dlTotal = compressedFile->size();
1164
1165 BarInfo info = _installInfo.at(_downgradePos);
1166 if (info.type == OSType)
1167 setCurInstallName(info.version + " Core OS");
1168 else if (info.type == RadioType)
1169 setCurInstallName(info.version + " Radio");
1170 else {
1171 // TODO: Extract naming from bar too, if possible
1172 setCurInstallName(QFileInfo(info.name).completeBaseName());
1173 }
1174
1175 if (info.type == RadioType)
1176 reply = manager->post(setData("update.cgi?type=radio", "octet-stream"), compressedFile);
1177 else
1178 reply = manager->post(setData("update.cgi?type=bar", "octet-stream"), compressedFile);
1179
1180 compressedFile->setParent(reply);
1181 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1182 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1183 connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(installProgress(qint64,qint64)));
1184 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
1185 }
1186 else {
1187 postData.addQueryItem("type", "bar");
1188 postData.addQueryItem("packageid", _downgradeInfo.at(_downgradePos));
1189 reply = manager->post(setData("update.cgi", "x-www-form-urlencoded"), postData.encodedQuery());
1190 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1191 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1192 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
1193 }
1194 }
1195 else if (xml.name() == "UpdateSend")
1196 {
1197 for (xml.readNext(); !xml.atEnd(); xml.readNext()) {
1198 if (xml.isStartElement()) {
1199 if (xml.name() == "Status") {
1200 if (xml.readElementText() == "Error") {
1201 return;
1202 }
1203 } else if (xml.name() == "ErrorDescription") {
1204 QMessageBox::critical(nullptr, "Error", xml.readElementText(), QMessageBox::Ok);
1205 }
1206 }
1207 }
1208 postQuery("update.cgi", "x-www-form-urlencoded", postData);
1209 }
1210 else if (xml.name() == "UpdateProgress")
1211 {
1212 bool inProgress = false;
1213 while (xml.readNextStartElement()) {
1214 element = xml.readElementText();
1215 if (xml.name() == "Status")
1216 {
1217 if (element == "InProgress")
1218 inProgress = true;
1219 else if (element == "Success")
1220 {
1221 inProgress = false;
1222 _dlDoneBytes += 100 * _dlTotal;
1223 compressedFile->close();
1224 if (_downgradePos == _downgradeInfo.count() - 1)
1225 {
1226 postData.addQueryItem("status","success");
1227 reply = manager->post(setData("update.cgi", "x-www-form-urlencoded"), postData.encodedQuery());
1228 }
1229 else
1230 {
1231 _downgradePos++;
1232 emit dgPosChanged();
1233 compressedFile = new QFile(_downgradeInfo.at(_downgradePos));
1234 compressedFile->open(QIODevice::ReadOnly);
1235 _dlBytes = 0;
1236 _dlTotal = compressedFile->size();
1237
1238 BarInfo info = _installInfo.at(_downgradePos);
1239 if (info.type == OSType)
1240 setCurInstallName(info.version + " Core OS");
1241 else if (info.type == RadioType)
1242 setCurInstallName(info.version + " Radio");
1243 else {
1244 setCurInstallName(QFileInfo(info.name).completeBaseName());
1245 }
1246
1247 QNetworkRequest request;
1248 if (info.type == RadioType)
1249 request = setData("update.cgi?type=radio", "octet-stream");
1250 else
1251 request = setData("update.cgi?type=bar", "octet-stream");
1252 request.setHeader(QNetworkRequest::ContentLengthHeader, compressedFile->size());
1253 request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
1254 reply = manager->post(request, compressedFile);
1255 compressedFile->setParent(reply);
1256 connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(installProgress(qint64,qint64)));
1257 }
1258 }
1259 else if (element == "Error")
1260 {
1261 QString errorText = QString(data).split("ErrorDescription>").at(1);
1262 errorText.chop(2);
1263 setNewLine("<br>While sending: " + _downgradeInfo.at(_downgradePos).split("/").last());
1264 setNewLine("&nbsp;&nbsp;Error: " + errorText);
1265 setInstalling(false);
1266 setCurDGProgress(-1);
1267 }
1268 }
1269 else if (xml.name() == "Progress")
1270 {
1271 if (_downgradePos == (_downgradeInfo.count() - 1))
1272 setCurDGProgress(50 + element.toInt()/2);
1273 else
1274 setCurDGProgress(inProgress ? (50 + element.toInt()/2) : 0);
1275
1276 bool resend = false;
1277 if (device->os.startsWith("2.")) // Playbook OS support
1278 resend = !data.contains("100");
1279 else
1280 resend = inProgress;
1281 if (resend) // No 100%!
1282 {
1283 reply = manager->post(setData("update.cgi", "x-www-form-urlencoded"), postData.encodedQuery());
1284 }
1285 }
1286 }
1287 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1288 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1289 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
1290 }
1291 else if (xml.name() == "Backup" || xml.name() == "BackupGet") {
1292 for (xml.readNext(); !xml.atEnd(); xml.readNext())
1293 {
1294 if (xml.isStartElement()) {
1295 if (xml.name() == "Status") {
1296 if (xml.readElementText() == "Error") {
1297 if (_backing) {
1298 setBacking(false);
1299 if (currentBackupZip != nullptr) {
1300 currentBackupZip->close();
1301 delete currentBackupZip;
1302 currentBackupZip = nullptr;
1303 QFile::remove(_backupFileName);
1304 }
1305 } else
1306 _hadPassword = false;
1307 }
1308 } else if (xml.name() == "ErrorDescription") {
1309 QMessageBox::information(nullptr, "Error", xml.readElementText().remove("HTTP_COOKIE="), QMessageBox::Ok);
1310 }
1311 }
1312 }
1313 }
1314 else if (xml.name() == "UpdateEnd") {
1315 setInstalling(false);
1316 setNewLine("Completed Update.");
1317 setCurDGProgress(-1);
1318 }
1319 else if (xml.name() == "BackupCheck")
1320 {
1321 if (_back.curMode() != "complete") {
1322 //postData.addQueryItem("action", "backup");
1323 postData.addQueryItem("type", _back.curMode());
1324 reply = manager->post(setData("backup.cgi", "x-www-form-urlencoded"), postData.encodedQuery());
1325 _zipFile = new QuaZipFile(currentBackupZip);
1326 QuaZipNewInfo newInfo("Archive/" + _back.curMode() + ".tar");
1327 newInfo.setPermissions(QFileDevice::Permission(0x7774));
1328 _zipFile->open(QIODevice::WriteOnly, newInfo);
1329 connect(reply, SIGNAL(downloadProgress(qint64,qint64)),this, SLOT(backupProgress(qint64, qint64)));
1330 connect(reply, &QNetworkReply::readyRead, [=]() {
1331 _zipFile->write(reply->readAll());
1332 });
1333 connect(reply, SIGNAL(finished()), this, SLOT(backupFileFinish()));
1334 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1335 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1336 } else {
1337 postData.addQueryItem("status", "success");
1338 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
1339 currentBackupZip->close();
1340 delete currentBackupZip;
1341 currentBackupZip = nullptr;
1342 setBacking(false);
1343 }
1344 }
1345 else if (xml.name() == "BackupList")
1346 {
1347 _back.clearModes();
1348 while(!xml.atEnd() && !xml.hasError()) {
1349 QXmlStreamReader::TokenType token = xml.readNext();
1350 if(token == QXmlStreamReader::StartElement && xml.attributes().count() > 3) {
1351 if (xml.attributes().at(0).name() == "id")
1352 _back.addMode(xml.attributes());
1353 else if (xml.attributes().at(0).name() == "pkgid")
1354 _back.addApp(xml.attributes());
1355 }
1356 }
1357 _back.sortApps();
1358 }
1359 else if (xml.name() == "BackupStart")
1360 {
1361 if (data.contains("Error")) {
1362 setBacking(false);
1363 setRestoring(false);
1364 return;
1365 }
1366
1367 postData.addQueryItem("query", "activity");
1368 if (_back.rev() == 2)
1369 postData.addQueryItem("opt", "rev2");
1370 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
1371 }
1372 else if (xml.name() == "BackupStartActivity")
1373 {
1374 postData.addQueryItem("type", _back.curMode());
1375
1376 if (_back.rev() == 2) {
1377 postData.addQueryItem("opt", "rev2");
1378
1379 // Select app by pkgid:
1380 //postData.addQueryItem("pkgid", "gYABgGhMIKEe6t-zx-otuOtK1JM");
1381 // Select apps by pkgtype (system, bin, data):
1382 //postData.addQueryItem("pkgtype", "data");
1383 // Perform backup by pkgtype: system, bin, data
1384 if (_back.curMode() == "app") {
1385 QString pkgtype;
1386 if (_back.appMode() & 1)
1387 pkgtype += "system,";
1388 if (_back.appMode() & 2)
1389 pkgtype += "data,";
1390 if (_back.appMode() & 4)
1391 pkgtype += "bin,";
1392 pkgtype.chop(1);
1393
1394 postData.addQueryItem("pkgtype", pkgtype);
1395 }
1396 }
1397
1398 reply = manager->post(setData("backup.cgi", "x-www-form-urlencoded"), postData.encodedQuery());
1399
1400 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1401 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1402
1403 while (!xml.atEnd()) {
1404 xml.readNext();
1405 if (xml.isStartElement()) {
1406 if (xml.name() == "Status" && xml.readElementText() == "InProgress") {
1407 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
1408 }
1409 else if (xml.name() == "TotalSize")
1410 {
1411 _back.setMaxSize(xml.readElementText().toLongLong());
1412 _zipFile = new QuaZipFile(currentBackupZip);
1413 QuaZipNewInfo newInfo("Archive/" + _back.curMode() + ".tar");
1414 newInfo.setPermissions(QFileDevice::Permission(0x7774));
1415 _zipFile->open(QIODevice::WriteOnly, newInfo);
1416 connect(reply, &QNetworkReply::readyRead, [=]() {
1417 _zipFile->write(reply->readAll());
1418 });
1419 connect(reply, SIGNAL(finished()), this, SLOT(backupFileFinish()));
1420 connect(reply, SIGNAL(downloadProgress(qint64,qint64)),this, SLOT(backupProgress(qint64, qint64)));
1421 }
1422 else {
1423 for (int i = 0; i < _back.numMethods(); i++) {
1424 // This is usually App, Media and Settings but make it future-proof
1425 if (xml.name().compare(_back.stringFromMode(i), Qt::CaseInsensitive) == 0) {
1426 _back.setCurMaxSize(i, xml.readElementText().toLongLong());
1427 }
1428 }
1429 }
1430 }
1431 }
1432 }
1433 else if (xml.name() == "RestoreStart")
1434 {
1435 if (data.contains("Error")) {
1436 setBacking(false);
1437 setRestoring(false);
1438 return;
1439 }
1440 restoreSendFile();
1441 }
1442 else if (xml.name() == "RestoreSend")
1443 {
1444 qIoSafeFree(_zipFile);
1445 _back.setCurMode(1);
1446 if (_back.curMode() == "complete") {
1447 postData.addQueryItem("status", "success");
1448 postQuery("backup.cgi", "x-www-form-urlencoded", postData);
1449
1450 setRestoring(false);
1451 currentBackupZip->close();
1452 delete currentBackupZip;
1453 currentBackupZip = nullptr;
1454 } else {
1455 restoreSendFile();
1456 }
1457 }
1458 }
1459
1460 void InstallNet::restoreSendFile() {
1461 currentBackupZip->setCurrentFile(QString("Archive/" + _back.curMode() + ".tar"));
1462 _zipFile = new QuaZipFile(currentBackupZip);
1463 _zipFile->open(QIODevice::ReadOnly);
1464 QNetworkRequest request = setData("backup.cgi?action=restore&type="+_back.curMode()+"&size="+_back.curMaxSize(), "octet-stream");
1465 request.setHeader(QNetworkRequest::ContentLengthHeader, _zipFile->size());
1466 request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
1467 reply = manager->post(request, _zipFile);
1468 _zipFile->setParent(reply);
1469 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
1470 this, SLOT(restoreError(QNetworkReply::NetworkError)));
1471 connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(restoreProgress(qint64, qint64)));
1472 connect(reply, SIGNAL(finished()), this, SLOT(restoreReply()));
1473 }
1474
1475 qint64 InstallNet::changeBackAppMode(QString type) {
1476 return _back.setAppMode(type);
1477 }
1478
1479 void InstallNet::resetVars()
1480 {
1481 qSafeFree(manager);
1482 qSafeFree(reply);
1483 qSafeFree(cookieJar);
1484 setCompleted(false);
1485 setInstalling(false);
1486 setRestoring(false);
1487 setBacking(false);
1488 qIoSafeFree(_zipFile);
1489 ioSafeFree(currentBackupZip);
1490 if (device != nullptr) {
1491 device->deleteLater();
1492 device = nullptr;
1493 emit deviceChanged();
1494 }
1495 setState(0);
1496 setCurDGProgress(-1);
1497 _dlBytes = 0;
1498 _dlTotal = 0;
1499 }
1500
1501 void InstallNet::restoreError(QNetworkReply::NetworkError error)
1502 {
1503 if (error == 5 || error == 99) // On purpose or unreachable
1504 return;
1505
1506 // This is only if it's a discovery pong. Otherwise it will be empty string.
1507 QNetworkRequest request = ((QNetworkReply*)sender())->request();
1508 QString ip_addr = request.attribute(QNetworkRequest::CustomVerbAttribute).toString();
1509 // If it's a discovery pong, the IP will be 169.x.x.x (at least 9 chars)
1510 QString this_ip = (ip_addr.length()) >= 9 ? ip_addr : _ip;
1511
1512 if (_state && this_ip == _ip) {
1513 resetVars();
1514 } else if (_state) {
1515 return;
1516 }
1517 QString errString = QString("Communication Error: %1 (%2) from %3")
1518 .arg(error)
1519 .arg( ((QNetworkReply*)sender())->errorString() )
1520 .arg(this_ip);
1521 setNewLine(errString);
1522 qDebug() << errString;
1523 }
1524
1525 void InstallNet::logadd(QString logtxt)
1526 {
1527 Q_UNUSED(logtxt);
1528 return;
1529 }
1530
1531 QByteArray InstallNet::HashPass(QByteArray challenge, QByteArray salt, int iterations)
1532 {
1533 /* Create Hashed Password */
1534 QByteArray hashedData = QByteArray(_password.toLatin1());
1535 int count = 0;
1536 bool challenger = true;
1537 do {
1538 QByteArray buf(4 + salt.length() + hashedData.length(),0);
1539 QDataStream buffer(&buf,QIODevice::WriteOnly);
1540 buffer.setByteOrder(QDataStream::LittleEndian);
1541 buffer << qint32(count);
1542 buffer.writeRawData(salt, salt.length());
1543 buffer.writeRawData(hashedData, hashedData.length());
1544 if (!count) hashedData.resize(64);
1545 SHA512((const unsigned char*)buf.data(), buf.length(), (unsigned char *)hashedData.data());
1546 if ((count == iterations - 1) && challenger)
1547 {
1548 count = -1;
1549 challenger = false;
1550 hashedData.prepend(challenge);
1551 }
1552 } while (++count < iterations);
1553 return hashedData;
1554 }
1555
1556 void InstallNet::disconnected()
1557 {
1558 setState(0);
1559 setCompleted(false);
1560 setRestoring(false);
1561 setBacking(false);
1562 setInstalling(false);
1563 }
1564
1565 void InstallNet::connected()
1566 {
1567 requestConfigure();
1568 }
1569
1570 QString InstallNet::appDeltaMsg()
1571 {
1572 if (_appList.count() == 0)
1573 return "";
1574 QString delta = "<currentSoftware>";
1575 for (int i = 0; i < _appList.count(); i++) {
1576 delta.append("<package id=\"" + _appList.at(i)->packageId() + "\" name=\"" + _appList.at(i)->name() + "\" type=\"" + _appList.at(i)->type() + "\"><version id=\"" + _appList.at(i)->versionId() + "\">" + _appList.at(i)->version() + "</version><checkSum type=\"SHA512\">" + _appList.at(i)->checksum() + "</checkSum></package>");
1577 }
1578 delta.append("</currentSoftware>");
1579 return delta;
1580 }
1581
1582 void InstallNet::exportInstalled()
1583 {
1584 QFile installedTxt(getSaveDir() + "/installed.txt");
1585 installedTxt.open(QIODevice::WriteOnly | QIODevice::Text);
1586 installedTxt.write("Installed Applications:\n");
1587 for (int i = 0; i < _appList.count(); i++) {
1588 if (_appList.at(i)->type() != "") {
1589 QString appLine = _appList.at(i)->friendlyName().remove("<b>").remove("</b>").leftJustified(55);
1590 appLine.append(_appList.at(i)->version() + "\n");
1591 installedTxt.write(appLine.toStdString().c_str());
1592 }
1593 }
1594 if (_appRemList.count()) {
1595 installedTxt.write("\n\nRemoved Applications:\n");
1596 for (int i = 0; i < _appRemList.count(); i++) {
1597 QString appLine = _appRemList.at(i)->friendlyName().remove("<b>").remove("</b>").leftJustified(55);
1598 appLine.append(_appRemList.at(i)->version() + "\n");
1599 installedTxt.write(appLine.toStdString().c_str());
1600 }
1601 }
1602 openFile(installedTxt.fileName());
1603 installedTxt.close();
1604 }
1605
1606 //Network Manager
1607 QNetworkReply* SslNetworkAccessManager::createRequest(Operation op, const QNetworkRequest& req, QIODevice* outgoingData)
1608 {
1609 QNetworkReply* reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
1610 reply->ignoreSslErrors();
1611 return reply;
1612 }