1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2017 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>
34 #include <QElapsedTimer>
36 using namespace MUtils;
38 ///////////////////////////////////////////////////////////////////////////////
40 ///////////////////////////////////////////////////////////////////////////////
42 static const char *header_id = "!Update";
44 static const char *mirror_url_postfix[] =
51 static const char *update_mirrors[] =
53 "http://muldersoft.com/",
54 "http://mulder.bplaced.net/",
55 "http://mulder.6te.net/",
56 "http://mulder.webuda.com/",
57 "http://mulder.pe.hu/",
58 "http://muldersoft.square7.ch/",
59 "http://muldersoft.co.nf/",
60 "http://muldersoft.eu.pn/",
61 "http://muldersoft.lima-city.de/",
62 "http://www.muldersoft.keepfree.de/",
63 "http://lamexp.sourceforge.net/",
64 "http://lordmulder.github.io/LameXP/",
65 "http://muldersoft.bitbucket.io/", //http://lord_mulder.bitbucket.org/
66 "http://www.tricksoft.de/",
67 "http://repo.or.cz/LameXP.git/blob_plain/gh-pages:/",
68 "http://gitlab.com/lamexp/lamexp/raw/gh-pages/",
72 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
77 "clbianco.altervista.org",
78 "status.aws.amazon.com",
86 "web.audacityteam.org",
87 "status.automattic.com",
95 "www.bingeandgrab.com",
96 "www.bucketheadpikes.com",
97 "www.buckethead-coop.com",
102 "www.citizeninsomniac.com",
107 "www.codeproject.com",
108 "www.der-postillon.com",
130 "www.huffingtonpost.co.uk",
138 "www.jiscdigitalmedia.ac.uk",
139 "kannmanumdieuhrzeitschonnbierchentrinken.de",
140 "mirrors.kernel.org",
142 "lame.sourceforge.net",
147 "www.livejournal.com",
153 "www.mod-technologies.com",
158 "wiki.multimedia.cx",
161 "mirror.netcologne.de",
172 "www.portablefreeware.com",
173 "support.proboards.com",
178 "www.rwth-aachen.de",
179 "www.seamonkey-project.org",
186 "www.sputnikmusic.com",
191 "tdm-gcc.tdragon.net",
199 "blog.virustotal.com",
200 "www.vkgoeswild.com",
203 "status.wikimedia.org",
213 "ffmpeg.zeranoe.com",
217 static const int MIN_CONNSCORE = 5;
218 static const int QUICK_MIRRORS = 3;
219 static const int MAX_CONN_TIMEOUT = 8000;
220 static const int DOWNLOAD_TIMEOUT = 30000;
222 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
223 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0"; /*use something innocuous*/
225 #define CHECK_CANCELLED() do \
227 if(MUTILS_BOOLIFY(m_cancelled)) \
229 m_success.fetchAndStoreOrdered(0); \
230 log("", "Update check has been cancelled by user!"); \
231 setProgress(m_maxProgress); \
232 setStatus(UpdateStatus_CancelledByUser); \
238 ////////////////////////////////////////////////////////////
240 ////////////////////////////////////////////////////////////
242 static int getMaxProgress(void)
245 while (update_mirrors[counter])
249 counter += MIN_CONNSCORE + QUICK_MIRRORS + 2;
253 static QStringList buildRandomList(const char *const values[])
256 for (int index = 0; values[index]; index++)
258 const int pos = next_rand_u32() % (index + 1);
259 list.insert(pos, QString::fromLatin1(values[index]));
264 ////////////////////////////////////////////////////////////
266 ////////////////////////////////////////////////////////////
268 UpdateCheckerInfo::UpdateCheckerInfo(void)
273 void UpdateCheckerInfo::resetInfo(void)
276 m_buildDate.setDate(1900, 1, 1);
277 m_downloadSite.clear();
278 m_downloadAddress.clear();
279 m_downloadFilename.clear();
280 m_downloadFilecode.clear();
281 m_downloadChecksum.clear();
284 bool UpdateCheckerInfo::isComplete(void)
286 if(this->m_buildNo < 1) return false;
287 if(this->m_buildDate.year() < 2010) return false;
288 if(this->m_downloadSite.isEmpty()) return false;
289 if(this->m_downloadAddress.isEmpty()) return false;
290 if(this->m_downloadFilename.isEmpty()) return false;
291 if(this->m_downloadFilecode.isEmpty()) return false;
292 if(this->m_downloadChecksum.isEmpty()) return false;
297 ////////////////////////////////////////////////////////////
298 // Constructor & Destructor
299 ////////////////////////////////////////////////////////////
301 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binMCat, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
303 m_updateInfo(new UpdateCheckerInfo()),
304 m_binaryWGet(binWGet),
305 m_binaryMCat(binMCat),
306 m_binaryGnuPG(binGnuPG),
307 m_binaryKeys(binKeys),
308 m_applicationId(applicationId),
309 m_installedBuildNo(installedBuildNo),
310 m_betaUpdates(betaUpdates),
311 m_testMode(testMode),
312 m_maxProgress(getMaxProgress())
314 m_status = UpdateStatus_NotStartedYet;
317 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
319 MUTILS_THROW("Tools not initialized correctly!");
323 UpdateChecker::~UpdateChecker(void)
327 ////////////////////////////////////////////////////////////
329 ////////////////////////////////////////////////////////////
331 void UpdateChecker::start(Priority priority)
333 m_success.fetchAndStoreOrdered(0);
334 m_cancelled.fetchAndStoreOrdered(0);
335 QThread::start(priority);
338 ////////////////////////////////////////////////////////////
339 // Protected functions
340 ////////////////////////////////////////////////////////////
342 void UpdateChecker::run(void)
344 qDebug("Update checker thread started!");
345 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
346 qDebug("Update checker thread completed.");
349 void UpdateChecker::checkForUpdates(void)
351 // ----- Initialization ----- //
353 m_updateInfo->resetInfo();
356 // ----- Test Internet Connection ----- //
358 log("Checking internet connection...", "");
359 setStatus(UpdateStatus_CheckingConnection);
361 const int networkStatus = OS::network_status();
362 if(networkStatus == OS::NETWORK_TYPE_NON)
364 log("Operating system reports that the computer is currently offline !!!");
365 setProgress(m_maxProgress);
366 setStatus(UpdateStatus_ErrorNoConnection);
372 // ----- Test Known Hosts Connectivity ----- //
374 int connectionScore = 0;
375 QStringList mirrorList = buildRandomList(known_hosts);
377 for(int connectionTimout = 250; connectionTimout <= MAX_CONN_TIMEOUT; connectionTimout *= 2)
379 QElapsedTimer elapsedTimer;
380 elapsedTimer.start();
381 const int globalTimout = 2 * MIN_CONNSCORE * connectionTimout;
382 while (!elapsedTimer.hasExpired(globalTimout))
384 const QString hostName = mirrorList.takeFirst();
385 if (tryContactHost(hostName, connectionTimout))
387 connectionScore += 1;
388 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
389 elapsedTimer.restart();
390 if (connectionScore >= MIN_CONNSCORE)
392 goto endLoop; /*success*/
397 mirrorList.append(hostName); /*re-schedule*/
405 if(connectionScore < MIN_CONNSCORE)
407 log("", "Connectivity test has failed: Internet connection appears to be broken!");
408 setProgress(m_maxProgress);
409 setStatus(UpdateStatus_ErrorConnectionTestFailed);
413 // ----- Fetch Update Info From Server ----- //
415 log("----", "", "Checking for updates online...");
416 setStatus(UpdateStatus_FetchingUpdates);
419 mirrorList = buildRandomList(update_mirrors);
421 while(!mirrorList.isEmpty())
423 setProgress(m_progress + 1);
424 const QString currentMirror = mirrorList.takeFirst();
425 const bool isQuick = (mirrorCount++ < QUICK_MIRRORS);
426 if(tryUpdateMirror(m_updateInfo.data(), currentMirror, isQuick))
428 m_success.ref(); /*success*/
433 mirrorList.append(currentMirror); /*re-schedule*/
439 while (m_progress < m_maxProgress)
442 setProgress(m_progress + 1);
446 // ----- Generate final result ----- //
448 if(MUTILS_BOOLIFY(m_success))
450 if(m_updateInfo->m_buildNo > m_installedBuildNo)
452 setStatus(UpdateStatus_CompletedUpdateAvailable);
454 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
456 setStatus(UpdateStatus_CompletedNoUpdates);
460 setStatus(UpdateStatus_CompletedNewVersionOlder);
465 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
469 void UpdateChecker::testKnownHosts(void)
471 QStringList hostList;
472 for(int i = 0; known_hosts[i]; i++)
474 hostList << QString::fromLatin1(known_hosts[i]);
477 qDebug("\n[Known Hosts]");
478 log("Testing all known hosts...", "", "---");
480 int hostCount = hostList.count();
481 while(!hostList.isEmpty())
483 QString currentHost = hostList.takeFirst();
484 qDebug("Testing: %s", currentHost.toLatin1().constData());
485 log("", "Testing:", currentHost, "");
486 if (!tryContactHost(currentHost, DOWNLOAD_TIMEOUT))
488 qWarning("\nConnectivity test FAILED on the following host:\n%s\n", currentHost.toLatin1().constData());
494 ////////////////////////////////////////////////////////////
496 ////////////////////////////////////////////////////////////
498 void UpdateChecker::setStatus(const int status)
500 if(m_status != status)
503 emit statusChanged(status);
507 void UpdateChecker::setProgress(const int progress)
509 if(m_progress != progress)
511 m_progress = progress;
512 emit progressChanged(progress);
516 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
518 if(!str1.isNull()) emit messageLogged(str1);
519 if(!str2.isNull()) emit messageLogged(str2);
520 if(!str3.isNull()) emit messageLogged(str3);
521 if(!str4.isNull()) emit messageLogged(str4);
524 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url, const bool &quick)
526 bool success = false;
527 log("", "Trying mirror:", url, "");
529 if (!tryContactHost(QUrl(url).host(), quick ? (MAX_CONN_TIMEOUT / 10) : MAX_CONN_TIMEOUT))
531 log("", quick ? "Mirror is too slow!" :"Mirror is unreachable!");
535 const QString randPart = next_rand_str();
536 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
537 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
539 if (getUpdateInfo(url, outFileVers, outFileSign))
541 log("", "Download okay, checking signature:");
542 if (checkSignature(outFileVers, outFileSign))
544 log("", "Signature okay, parsing info:", "");
545 success = parseVersionInfo(outFileVers, updateInfo);
549 log("", "Bad signature, take care!");
554 log("", "Download has failed!");
557 QFile::remove(outFileVers);
558 QFile::remove(outFileSign);
563 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
565 log("Downloading update info:", "");
566 if(getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
570 log("", "Downloading signature:", "");
571 if (getFile(QString("%1%2.sig2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
580 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
582 QRegExp value("^(\\w+)=(.+)$");
583 QRegExp section("^\\[(.+)\\]$");
585 QDate updateInfoDate;
586 updateInfo->resetInfo();
589 if(!data.open(QIODevice::ReadOnly))
591 qWarning("Cannot open update info file for reading!");
600 QString line = QString::fromLatin1(data.readLine()).trimmed();
601 if(section.indexIn(line) >= 0)
603 log(QString("Sec: [%1]").arg(section.cap(1)));
604 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
605 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
608 if(inSec && (value.indexIn(line) >= 0))
610 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
611 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
614 const unsigned int temp = value.cap(2).toUInt(&ok);
615 if(ok) updateInfo->m_buildNo = temp;
617 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
619 const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
620 if(temp.isValid()) updateInfo->m_buildDate = temp;
622 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
624 updateInfo->m_downloadSite = value.cap(2).trimmed();
626 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
628 updateInfo->m_downloadAddress = value.cap(2).trimmed();
630 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
632 updateInfo->m_downloadFilename = value.cap(2).trimmed();
634 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
636 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
638 else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
640 updateInfo->m_downloadChecksum = value.cap(2).trimmed();
643 if(inHdr && (value.indexIn(line) >= 0))
645 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
646 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
648 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
649 if(temp.isValid()) updateInfoDate = temp;
654 if(!updateInfoDate.isValid())
656 updateInfo->resetInfo();
657 log("WARNING: Version info timestamp is missing!");
661 const QDate currentDate = OS::current_date();
662 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
664 updateInfo->resetInfo();
665 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
668 else if(currentDate < updateInfoDate)
670 log("Version info is from the future, take care!");
671 qWarning("Version info is from the future, take care!");
674 if(!updateInfo->isComplete())
676 log("WARNING: Version info is incomplete!");
683 //----------------------------------------------------------
685 //----------------------------------------------------------
687 bool UpdateChecker::getFile(const QString &url, const QString &outFile, const unsigned int maxRedir)
689 for (int i = 0; i < 2; i++)
691 if (getFile(url, (i > 0), outFile, maxRedir))
695 if (MUTILS_BOOLIFY(m_cancelled))
703 bool UpdateChecker::getFile(const QString &url, const bool forceIp4, const QString &outFile, const unsigned int maxRedir)
705 QFileInfo output(outFile);
706 output.setCaching(false);
710 QFile::remove(output.canonicalFilePath());
718 init_process(process, output.absolutePath());
726 args << "--no-config" << "--no-cache" << "--no-dns-cache" << "--no-check-certificate" << "--no-hsts";
727 args << QString().sprintf("--max-redirect=%u", maxRedir) << QString().sprintf("--timeout=%u", DOWNLOAD_TIMEOUT / 1000);
728 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
729 args << "-O" << output.fileName() << url;
732 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
733 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
734 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
737 timer.setSingleShot(true);
738 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
740 const QRegExp httpResponseOK("200 OK$");
742 process.start(m_binaryWGet, args);
744 if (!process.waitForStarted())
749 timer.start(DOWNLOAD_TIMEOUT);
751 while (process.state() != QProcess::NotRunning)
754 const bool bTimeOut = (!timer.isActive());
755 while (process.canReadLine())
757 const QString line = QString::fromLatin1(process.readLine()).simplified();
760 if (bTimeOut || MUTILS_BOOLIFY(m_cancelled))
762 qWarning("WGet process timed out <-- killing!");
764 process.waitForFinished();
765 log(bTimeOut ? "!!! TIMEOUT !!!": "!!! CANCELLED !!!");
771 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
773 log(QString().sprintf("Exited with code %d", process.exitCode()));
774 return (process.exitCode() == 0) && output.exists() && output.isFile();
777 bool UpdateChecker::tryContactHost(const QString &hostname, const int &timeoutMsec)
779 log(QString("Connecting to host: %1").arg(hostname), "");
782 init_process(process, temp_folder());
785 args << "--retry" << QString::number(3) << hostname << QString::number(80);
788 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
789 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
790 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
793 timer.setSingleShot(true);
794 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
796 process.start(m_binaryMCat, args);
798 if (!process.waitForStarted())
803 timer.start(timeoutMsec);
805 while (process.state() != QProcess::NotRunning)
808 const bool bTimeOut = (!timer.isActive());
809 while (process.canReadLine())
811 QString line = QString::fromLatin1(process.readLine()).simplified();
814 if (bTimeOut || MUTILS_BOOLIFY(m_cancelled))
816 qWarning("MCat process timed out <-- killing!");
818 process.waitForFinished();
819 log(bTimeOut ? "!!! TIMEOUT !!!" : "!!! CANCELLED !!!");
825 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
827 if (process.exitCode() != 0)
829 log("Connection has failed!");
832 log(QString().sprintf("Exited with code %d", process.exitCode()), "");
833 return (process.exitCode() == 0);
836 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
838 if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
840 qWarning("CheckSignature: File and signature should be in same folder!");
844 QString keyRingPath(m_binaryKeys);
845 bool removeKeyring = false;
846 if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
848 keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
849 removeKeyring = true;
850 if (!QFile::copy(m_binaryKeys, keyRingPath))
852 qWarning("CheckSignature: Failed to copy the key-ring file!");
858 init_process(process, QFileInfo(file).absolutePath());
861 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
862 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
863 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
865 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(keyRingPath).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
867 if (!process.waitForStarted())
871 remove_file(keyRingPath);
876 while (process.state() == QProcess::Running)
879 while (process.canReadLine())
881 log(QString::fromLatin1(process.readLine()).simplified());
887 remove_file(keyRingPath);
890 log(QString().sprintf("Exited with code %d", process.exitCode()));
891 return (process.exitCode() == 0);
894 ////////////////////////////////////////////////////////////
896 ////////////////////////////////////////////////////////////
900 ////////////////////////////////////////////////////////////
902 ////////////////////////////////////////////////////////////