1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 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 using namespace MUtils;
37 ///////////////////////////////////////////////////////////////////////////////
39 ///////////////////////////////////////////////////////////////////////////////
41 static const char *header_id = "!Update";
43 static const char *mirror_url_postfix[] =
50 static const char *update_mirrors[] =
52 "http://muldersoft.com/",
53 "http://mulder.bplaced.net/", //"http://mulder.cwsurf.de/",
54 "http://mulder.6te.net/",
55 "http://mulder.webuda.com/", //"http://mulder.byethost13.com/",
56 "http://mulder.pe.hu/", //"http://muldersoft.kilu.de/",
57 "http://muldersoft.square7.ch/", //"http://muldersoft.zxq.net/",
58 "http://muldersoft.co.nf/",
59 "http://muldersoft.eu.pn/",
60 "http://muldersoft.lima-city.de/",
61 "http://www.muldersoft.keepfree.de/",
62 "http://lamexp.sourceforge.net/",
63 "http://lordmulder.github.io/LameXP/",
64 "http://lord_mulder.bitbucket.org/",
65 "http://www.tricksoft.de/",
69 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
74 "clbianco.altervista.org",
75 "status.aws.amazon.com",
83 "web.audacityteam.org",
84 "status.automattic.com",
92 "www.bingeandgrab.com",
93 "www.bucketheadpikes.com",
94 "www.buckethead-coop.com",
97 "www.citizeninsomniac.com",
101 "www.codeproject.com",
102 "www.der-postillon.com",
121 "www.huffingtonpost.co.uk",
127 "www.jiscdigitalmedia.ac.uk",
128 "kannmanumdieuhrzeitschonnbierchentrinken.de",
129 "mirrors.kernel.org",
131 "lame.sourceforge.net",
136 "www.livejournal.com",
141 "www.mod-technologies.com",
145 "wiki.multimedia.cx",
147 "mirror.netcologne.de",
157 "www.portablefreeware.com",
158 "support.proboards.com",
163 "www.seamonkey-project.org",
170 "www.sputnikmusic.com",
174 "tdm-gcc.tdragon.net",
181 "blog.virustotal.com",
182 "www.vkgoeswild.com",
185 "status.wikimedia.org",
195 "ffmpeg.zeranoe.com",
199 static const int MIN_CONNSCORE = 8;
200 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
201 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
204 static int getMaxProgress(void)
206 int counter = MIN_CONNSCORE + 2;
207 for(int i = 0; update_mirrors[i]; i++) counter++;
211 static QStringList buildRandomList(const char *const values[])
214 for (int index = 0; values[index]; index++)
216 const int pos = next_rand32() % (index + 1);
217 list.insert(pos, QString::fromLatin1(values[index]));
222 ////////////////////////////////////////////////////////////
224 ////////////////////////////////////////////////////////////
226 UpdateCheckerInfo::UpdateCheckerInfo(void)
231 void UpdateCheckerInfo::resetInfo(void)
234 m_buildDate.setDate(1900, 1, 1);
235 m_downloadSite.clear();
236 m_downloadAddress.clear();
237 m_downloadFilename.clear();
238 m_downloadFilecode.clear();
239 m_downloadChecksum.clear();
242 bool UpdateCheckerInfo::isComplete(void)
244 if(this->m_buildNo < 1) return false;
245 if(this->m_buildDate.year() < 2010) return false;
246 if(this->m_downloadSite.isEmpty()) return false;
247 if(this->m_downloadAddress.isEmpty()) return false;
248 if(this->m_downloadFilename.isEmpty()) return false;
249 if(this->m_downloadFilecode.isEmpty()) return false;
250 if(this->m_downloadChecksum.isEmpty()) return false;
255 ////////////////////////////////////////////////////////////
256 // Constructor & Destructor
257 ////////////////////////////////////////////////////////////
259 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binNC, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
261 m_updateInfo(new UpdateCheckerInfo()),
262 m_binaryWGet(binWGet),
264 m_binaryGnuPG(binGnuPG),
265 m_binaryKeys(binKeys),
266 m_applicationId(applicationId),
267 m_installedBuildNo(installedBuildNo),
268 m_betaUpdates(betaUpdates),
269 m_testMode(testMode),
270 m_maxProgress(getMaxProgress())
273 m_status = UpdateStatus_NotStartedYet;
276 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
278 MUTILS_THROW("Tools not initialized correctly!");
282 UpdateChecker::~UpdateChecker(void)
286 ////////////////////////////////////////////////////////////
287 // Protected functions
288 ////////////////////////////////////////////////////////////
290 void UpdateChecker::run(void)
292 qDebug("Update checker thread started!");
293 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
294 qDebug("Update checker thread completed.");
297 void UpdateChecker::checkForUpdates(void)
299 // ----- Initialization ----- //
302 m_updateInfo->resetInfo();
306 // ----- Test Internet Connection ----- //
308 log("Checking internet connection...", "");
309 setStatus(UpdateStatus_CheckingConnection);
311 const int networkStatus = OS::network_status();
312 if(networkStatus == OS::NETWORK_TYPE_NON)
314 log("Operating system reports that the computer is currently offline !!!");
315 setProgress(m_maxProgress);
316 setStatus(UpdateStatus_ErrorNoConnection);
322 // ----- Test Known Hosts Connectivity ----- //
324 int connectionScore = 0;
326 QStringList hostList = buildRandomList(known_hosts);
327 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE)))
329 if(tryContactHost(hostList.takeFirst()))
331 connectionScore += 1;
333 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
337 if(connectionScore < MIN_CONNSCORE)
339 log("", "Connectivity test has failed: Internet connection appears to be broken!");
340 setProgress(m_maxProgress);
341 setStatus(UpdateStatus_ErrorConnectionTestFailed);
345 // ----- Fetch Update Info From Server ----- //
347 log("----", "", "Checking for updates online...");
348 setStatus(UpdateStatus_FetchingUpdates);
350 QStringList mirrorList = buildRandomList(update_mirrors);
351 while(!mirrorList.isEmpty())
353 QString currentMirror = mirrorList.takeFirst();
354 setProgress(m_progress + 1);
357 if(tryUpdateMirror(m_updateInfo.data(), currentMirror))
368 setProgress(m_maxProgress);
372 if(m_updateInfo->m_buildNo > m_installedBuildNo)
374 setStatus(UpdateStatus_CompletedUpdateAvailable);
376 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
378 setStatus(UpdateStatus_CompletedNoUpdates);
382 setStatus(UpdateStatus_CompletedNewVersionOlder);
387 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
391 void UpdateChecker::testKnownHosts(void)
393 QStringList hostList;
394 for(int i = 0; known_hosts[i]; i++)
396 hostList << QString::fromLatin1(known_hosts[i]);
399 qDebug("\n[Known Hosts]");
400 log("Testing all known hosts...", "", "---");
402 int hostCount = hostList.count();
403 while(!hostList.isEmpty())
405 QString currentHost = hostList.takeFirst();
406 qDebug("Testing: %s", currentHost.toLatin1().constData());
407 log("", "Testing:", currentHost, "");
408 if (!tryContactHost(currentHost))
410 qWarning("\nConnectivity test FAILED on the following host:\n%s\n", currentHost.toLatin1().constData());
416 ////////////////////////////////////////////////////////////
418 ////////////////////////////////////////////////////////////
420 void UpdateChecker::setStatus(const int status)
422 if(m_status != status)
425 emit statusChanged(status);
429 void UpdateChecker::setProgress(const int progress)
431 if(m_progress != progress)
433 m_progress = progress;
434 emit progressChanged(progress);
438 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
440 if(!str1.isNull()) emit messageLogged(str1);
441 if(!str2.isNull()) emit messageLogged(str2);
442 if(!str3.isNull()) emit messageLogged(str3);
443 if(!str4.isNull()) emit messageLogged(str4);
446 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url)
448 bool success = false;
449 log("", "Trying mirror:", url);
451 const QString randPart = rand_str();
452 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
453 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
455 if(getUpdateInfo(url, outFileVers, outFileSign))
457 log("", "Download okay, checking signature:");
458 if(checkSignature(outFileVers, outFileSign))
460 log("", "Signature okay, parsing info:");
461 success = parseVersionInfo(outFileVers, updateInfo);
465 log("", "Bad signature, take care!");
470 log("", "Download has failed!");
473 QFile::remove(outFileVers);
474 QFile::remove(outFileSign);
479 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
481 log("", "Downloading update info:");
482 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
487 log("", "Downloading signature:");
488 if(!getFile(QString("%1%2.sig2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
496 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
498 QRegExp value("^(\\w+)=(.+)$");
499 QRegExp section("^\\[(.+)\\]$");
501 QDate updateInfoDate;
502 updateInfo->resetInfo();
505 if(!data.open(QIODevice::ReadOnly))
507 qWarning("Cannot open update info file for reading!");
516 QString line = QString::fromLatin1(data.readLine()).trimmed();
517 if(section.indexIn(line) >= 0)
519 log(QString("Sec: [%1]").arg(section.cap(1)));
520 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
521 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
524 if(inSec && (value.indexIn(line) >= 0))
526 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
527 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
530 const unsigned int temp = value.cap(2).toUInt(&ok);
531 if(ok) updateInfo->m_buildNo = temp;
533 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
535 const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
536 if(temp.isValid()) updateInfo->m_buildDate = temp;
538 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
540 updateInfo->m_downloadSite = value.cap(2).trimmed();
542 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
544 updateInfo->m_downloadAddress = value.cap(2).trimmed();
546 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
548 updateInfo->m_downloadFilename = value.cap(2).trimmed();
550 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
552 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
554 else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
556 updateInfo->m_downloadChecksum = value.cap(2).trimmed();
559 if(inHdr && (value.indexIn(line) >= 0))
561 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
562 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
564 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
565 if(temp.isValid()) updateInfoDate = temp;
570 if(!updateInfoDate.isValid())
572 updateInfo->resetInfo();
573 log("WARNING: Version info timestamp is missing!");
577 const QDate currentDate = OS::current_date();
578 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
580 updateInfo->resetInfo();
581 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
584 else if(currentDate < updateInfoDate)
586 log("Version info is from the future, take care!");
587 qWarning("Version info is from the future, take care!");
590 if(!updateInfo->isComplete())
592 log("WARNING: Version info is incomplete!");
599 //----------------------------------------------------------
601 //----------------------------------------------------------
603 bool UpdateChecker::getFile(const QString &url, const QString &outFile, const unsigned int maxRedir, bool *httpOk)
605 for (int i = 0; i < 2; i++)
607 if (getFile(url, (i > 0), outFile, maxRedir, httpOk))
615 bool UpdateChecker::getFile(const QString &url, const bool forceIp4, const QString &outFile, const unsigned int maxRedir, bool *httpOk)
617 QFileInfo output(outFile);
618 output.setCaching(false);
619 if (httpOk) *httpOk = false;
623 QFile::remove(output.canonicalFilePath());
631 init_process(process, output.absolutePath());
639 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
640 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
641 args << "-O" << output.fileName() << url;
644 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
645 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
646 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
649 timer.setSingleShot(true);
650 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
652 const QRegExp httpResponseOK("200 OK$");
654 process.start(m_binaryWGet, args);
656 if (!process.waitForStarted())
663 while (process.state() != QProcess::NotRunning)
666 const bool bTimeOut = (!timer.isActive());
667 while (process.canReadLine())
669 QString line = QString::fromLatin1(process.readLine()).simplified();
670 if (line.contains(httpResponseOK))
672 line.append(" [OK]");
673 if (httpOk) *httpOk = true;
679 qWarning("WGet process timed out <-- killing!");
681 process.waitForFinished();
682 log("!!! TIMEOUT !!!");
688 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
690 log(QString().sprintf("Exited with code %d", process.exitCode()));
691 return (process.exitCode() == 0) && output.exists() && output.isFile();
694 bool UpdateChecker::tryContactHost(const QString &hostname)
696 log(QString("Connecting to host: %1").arg(hostname));
699 init_process(process, temp_folder());
702 args << "-z" << hostname << QString::number(80);
705 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
706 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
707 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
710 timer.setSingleShot(true);
711 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
713 process.start(m_binaryNC, args);
715 if (!process.waitForStarted())
722 while (process.state() != QProcess::NotRunning)
725 const bool bTimeOut = (!timer.isActive());
726 while (process.canReadLine())
728 QString line = QString::fromLatin1(process.readLine()).simplified();
733 qWarning("NC process timed out <-- killing!");
735 process.waitForFinished();
736 log("!!! TIMEOUT !!!");
742 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
744 if (process.exitCode() != 0)
746 log("Connection has failed!");
749 log(QString().sprintf("Exited with code %d", process.exitCode()), "");
750 return (process.exitCode() == 0);
753 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
755 if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
757 qWarning("CheckSignature: File and signature should be in same folder!");
761 QString keyRingPath(m_binaryKeys);
762 bool removeKeyring = false;
763 if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
765 keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
766 removeKeyring = true;
767 if (!QFile::copy(m_binaryKeys, keyRingPath))
769 qWarning("CheckSignature: Failed to copy the key-ring file!");
775 init_process(process, QFileInfo(file).absolutePath());
778 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
779 connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
780 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
782 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(keyRingPath).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
784 if (!process.waitForStarted())
788 remove_file(keyRingPath);
793 while (process.state() == QProcess::Running)
796 while (process.canReadLine())
798 log(QString::fromLatin1(process.readLine()).simplified());
804 remove_file(keyRingPath);
807 log(QString().sprintf("Exited with code %d", process.exitCode()));
808 return (process.exitCode() == 0);
811 ////////////////////////////////////////////////////////////
813 ////////////////////////////////////////////////////////////
817 ////////////////////////////////////////////////////////////
819 ////////////////////////////////////////////////////////////