1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 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_prim[] =
52 "http://muldersoft.com/",
53 "http://mulder.bplaced.net/",
54 "http://mulder.cwsurf.de/",
55 "http://mulder.6te.net/",
56 "http://mulder.webuda.com/", //"http://mulder.byethost13.com/",
57 "http://mulder.pe.hu/", //"http://muldersoft.kilu.de/",
58 "http://muldersoft.square7.ch/", //"http://muldersoft.zxq.net/",
59 "http://muldersoft.co.nf/",
60 "http://muldersoft.eu.pn/",
61 "http://lamexp.sourceforge.net/",
62 "http://lordmulder.github.io/LameXP/",
63 "http://lord_mulder.bitbucket.org/",
64 "http://www.tricksoft.de/",
68 static const char *update_mirrors_back[] =
70 "http://mplayer.savedonthe.net/",
74 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
76 "http://www.163.com/",
77 "http://www.7-zip.org/",
78 "http://www.ac3filter.net/",
79 "http://www.amazon.com/",
80 "http://antergos.com/",
81 "http://www.aol.com/",
82 "http://www.apache.org/",
83 "http://www.apple.com/",
84 "http://www.adobe.com/",
85 "http://web.audacityteam.org/",
86 "http://automattic.com/",
87 "http://www.avidemux.org/",
88 "http://www.babylon.com/",
89 "http://www.baidu.com/",
90 "http://bandcamp.com/",
91 "http://www.bbc.co.uk/",
92 "http://www.berlios.de/",
93 "http://www.bing.com/",
94 "http://www.bucketheadpikes.com/",
96 "http://www.citizeninsomniac.com/WMV/",
97 "http://www.cnet.com/",
99 "http://www.codeplex.com/",
100 "http://www.der-postillon.com/",
101 "http://www.ebay.com/",
102 "http://www.equation.com/",
104 "http://fedoraproject.org/wiki/Fedora_Project_Wiki",
105 "http://blog.fefe.de/",
106 "http://www.ffmpeg.org/",
107 "http://blog.flickr.net/en",
108 "http://free-codecs.com/",
109 "http://git-scm.com/",
110 "http://status.gitlab.com/",
111 "http://www.gmx.net/",
112 "http://news.gnome.org/",
113 "http://www.gnu.org/",
115 "http://code.google.com/",
116 "http://haali.su/mkv/",
117 "http://www.heise.de/",
118 "http://www.huffingtonpost.co.uk/",
119 "http://www.iana.org/",
120 "http://www.imdb.com/",
121 "http://www.imgburn.com/",
123 "http://www.jd.com/contact/",
124 "http://kannmanumdieuhrzeitschonnbierchentrinken.de/",
125 "http://mirrors.kernel.org/",
126 "http://komisar.gin.by/",
127 "http://lame.sourceforge.net/",
128 "http://www.libav.org/",
129 "http://blog.linkedin.com/",
130 "http://www.linuxmint.com/",
131 "http://www.livedoor.com/",
132 "http://www.livejournal.com/",
133 "http://go.mail.ru/",
134 "http://www.mediafire.com/about/",
135 "http://ftp.mozilla.org/",
136 "http://mplayerhq.hu/",
137 "http://www.msn.com/en-us/",
138 "http://wiki.multimedia.cx/",
139 "http://www.nch.com.au/",
140 "http://oss.netfarm.it/",
141 "http://www.nytimes.com/",
142 "http://www.opera.com/",
143 "http://www.partha.com/",
144 "http://pastie.org/",
145 "http://www.portablefreeware.com/",
147 "http://www.quakelive.com/",
148 "http://www.seamonkey-project.org/",
149 "http://www.shspvr.com/",
150 "http://www.sina.com.cn/",
151 "http://www.sohu.com/",
152 "http://www.sogou.com/",
153 "http://sourceforge.net/",
154 "http://www.spiegel.de/",
155 "http://stackoverflow.com/",
156 "http://tdm-gcc.tdragon.net/",
157 "http://www.tdrsmusic.com/",
158 "http://www.ubuntu.com/",
159 "http://www.uol.com.br/",
160 "http://www.videohelp.com/",
161 "http://www.videolan.org/",
162 "http://virtualdub.org/",
163 "http://blog.virustotal.com/",
164 "http://www.warr.org/buckethead.html",
165 "http://www.weibo.com/login.php",
166 "http://status.wikimedia.org/",
167 "http://www.winamp.com/",
170 "http://xhmikosr.1f0.de/",
172 "http://us.mail.yahoo.com/",
173 "http://www.yandex.ru/",
174 "http://www.youtube.com/yt/about/",
175 "http://www.zedo.com/",
176 "http://ffmpeg.zeranoe.com/",
180 static const int MIN_CONNSCORE = 8;
181 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
182 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
185 static int getMaxProgress(void)
187 int counter = MIN_CONNSCORE + 2;
188 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
189 for(int i = 0; update_mirrors_back[i]; i++) counter++;
193 ////////////////////////////////////////////////////////////
195 ////////////////////////////////////////////////////////////
197 UpdateCheckerInfo::UpdateCheckerInfo(void)
202 void UpdateCheckerInfo::resetInfo(void)
205 m_buildDate.setDate(1900, 1, 1);
206 m_downloadSite.clear();
207 m_downloadAddress.clear();
208 m_downloadFilename.clear();
209 m_downloadFilecode.clear();
210 m_downloadChecksum.clear();
213 bool UpdateCheckerInfo::isComplete(void)
215 if(this->m_buildNo < 1) return false;
216 if(this->m_buildDate.year() < 2010) return false;
217 if(this->m_downloadSite.isEmpty()) return false;
218 if(this->m_downloadAddress.isEmpty()) return false;
219 if(this->m_downloadFilename.isEmpty()) return false;
220 if(this->m_downloadFilecode.isEmpty()) return false;
221 if(this->m_downloadChecksum.isEmpty()) return false;
226 ////////////////////////////////////////////////////////////
227 // Constructor & Destructor
228 ////////////////////////////////////////////////////////////
230 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
232 m_updateInfo(new UpdateCheckerInfo()),
233 m_binaryWGet(binWGet),
234 m_binaryGnuPG(binGnuPG),
235 m_binaryKeys(binKeys),
236 m_applicationId(applicationId),
237 m_installedBuildNo(installedBuildNo),
238 m_betaUpdates(betaUpdates),
239 m_testMode(testMode),
240 m_maxProgress(getMaxProgress())
243 m_status = UpdateStatus_NotStartedYet;
246 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
248 MUTILS_THROW("Tools not initialized correctly!");
252 UpdateChecker::~UpdateChecker(void)
256 ////////////////////////////////////////////////////////////
257 // Protected functions
258 ////////////////////////////////////////////////////////////
260 void UpdateChecker::run(void)
262 qDebug("Update checker thread started!");
263 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
264 qDebug("Update checker thread completed.");
267 void UpdateChecker::checkForUpdates(void)
269 // ----- Initialization ----- //
272 m_updateInfo->resetInfo();
276 // ----- Test Internet Connection ----- //
278 int connectionScore = 0;
279 int maxConnectTries = (3 * MIN_CONNSCORE) / 2;
281 log("Checking internet connection...");
282 setStatus(UpdateStatus_CheckingConnection);
284 const int networkStatus = OS::network_status();
285 if(networkStatus == OS::NETWORK_TYPE_NON)
287 log("", "Operating system reports that the computer is currently offline !!!");
288 setProgress(m_maxProgress);
289 setStatus(UpdateStatus_ErrorNoConnection);
295 // ----- Test Known Hosts Connectivity ----- //
297 QStringList hostList;
298 for(int i = 0; known_hosts[i]; i++)
300 hostList << QString::fromLatin1(known_hosts[i]);
303 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
305 switch(tryContactHost(hostList.takeAt(next_rand32() % hostList.count())))
307 case 01: connectionScore += 1; break;
308 case 02: connectionScore += 2; break;
309 default: maxConnectTries -= 1; break;
311 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
315 if(connectionScore < MIN_CONNSCORE)
317 log("", "Connectivity test has failed: Internet connection appears to be broken!");
318 setProgress(m_maxProgress);
319 setStatus(UpdateStatus_ErrorConnectionTestFailed);
323 // ----- Build Mirror List ----- //
325 log("", "----", "", "Checking for updates online...");
326 setStatus(UpdateStatus_FetchingUpdates);
328 QStringList mirrorList;
329 for(int index = 0; update_mirrors_prim[index]; index++)
331 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
334 if(const int len = mirrorList.count())
336 const int rounds = len * 1097;
337 for(int i = 0; i < rounds; i++)
339 mirrorList.swap(i % len, next_rand32() % len);
343 for(int index = 0; update_mirrors_back[index]; index++)
345 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
348 // ----- Fetch Update Info From Server ----- //
350 while(!mirrorList.isEmpty())
352 QString currentMirror = mirrorList.takeFirst();
353 setProgress(m_progress + 1);
356 if(tryUpdateMirror(m_updateInfo.data(), currentMirror))
367 setProgress(m_maxProgress);
371 if(m_updateInfo->m_buildNo > m_installedBuildNo)
373 setStatus(UpdateStatus_CompletedUpdateAvailable);
375 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
377 setStatus(UpdateStatus_CompletedNoUpdates);
381 setStatus(UpdateStatus_CompletedNewVersionOlder);
386 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
390 void UpdateChecker::testKnownHosts(void)
392 QStringList hostList;
393 for(int i = 0; known_hosts[i]; i++)
395 hostList << QString::fromLatin1(known_hosts[i]);
398 qDebug("\n[Known Hosts]");
399 log("Testing all known hosts...", "", "---");
401 int hostCount = hostList.count();
402 while(!hostList.isEmpty())
404 QString currentHost = hostList.takeFirst();
405 qDebug("Testing: %s", currentHost.toLatin1().constData());
406 log("", "Testing:", currentHost, "");
407 QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
409 if(!getFile(currentHost, outFile, 0, &httpOk))
413 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
417 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
421 QFile::remove(outFile);
425 ////////////////////////////////////////////////////////////
427 ////////////////////////////////////////////////////////////
429 void UpdateChecker::setStatus(const int status)
431 if(m_status != status)
434 emit statusChanged(status);
438 void UpdateChecker::setProgress(const int progress)
440 if(m_progress != progress)
442 m_progress = progress;
443 emit progressChanged(progress);
447 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
449 if(!str1.isNull()) emit messageLogged(str1);
450 if(!str2.isNull()) emit messageLogged(str2);
451 if(!str3.isNull()) emit messageLogged(str3);
452 if(!str4.isNull()) emit messageLogged(str4);
455 int UpdateChecker::tryContactHost(const QString &url)
457 int result = -1; bool httpOkay = false;
458 const QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
459 log("", "Testing host:", url);
461 if(getFile(url, outFile, 0, &httpOkay))
463 log("Connection to host was established successfully.");
470 log("Connection to host timed out after HTTP OK was received.");
475 log("Connection failed: The host could not be reached!");
480 QFile::remove(outFile);
484 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url)
486 bool success = false;
487 log("", "Trying mirror:", url);
489 const QString randPart = rand_str();
490 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
491 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
493 if(getUpdateInfo(url, outFileVers, outFileSign))
495 log("", "Download okay, checking signature:");
496 if(checkSignature(outFileVers, outFileSign))
498 log("", "Signature okay, parsing info:");
499 success = parseVersionInfo(outFileVers, updateInfo);
503 log("", "Bad signature, take care!");
508 log("", "Download has failed!");
511 QFile::remove(outFileVers);
512 QFile::remove(outFileSign);
517 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
519 log("", "Downloading update info:");
520 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
525 log("", "Downloading signature:");
526 if(!getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
534 bool UpdateChecker::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
536 QFileInfo output(outFile);
537 output.setCaching(false);
538 if(httpOk) *httpOk = false;
542 QFile::remove(output.canonicalFilePath());
550 init_process(process, output.absolutePath());
553 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
554 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
555 args << "-O" << output.fileName() << url;
558 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
559 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
560 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
563 timer.setSingleShot(true);
564 timer.setInterval(25000);
565 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
567 const QRegExp httpResponseOK("200 OK$");
569 process.start(m_binaryWGet, args);
571 if(!process.waitForStarted())
578 while(process.state() != QProcess::NotRunning)
581 const bool bTimeOut = (!timer.isActive());
582 while(process.canReadLine())
584 QString line = QString::fromLatin1(process.readLine()).simplified();
585 if(line.contains(httpResponseOK))
587 line.append(" [OK]");
588 if(httpOk) *httpOk = true;
594 qWarning("WGet process timed out <-- killing!");
596 process.waitForFinished();
597 log("!!! TIMEOUT !!!");
603 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
605 log(QString().sprintf("Exited with code %d", process.exitCode()));
606 return (process.exitCode() == 0) && output.exists() && output.isFile();
609 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
611 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
613 qWarning("CheckSignature: File and signature should be in same folder!");
617 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
619 qWarning("CheckSignature: File and keyring should be in same folder!");
624 init_process(process, QFileInfo(file).absolutePath());
627 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
628 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
629 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
631 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
633 if(!process.waitForStarted())
638 while(process.state() == QProcess::Running)
641 while(process.canReadLine())
643 log(QString::fromLatin1(process.readLine()).simplified());
647 log(QString().sprintf("Exited with code %d", process.exitCode()));
648 return (process.exitCode() == 0);
651 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
653 QRegExp value("^(\\w+)=(.+)$");
654 QRegExp section("^\\[(.+)\\]$");
656 QDate updateInfoDate;
657 updateInfo->resetInfo();
660 if(!data.open(QIODevice::ReadOnly))
662 qWarning("Cannot open update info file for reading!");
671 QString line = QString::fromLatin1(data.readLine()).trimmed();
672 if(section.indexIn(line) >= 0)
674 log(QString("Sec: [%1]").arg(section.cap(1)));
675 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
676 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
679 if(inSec && (value.indexIn(line) >= 0))
681 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
682 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
685 const unsigned int temp = value.cap(2).toUInt(&ok);
686 if(ok) updateInfo->m_buildNo = temp;
688 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
690 const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
691 if(temp.isValid()) updateInfo->m_buildDate = temp;
693 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
695 updateInfo->m_downloadSite = value.cap(2).trimmed();
697 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
699 updateInfo->m_downloadAddress = value.cap(2).trimmed();
701 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
703 updateInfo->m_downloadFilename = value.cap(2).trimmed();
705 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
707 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
709 else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
711 updateInfo->m_downloadChecksum = value.cap(2).trimmed();
714 if(inHdr && (value.indexIn(line) >= 0))
716 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
717 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
719 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
720 if(temp.isValid()) updateInfoDate = temp;
725 if(!updateInfoDate.isValid())
727 updateInfo->resetInfo();
728 log("WARNING: Version info timestamp is missing!");
732 const QDate currentDate = OS::current_date();
733 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
735 updateInfo->resetInfo();
736 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
739 else if(currentDate < updateInfoDate)
741 log("Version info is from the future, take care!");
742 qWarning("Version info is from the future, take care!");
745 if(!updateInfo->isComplete())
747 log("WARNING: Version info is incomplete!");
754 ////////////////////////////////////////////////////////////
756 ////////////////////////////////////////////////////////////
760 ////////////////////////////////////////////////////////////
762 ////////////////////////////////////////////////////////////