Removed some obsolete/broken mirror sites from the list.
[MUtilities.git] / src / UpdateChecker.cpp
blobddb352bcd142cdf9df06526a0fca379a44ed5e86
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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>
28 #include <QFile>
29 #include <QFileInfo>
30 #include <QProcess>
31 #include <QUrl>
32 #include <QEventLoop>
33 #include <QTimer>
35 using namespace MUtils;
37 ///////////////////////////////////////////////////////////////////////////////
38 // CONSTANTS
39 ///////////////////////////////////////////////////////////////////////////////
41 static const char *header_id = "!Update";
43 static const char *mirror_url_postfix[] =
45 "update.ver",
46 "update_beta.ver",
47 NULL
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/",
65 NULL
68 static const char *update_mirrors_back[] =
70 "http://mplayer.savedonthe.net/",
71 NULL
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/",
95 "http://www.ccc.de/",
96 "http://www.citizeninsomniac.com/WMV/",
97 "http://www.cnet.com/",
98 "http://cnzz.com/",
99 "http://www.codeplex.com/",
100 "http://www.der-postillon.com/",
101 "http://www.ebay.com/",
102 "http://www.equation.com/",
103 "http://fc2.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/",
114 "http://go.com/",
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/",
122 "http://imgur.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/",
146 "http://www.qt.io/",
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/",
168 "http://wpde.org/",
169 "http://x265.org/",
170 "http://xhmikosr.1f0.de/",
171 "http://xiph.org/",
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/",
177 NULL
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";
184 //Helper function
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++;
190 return counter;
193 ////////////////////////////////////////////////////////////
194 // Update Info Class
195 ////////////////////////////////////////////////////////////
197 UpdateCheckerInfo::UpdateCheckerInfo(void)
199 resetInfo();
202 void UpdateCheckerInfo::resetInfo(void)
204 m_buildNo = 0;
205 m_buildDate.setDate(1900, 1, 1);
206 m_downloadSite.clear();
207 m_downloadAddress.clear();
208 m_downloadFilename.clear();
209 m_downloadFilecode.clear();
212 ////////////////////////////////////////////////////////////
213 // Constructor & Destructor
214 ////////////////////////////////////////////////////////////
216 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
218 m_updateInfo(new UpdateCheckerInfo()),
219 m_binaryWGet(binWGet),
220 m_binaryGnuPG(binGnuPG),
221 m_binaryKeys(binKeys),
222 m_applicationId(applicationId),
223 m_installedBuildNo(installedBuildNo),
224 m_betaUpdates(betaUpdates),
225 m_testMode(testMode),
226 m_maxProgress(getMaxProgress())
228 m_success = false;
229 m_status = UpdateStatus_NotStartedYet;
230 m_progress = 0;
232 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
234 MUTILS_THROW("Tools not initialized correctly!");
238 UpdateChecker::~UpdateChecker(void)
240 delete m_updateInfo;
243 ////////////////////////////////////////////////////////////
244 // Protected functions
245 ////////////////////////////////////////////////////////////
247 void UpdateChecker::run(void)
249 qDebug("Update checker thread started!");
250 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
251 qDebug("Update checker thread completed.");
254 void UpdateChecker::checkForUpdates(void)
256 // ----- Initialization ----- //
258 m_success = false;
259 m_updateInfo->resetInfo();
260 seed_rand();
261 setProgress(0);
263 // ----- Test Internet Connection ----- //
265 int connectionScore = 0;
266 int maxConnectTries = (3 * MIN_CONNSCORE) / 2;
268 log("Checking internet connection...");
269 setStatus(UpdateStatus_CheckingConnection);
271 const int networkStatus = OS::network_status();
272 if(networkStatus == OS::NETWORK_TYPE_NON)
274 log("", "Operating system reports that the computer is currently offline !!!");
275 setProgress(m_maxProgress);
276 setStatus(UpdateStatus_ErrorNoConnection);
277 return;
280 setProgress(1);
282 // ----- Test Known Hosts Connectivity ----- //
284 QStringList hostList;
285 for(int i = 0; known_hosts[i]; i++)
287 hostList << QString::fromLatin1(known_hosts[i]);
290 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
292 switch(tryContactHost(hostList.takeAt(next_rand32() % hostList.count())))
294 case 01: connectionScore += 1; break;
295 case 02: connectionScore += 2; break;
296 default: maxConnectTries -= 1; break;
298 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
299 msleep(64);
302 if(connectionScore < MIN_CONNSCORE)
304 log("", "Connectivity test has failed: Internet connection appears to be broken!");
305 setProgress(m_maxProgress);
306 setStatus(UpdateStatus_ErrorConnectionTestFailed);
307 return;
310 // ----- Build Mirror List ----- //
312 log("", "----", "", "Checking for updates online...");
313 setStatus(UpdateStatus_FetchingUpdates);
315 QStringList mirrorList;
316 for(int index = 0; update_mirrors_prim[index]; index++)
318 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
321 if(const int len = mirrorList.count())
323 const int rounds = len * 1097;
324 for(int i = 0; i < rounds; i++)
326 mirrorList.swap(i % len, next_rand32() % len);
330 for(int index = 0; update_mirrors_back[index]; index++)
332 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
335 // ----- Fetch Update Info From Server ----- //
337 while(!mirrorList.isEmpty())
339 QString currentMirror = mirrorList.takeFirst();
340 setProgress(m_progress + 1);
341 if(!m_success)
343 if(tryUpdateMirror(m_updateInfo, currentMirror))
345 m_success = true;
348 else
350 msleep(64);
354 setProgress(m_maxProgress);
356 if(m_success)
358 if(m_updateInfo->m_buildNo > m_installedBuildNo)
360 setStatus(UpdateStatus_CompletedUpdateAvailable);
362 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
364 setStatus(UpdateStatus_CompletedNoUpdates);
366 else
368 setStatus(UpdateStatus_CompletedNewVersionOlder);
371 else
373 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
377 void UpdateChecker::testKnownHosts(void)
379 QStringList hostList;
380 for(int i = 0; known_hosts[i]; i++)
382 hostList << QString::fromLatin1(known_hosts[i]);
385 qDebug("\n[Known Hosts]");
386 log("Testing all known hosts...", "", "---");
388 int hostCount = hostList.count();
389 while(!hostList.isEmpty())
391 QString currentHost = hostList.takeFirst();
392 qDebug("Testing: %s", currentHost.toLatin1().constData());
393 log("", "Testing:", currentHost, "");
394 QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
395 bool httpOk = false;
396 if(!getFile(currentHost, outFile, 0, &httpOk))
398 if(httpOk)
400 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
402 else
404 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
407 log("", "---");
408 QFile::remove(outFile);
412 ////////////////////////////////////////////////////////////
413 // PRIVATE FUNCTIONS
414 ////////////////////////////////////////////////////////////
416 void UpdateChecker::setStatus(const int status)
418 if(m_status != status)
420 m_status = status;
421 emit statusChanged(status);
425 void UpdateChecker::setProgress(const int progress)
427 if(m_progress != progress)
429 m_progress = progress;
430 emit progressChanged(progress);
434 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
436 if(!str1.isNull()) emit messageLogged(str1);
437 if(!str2.isNull()) emit messageLogged(str2);
438 if(!str3.isNull()) emit messageLogged(str3);
439 if(!str4.isNull()) emit messageLogged(str4);
442 int UpdateChecker::tryContactHost(const QString &url)
444 int result = -1; bool httpOkay = false;
445 const QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
446 log("", "Testing host:", url);
448 if(getFile(url, outFile, 0, &httpOkay))
450 log("Connection to host was established successfully.");
451 result = 2;
453 else
455 if(httpOkay)
457 log("Connection to host timed out after HTTP OK was received.");
458 result = 1;
460 else
462 log("Connection failed: The host could not be reached!");
463 result = 0;
467 QFile::remove(outFile);
468 return result;
471 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url)
473 bool success = false;
474 log("", "Trying mirror:", url);
476 const QString randPart = rand_str();
477 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
478 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
480 if(getUpdateInfo(url, outFileVers, outFileSign))
482 log("", "Download okay, checking signature:");
483 if(checkSignature(outFileVers, outFileSign))
485 log("", "Signature okay, parsing info:");
486 success = parseVersionInfo(outFileVers, updateInfo);
488 else
490 log("", "Bad signature, take care!");
493 else
495 log("", "Download has failed!");
498 QFile::remove(outFileVers);
499 QFile::remove(outFileSign);
501 return success;
504 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
506 log("", "Downloading update info:");
507 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
509 return false;
512 log("", "Downloading signature:");
513 if(!getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
515 return false;
518 return true;
521 bool UpdateChecker::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
523 QFileInfo output(outFile);
524 output.setCaching(false);
525 if(httpOk) *httpOk = false;
527 if(output.exists())
529 QFile::remove(output.canonicalFilePath());
530 if(output.exists())
532 return false;
536 QProcess process;
537 init_process(process, output.absolutePath());
539 QStringList args;
540 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
541 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
542 args << "-O" << output.fileName() << url;
544 QEventLoop loop;
545 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
546 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
547 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
549 QTimer timer;
550 timer.setSingleShot(true);
551 timer.setInterval(25000);
552 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
554 const QRegExp httpResponseOK("200 OK$");
556 process.start(m_binaryWGet, args);
558 if(!process.waitForStarted())
560 return false;
563 timer.start();
565 while(process.state() != QProcess::NotRunning)
567 loop.exec();
568 const bool bTimeOut = (!timer.isActive());
569 while(process.canReadLine())
571 QString line = QString::fromLatin1(process.readLine()).simplified();
572 if(line.contains(httpResponseOK))
574 line.append(" [OK]");
575 if(httpOk) *httpOk = true;
577 log(line);
579 if(bTimeOut)
581 qWarning("WGet process timed out <-- killing!");
582 process.kill();
583 process.waitForFinished();
584 log("!!! TIMEOUT !!!");
585 return false;
589 timer.stop();
590 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
592 log(QString().sprintf("Exited with code %d", process.exitCode()));
593 return (process.exitCode() == 0) && output.exists() && output.isFile();
596 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
598 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
600 qWarning("CheckSignature: File and signature should be in same folder!");
601 return false;
604 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
606 qWarning("CheckSignature: File and keyring should be in same folder!");
607 return false;
610 QProcess process;
611 init_process(process, QFileInfo(file).absolutePath());
613 QEventLoop loop;
614 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
615 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
616 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
618 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
620 if(!process.waitForStarted())
622 return false;
625 while(process.state() == QProcess::Running)
627 loop.exec();
628 while(process.canReadLine())
630 log(QString::fromLatin1(process.readLine()).simplified());
634 log(QString().sprintf("Exited with code %d", process.exitCode()));
635 return (process.exitCode() == 0);
638 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
640 QRegExp value("^(\\w+)=(.+)$");
641 QRegExp section("^\\[(.+)\\]$");
643 QDate updateInfoDate;
644 updateInfo->resetInfo();
646 QFile data(file);
647 if(!data.open(QIODevice::ReadOnly))
649 qWarning("Cannot open update info file for reading!");
650 return false;
653 bool inHdr = false;
654 bool inSec = false;
656 while(!data.atEnd())
658 QString line = QString::fromLatin1(data.readLine()).trimmed();
659 if(section.indexIn(line) >= 0)
661 log(QString("Sec: [%1]").arg(section.cap(1)));
662 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
663 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
664 continue;
666 if(inSec && (value.indexIn(line) >= 0))
668 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
669 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
671 bool ok = false;
672 unsigned int temp = value.cap(2).toUInt(&ok);
673 if(ok) updateInfo->m_buildNo = temp;
675 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
677 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
678 if(temp.isValid()) updateInfo->m_buildDate = temp;
680 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
682 updateInfo->m_downloadSite = value.cap(2).trimmed();
684 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
686 updateInfo->m_downloadAddress = value.cap(2).trimmed();
688 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
690 updateInfo->m_downloadFilename = value.cap(2).trimmed();
692 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
694 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
697 if(inHdr && (value.indexIn(line) >= 0))
699 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
700 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
702 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
703 if(temp.isValid()) updateInfoDate = temp;
708 if(!updateInfoDate.isValid())
710 updateInfo->resetInfo();
711 log("WARNING: Version info timestamp is missing!");
712 return false;
715 const QDate currentDate = OS::current_date();
716 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
718 updateInfo->resetInfo();
719 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
720 return false;
722 else if(currentDate < updateInfoDate)
724 log("Version info is from the future, take care!");
725 qWarning("Version info is from the future, take care!");
728 bool complete = true;
730 if(!(updateInfo->m_buildNo > 0)) complete = false;
731 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
732 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
733 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
734 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
735 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
737 if(!complete)
739 log("WARNING: Version info is incomplete!");
742 return complete;
745 ////////////////////////////////////////////////////////////
746 // SLOTS
747 ////////////////////////////////////////////////////////////
749 /*NONE*/
751 ////////////////////////////////////////////////////////////
752 // EVENTS
753 ////////////////////////////////////////////////////////////
755 /*NONE*/