1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
22 #include <MUtils/Global.h>
23 #include <MUtils/UpdateChecker.h>
24 #include <MUtils/OSSupport.h>
25 #include <MUtils/Exception.h>
27 #include <QStringList>
35 #include <QElapsedTimer>
41 ///////////////////////////////////////////////////////////////////////////////
43 ///////////////////////////////////////////////////////////////////////////////
45 static const char *header_id = "!Update";
47 static const char *mirror_url_postfix[] =
54 static const int MIN_CONNSCORE = 5;
55 static const int QUICK_MIRRORS = 3;
56 static const int MAX_CONN_TIMEOUT = 16000;
57 static const int DOWNLOAD_TIMEOUT = 30000;
59 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
60 static char *USER_AGENT_STR = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"; /*use something innocuous*/
62 #define CHECK_CANCELLED() do \
64 if(MUTILS_BOOLIFY(m_cancelled)) \
66 m_success.fetchAndStoreOrdered(0); \
67 log("", "Update check has been cancelled by user!"); \
68 setProgress(m_maxProgress); \
69 setStatus(UpdateStatus_CancelledByUser); \
75 ////////////////////////////////////////////////////////////
77 ////////////////////////////////////////////////////////////
79 static int getMaxProgress(void)
82 while (update_mirrors[counter])
86 counter += MIN_CONNSCORE + QUICK_MIRRORS + 2;
90 static QStringList buildRandomList(const char *const values[])
93 for (int index = 0; values[index]; index++)
95 const int pos = MUtils::next_rand_u32() % (index + 1);
96 list.insert(pos, QString::fromLatin1(values[index]));
101 static const QHash<QString, QString> *initEnvVars(void)
103 QHash<QString, QString> *const environment = new QHash<QString, QString>();
104 environment->insert(QLatin1String("CURL_HOME"), QDir::toNativeSeparators(MUtils::temp_folder()));
108 ////////////////////////////////////////////////////////////
110 ////////////////////////////////////////////////////////////
112 MUtils::UpdateCheckerInfo::UpdateCheckerInfo(void)
117 void MUtils::UpdateCheckerInfo::resetInfo(void)
120 m_buildDate.setDate(1900, 1, 1);
121 m_downloadSite.clear();
122 m_downloadAddress.clear();
123 m_downloadFilename.clear();
124 m_downloadFilecode.clear();
125 m_downloadChecksum.clear();
128 bool MUtils::UpdateCheckerInfo::isComplete(void)
130 if(this->m_buildNo < 1) return false;
131 if(this->m_buildDate.year() < 2010) return false;
132 if(this->m_downloadSite.isEmpty()) return false;
133 if(this->m_downloadAddress.isEmpty()) return false;
134 if(this->m_downloadFilename.isEmpty()) return false;
135 if(this->m_downloadFilecode.isEmpty()) return false;
136 if(this->m_downloadChecksum.isEmpty()) return false;
141 ////////////////////////////////////////////////////////////
142 // Constructor & Destructor
143 ////////////////////////////////////////////////////////////
145 MUtils::UpdateChecker::UpdateChecker(const QString &binCurl, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
147 m_updateInfo(new UpdateCheckerInfo()),
148 m_binaryCurl(binCurl),
149 m_binaryGnuPG(binGnuPG),
150 m_binaryKeys(binKeys),
151 m_applicationId(applicationId),
152 m_installedBuildNo(installedBuildNo),
153 m_betaUpdates(betaUpdates),
154 m_testMode(testMode),
155 m_maxProgress(getMaxProgress()),
156 m_environment(initEnvVars())
158 m_status = UpdateStatus_NotStartedYet;
161 if(m_binaryCurl.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
163 MUTILS_THROW("Tools not initialized correctly!");
167 MUtils::UpdateChecker::~UpdateChecker(void)
171 ////////////////////////////////////////////////////////////
173 ////////////////////////////////////////////////////////////
175 void MUtils::UpdateChecker::start(Priority priority)
177 m_success.fetchAndStoreOrdered(0);
178 m_cancelled.fetchAndStoreOrdered(0);
179 QThread::start(priority);
182 ////////////////////////////////////////////////////////////
183 // Protected functions
184 ////////////////////////////////////////////////////////////
186 void MUtils::UpdateChecker::run(void)
188 qDebug("Update checker thread started!");
189 MUTILS_EXCEPTION_HANDLER(m_testMode ? testMirrorsList() : checkForUpdates());
190 qDebug("Update checker thread completed.");
193 void MUtils::UpdateChecker::checkForUpdates(void)
195 // ----- Initialization ----- //
197 m_updateInfo->resetInfo();
200 // ----- Test Internet Connection ----- //
202 log("Checking your Internet connection...", "");
203 setStatus(UpdateStatus_CheckingConnection);
205 const int networkStatus = OS::network_status();
206 if(networkStatus == OS::NETWORK_TYPE_NON)
208 log("Operating system reports that the computer is currently offline !!!");
209 setProgress(m_maxProgress);
210 setStatus(UpdateStatus_ErrorNoConnection);
217 // ----- Test Known Hosts Connectivity ----- //
219 int connectionScore = 0;
220 QStringList mirrorList = buildRandomList(known_hosts);
222 for(int connectionTimout = 1000; connectionTimout <= MAX_CONN_TIMEOUT; connectionTimout *= 2)
224 QElapsedTimer elapsedTimer;
225 elapsedTimer.start();
226 const int globalTimout = 2 * MIN_CONNSCORE * connectionTimout;
227 while (!elapsedTimer.hasExpired(globalTimout))
229 const QString hostName = mirrorList.takeFirst();
230 if (tryContactHost(hostName, connectionTimout))
232 connectionScore += 1;
233 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
234 elapsedTimer.restart();
235 if (connectionScore >= MIN_CONNSCORE)
237 goto endLoop; /*success*/
242 mirrorList.append(hostName); /*re-schedule*/
250 if(connectionScore < MIN_CONNSCORE)
252 log("", "Connectivity test has failed: Internet connection appears to be broken!");
253 setProgress(m_maxProgress);
254 setStatus(UpdateStatus_ErrorConnectionTestFailed);
258 // ----- Fetch Update Info From Server ----- //
260 log("----", "", "Internet connection is operational, checking for updates online...");
261 setStatus(UpdateStatus_FetchingUpdates);
264 mirrorList = buildRandomList(update_mirrors);
266 while(!mirrorList.isEmpty())
268 setProgress(m_progress + 1);
269 const QString currentMirror = mirrorList.takeFirst();
270 const bool isQuick = (mirrorCount++ < QUICK_MIRRORS);
271 if(tryUpdateMirror(m_updateInfo.data(), currentMirror, isQuick))
273 m_success.ref(); /*success*/
278 mirrorList.append(currentMirror); /*re-schedule*/
284 while (m_progress < m_maxProgress)
287 setProgress(m_progress + 1);
291 // ----- Generate final result ----- //
293 if(MUTILS_BOOLIFY(m_success))
295 if(m_updateInfo->m_buildNo > m_installedBuildNo)
297 setStatus(UpdateStatus_CompletedUpdateAvailable);
299 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
301 setStatus(UpdateStatus_CompletedNoUpdates);
305 setStatus(UpdateStatus_CompletedNewVersionOlder);
310 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
314 void MUtils::UpdateChecker::testMirrorsList(void)
316 // ----- Test update mirrors ----- //
318 QStringList mirrorList;
319 for(int i = 0; update_mirrors[i]; i++)
321 mirrorList << QString::fromLatin1(update_mirrors[i]);
324 qDebug("\n[Mirror Sites]");
325 log("Testing all known mirror sites...", "", "---");
327 UpdateCheckerInfo updateInfo;
328 while (!mirrorList.isEmpty())
330 const QString currentMirror = mirrorList.takeFirst();
331 bool success = false;
332 qDebug("Testing: %s", MUTILS_L1STR(currentMirror));
333 log("", "Testing:", currentMirror, "");
334 for (quint8 attempt = 0; attempt < 3; ++attempt)
336 updateInfo.resetInfo();
337 if (tryUpdateMirror(&updateInfo, currentMirror, (!attempt)))
345 qWarning("\nUpdate mirror seems to be unavailable:\n%s\n", MUTILS_L1STR(currentMirror));
350 // ----- Test known hosts ----- //
352 QStringList knownHostList;
353 for (int i = 0; known_hosts[i]; i++)
355 knownHostList << QString::fromLatin1(known_hosts[i]);
358 qDebug("\n[Known Hosts]");
359 log("Testing all known hosts...", "", "---");
361 while(!knownHostList.isEmpty())
363 const QString currentHost = knownHostList.takeFirst();
364 qDebug("Testing: %s", MUTILS_L1STR(currentHost));
365 log(QLatin1String(""), "Testing:", currentHost, "");
366 if (!tryContactHost(currentHost, DOWNLOAD_TIMEOUT))
368 qWarning("\nConnectivity test FAILED on the following host:\n%s\n", MUTILS_L1STR(currentHost));
374 ////////////////////////////////////////////////////////////
376 ////////////////////////////////////////////////////////////
378 void MUtils::UpdateChecker::setStatus(const int status)
380 if(m_status != status)
383 emit statusChanged(status);
387 void MUtils::UpdateChecker::setProgress(const int progress)
389 if(m_progress != progress)
391 m_progress = progress;
392 emit progressChanged(progress);
396 void MUtils::UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
398 if(!str1.isNull()) emit messageLogged(str1);
399 if(!str2.isNull()) emit messageLogged(str2);
400 if(!str3.isNull()) emit messageLogged(str3);
401 if(!str4.isNull()) emit messageLogged(str4);
404 bool MUtils::UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url, const bool &quick)
406 bool success = false;
407 log("", "Trying mirror:", url, "");
411 if (!tryContactHost(QUrl(url).host(), (MAX_CONN_TIMEOUT / 8)))
413 log("", "Mirror is too slow, skipping!");
418 const QString randPart = next_rand_str();
419 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
420 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
422 if (getUpdateInfo(url, outFileVers, outFileSign))
424 log("Download completed, verifying signature:", "");
425 if (checkSignature(outFileVers, outFileSign))
427 log("", "Signature is valid, parsing info:", "");
428 success = parseVersionInfo(outFileVers, updateInfo);
432 log("", "Bad signature, take care !!!");
437 log("", "Download has failed!");
440 QFile::remove(outFileVers);
441 QFile::remove(outFileSign);
446 bool MUtils::UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
448 log("Downloading update info:", "");
449 if(getFile(QUrl(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileVers))
453 log( "Downloading signature file:", "");
454 if (getFile(QUrl(QString("%1%2.sig2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileSign))
463 bool MUtils::UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
465 QRegExp value("^(\\w+)=(.+)$");
466 QRegExp section("^\\[(.+)\\]$");
468 QDate updateInfoDate;
469 updateInfo->resetInfo();
472 if(!data.open(QIODevice::ReadOnly))
474 qWarning("Cannot open update info file for reading!");
483 QString line = QString::fromLatin1(data.readLine()).trimmed();
484 if(section.indexIn(line) >= 0)
486 log(QString("Sec: [%1]").arg(section.cap(1)));
487 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
488 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
491 if(inSec && (value.indexIn(line) >= 0))
493 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
494 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
497 const unsigned int temp = value.cap(2).toUInt(&ok);
498 if(ok) updateInfo->m_buildNo = temp;
500 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
502 const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
503 if(temp.isValid()) updateInfo->m_buildDate = temp;
505 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
507 updateInfo->m_downloadSite = value.cap(2).trimmed();
509 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
511 updateInfo->m_downloadAddress = value.cap(2).trimmed();
513 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
515 updateInfo->m_downloadFilename = value.cap(2).trimmed();
517 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
519 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
521 else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
523 updateInfo->m_downloadChecksum = value.cap(2).trimmed();
526 if(inHdr && (value.indexIn(line) >= 0))
528 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
529 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
531 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
532 if(temp.isValid()) updateInfoDate = temp;
537 if(!updateInfoDate.isValid())
539 updateInfo->resetInfo();
540 log("WARNING: Version info timestamp is missing!");
544 const QDate currentDate = OS::current_date();
545 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
547 updateInfo->resetInfo();
548 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
551 else if(currentDate < updateInfoDate)
553 log("Version info is from the future, take care!");
554 qWarning("Version info is from the future, take care!");
557 if(!updateInfo->isComplete())
559 log("WARNING: Version info is incomplete!");
566 //----------------------------------------------------------
568 //----------------------------------------------------------
570 bool MUtils::UpdateChecker::getFile(const QUrl &url, const QString &outFile, const unsigned int maxRedir)
572 QFileInfo output(outFile);
573 output.setCaching(false);
577 QFile::remove(output.canonicalFilePath());
580 qWarning("Existing output file could not be found!");
585 QStringList args(QLatin1String("-vsSNqkfL"));
586 args << "-m" << QString::number(DOWNLOAD_TIMEOUT / 1000);
587 args << "--max-redirs" << QString::number(maxRedir);
588 args << "-A" << USER_AGENT_STR;
589 args << "-e" << QString("%1://%2/;auto").arg(url.scheme(), url.host());
590 args << "-o" << output.fileName() << url.toString();
592 return invokeCurl(args, output.absolutePath(), DOWNLOAD_TIMEOUT);
595 bool MUtils::UpdateChecker::tryContactHost(const QString &hostname, const int &timeoutMsec)
597 log(QString("Connecting to host: %1").arg(hostname), "");
599 QStringList args(QLatin1String("-vsSNqkI"));
600 args << "-m" << QString::number(qMax(1, timeoutMsec / 1000));
601 args << "-A" << USER_AGENT_STR;
602 args << "-o" << OS::null_device() << QString("http://%1/").arg(hostname);
604 return invokeCurl(args, temp_folder(), timeoutMsec);
607 bool MUtils::UpdateChecker::invokeCurl(const QStringList &args, const QString &workingDir, const int timeout)
610 init_process(process, workingDir, true, NULL, m_environment.data());
613 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
614 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
615 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
618 timer.setSingleShot(true);
619 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
621 process.start(m_binaryCurl, args);
622 if (!process.waitForStarted())
627 bool bAborted = false;
628 timer.start(qMax(2 * timeout, 2500));
630 while (process.state() != QProcess::NotRunning)
633 while (process.canReadLine())
635 const QString line = QString::fromLatin1(process.readLine()).simplified();
636 if ((!line.isEmpty()) && line.compare(QLatin1String("<")) && line.compare(QLatin1String(">")))
641 const bool bCancelled = MUTILS_BOOLIFY(m_cancelled);
642 if (bAborted = (bCancelled || ((!timer.isActive()) && (!process.waitForFinished(15)))))
644 log(bCancelled ? "CANCELLED BY USER !!!" : "PROCESS TIMEOUT !!!", "");
645 qWarning("WARNING: cURL process %s!", bCancelled ? "cancelled" : "timed out");
646 break; /*abort process*/
651 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
656 process.waitForFinished(-1);
660 const int exitCode = process.exitCode();
663 case 0: log(QLatin1String("DONE: Transfer completed successfully."), ""); break;
664 case 6: log(QLatin1String("ERROR: Remote host could not be resolved!"), ""); break;
665 case 7: log(QLatin1String("ERROR: Connection to remote host could not be established!"), ""); break;
666 case 22: log(QLatin1String("ERROR: Requested URL was not found or returned an error!"), ""); break;
667 case 28: log(QLatin1String("ERROR: Operation timed out !!!"), ""); break;
668 default: log(QString().sprintf("ERROR: Terminated with unknown code %d", exitCode), ""); break;
671 return (exitCode == 0);
674 bool MUtils::UpdateChecker::checkSignature(const QString &file, const QString &signature)
676 if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
678 qWarning("CheckSignature: File and signature should be in same folder!");
682 QString keyRingPath(m_binaryKeys);
683 bool removeKeyring = false;
684 if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
686 keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
687 removeKeyring = true;
688 if (!QFile::copy(m_binaryKeys, keyRingPath))
690 qWarning("CheckSignature: Failed to copy the key-ring file!");
696 init_process(process, QFileInfo(file).absolutePath());
699 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
700 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
701 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
703 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(keyRingPath).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
705 if (!process.waitForStarted())
709 remove_file(keyRingPath);
714 while (process.state() == QProcess::Running)
717 while (process.canReadLine())
719 const QString line = QString::fromLatin1(process.readLine()).simplified();
729 remove_file(keyRingPath);
732 log(QString().sprintf("Exited with code %d", process.exitCode()));
733 return (process.exitCode() == 0);
736 ////////////////////////////////////////////////////////////
738 ////////////////////////////////////////////////////////////
742 ////////////////////////////////////////////////////////////
744 ////////////////////////////////////////////////////////////