Moved all the Sound-specific functions into MUtilities library.
[MUtilities.git] / src / UpdateChecker.cpp
blob1f0502e122321c2fa0f9850925806a3ee3e9f12c
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 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/",
57 "http://mulder.byethost13.com/",
58 "http://muldersoft.kilu.de/",
59 "http://mulder.pe.hu/",
60 "http://muldersoft.zxq.net/",
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://www.avidemux.org/",
86 "http://www.babylon.com/",
87 "http://www.baidu.com/",
88 "http://bandcamp.com/",
89 "http://www.bbc.co.uk/",
90 "http://www.berlios.de/",
91 "http://www.bing.com/",
92 "http://www.cnet.com/",
93 "http://cnzz.com/",
94 "http://www.codeplex.com/",
95 "http://qt.digia.com/",
96 "http://www.ebay.com/",
97 "http://www.equation.com/",
98 "http://fc2.com/",
99 "http://fedoraproject.org/",
100 "http://www.ffmpeg.org/",
101 "http://blog.flickr.net/en",
102 "http://free-codecs.com/",
103 "http://blog.gitorious.org/",
104 "http://git-scm.com/",
105 "http://www.gmx.net/",
106 "http://www.gnome.org/",
107 "http://www.gnu.org/",
108 "http://go.com/",
109 "http://code.google.com/",
110 "http://www.heise.de/",
111 "http://www.huffingtonpost.co.uk/",
112 "http://www.iana.org/",
113 "http://www.imdb.com/",
114 "http://www.imgburn.com/",
115 "http://imgur.com/",
116 "http://en.jd.com/",
117 "http://kannmanumdieuhrzeitschonnbierchentrinken.de/",
118 "http://mirrors.kernel.org/",
119 "http://lame.sourceforge.net/",
120 "http://www.libav.org/",
121 "http://www.linkedin.com/about-us",
122 "http://www.linuxmint.com/",
123 "http://www.livedoor.com/",
124 "http://www.livejournal.com/",
125 "http://go.mail.ru/",
126 "http://www.mediafire.com/",
127 "http://ftp.mozilla.org/",
128 "http://mplayerhq.hu/",
129 "http://www.msn.com/?st=1",
130 "http://oss.netfarm.it/",
131 "http://www.nytimes.com/",
132 "http://www.opera.com/",
133 "http://pastie.org/",
134 "http://www.portablefreeware.com/",
135 "http://qt-project.org/",
136 "http://www.quakelive.com/",
137 "http://www.seamonkey-project.org/",
138 "http://www.sina.com.cn/",
139 "http://www.sohu.com/",
140 "http://www.soso.com/",
141 "http://sourceforge.net/",
142 "http://www.spiegel.de/",
143 "http://tdm-gcc.tdragon.net/",
144 "http://www.tdrsmusic.com/",
145 "http://www.ubuntu.com/",
146 "http://status.twitter.com/",
147 "http://www.uol.com.br/",
148 "http://www.videohelp.com/",
149 "http://www.videolan.org/",
150 "http://virtualdub.org/",
151 "http://blog.virustotal.com/",
152 "http://weibo.com/login.php",
153 "http://www.wikipedia.org/",
154 "http://www.winamp.com/",
155 "http://wordpress.com/about/",
156 "http://xiph.org/",
157 "http://us.mail.yahoo.com/",
158 "http://www.yandex.ru/",
159 "http://www.youtube.com/yt/about/",
160 "http://www.zedo.com/",
161 "http://ffmpeg.zeranoe.com/",
162 NULL
165 static const int MIN_CONNSCORE = 8;
166 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
167 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
169 //Helper function
170 static int getMaxProgress(void)
172 int counter = MIN_CONNSCORE + 2;
173 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
174 for(int i = 0; update_mirrors_back[i]; i++) counter++;
175 return counter;
178 ////////////////////////////////////////////////////////////
179 // Update Info Class
180 ////////////////////////////////////////////////////////////
182 UpdateCheckerInfo::UpdateCheckerInfo(void)
184 resetInfo();
187 void UpdateCheckerInfo::resetInfo(void)
189 m_buildNo = 0;
190 m_buildDate.setDate(1900, 1, 1);
191 m_downloadSite.clear();
192 m_downloadAddress.clear();
193 m_downloadFilename.clear();
194 m_downloadFilecode.clear();
197 ////////////////////////////////////////////////////////////
198 // Constructor & Destructor
199 ////////////////////////////////////////////////////////////
201 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
203 m_updateInfo(new UpdateCheckerInfo()),
204 m_binaryWGet(binWGet),
205 m_binaryGnuPG(binGnuPG),
206 m_binaryKeys(binKeys),
207 m_applicationId(applicationId),
208 m_installedBuildNo(installedBuildNo),
209 m_betaUpdates(betaUpdates),
210 m_testMode(testMode),
211 m_maxProgress(getMaxProgress())
213 m_success = false;
214 m_status = UpdateStatus_NotStartedYet;
215 m_progress = 0;
217 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
219 MUTILS_THROW("Tools not initialized correctly!");
223 UpdateChecker::~UpdateChecker(void)
225 delete m_updateInfo;
228 ////////////////////////////////////////////////////////////
229 // Protected functions
230 ////////////////////////////////////////////////////////////
232 void UpdateChecker::run(void)
234 qDebug("Update checker thread started!");
235 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
236 qDebug("Update checker thread completed.");
239 void UpdateChecker::checkForUpdates(void)
241 // ----- Initialization ----- //
243 m_success = false;
244 m_updateInfo->resetInfo();
245 seed_rand();
246 setProgress(0);
248 // ----- Test Internet Connection ----- //
250 int connectionScore = 0;
251 int maxConnectTries = (3 * MIN_CONNSCORE) / 2;
253 log("Checking internet connection...");
254 setStatus(UpdateStatus_CheckingConnection);
256 const int networkStatus = OS::network_status();
257 if(networkStatus == OS::NETWORK_TYPE_NON)
259 log("", "Operating system reports that the computer is currently offline !!!");
260 setProgress(m_maxProgress);
261 setStatus(UpdateStatus_ErrorNoConnection);
262 return;
265 setProgress(1);
267 // ----- Test Known Hosts Connectivity ----- //
269 QStringList hostList;
270 for(int i = 0; known_hosts[i]; i++)
272 hostList << QString::fromLatin1(known_hosts[i]);
275 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
277 switch(tryContactHost(hostList.takeAt(next_rand32() % hostList.count())))
279 case 01: connectionScore += 1; break;
280 case 02: connectionScore += 2; break;
281 default: maxConnectTries -= 1; break;
283 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
284 msleep(64);
287 if(connectionScore < MIN_CONNSCORE)
289 log("", "Connectivity test has failed: Internet connection appears to be broken!");
290 setProgress(m_maxProgress);
291 setStatus(UpdateStatus_ErrorConnectionTestFailed);
292 return;
295 // ----- Build Mirror List ----- //
297 log("", "----", "", "Checking for updates online...");
298 setStatus(UpdateStatus_FetchingUpdates);
300 QStringList mirrorList;
301 for(int index = 0; update_mirrors_prim[index]; index++)
303 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
306 if(const int len = mirrorList.count())
308 const int rounds = len * 1097;
309 for(int i = 0; i < rounds; i++)
311 mirrorList.swap(i % len, next_rand32() % len);
315 for(int index = 0; update_mirrors_back[index]; index++)
317 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
320 // ----- Fetch Update Info From Server ----- //
322 while(!mirrorList.isEmpty())
324 QString currentMirror = mirrorList.takeFirst();
325 setProgress(m_progress + 1);
326 if(!m_success)
328 if(tryUpdateMirror(m_updateInfo, currentMirror))
330 m_success = true;
333 else
335 msleep(64);
339 setProgress(m_maxProgress);
341 if(m_success)
343 if(m_updateInfo->m_buildNo > m_installedBuildNo)
345 setStatus(UpdateStatus_CompletedUpdateAvailable);
347 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
349 setStatus(UpdateStatus_CompletedNoUpdates);
351 else
353 setStatus(UpdateStatus_CompletedNewVersionOlder);
356 else
358 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
362 void UpdateChecker::testKnownHosts(void)
364 QStringList hostList;
365 for(int i = 0; known_hosts[i]; i++)
367 hostList << QString::fromLatin1(known_hosts[i]);
370 qDebug("\n[Known Hosts]");
371 log("Testing all known hosts...", "", "---");
373 int hostCount = hostList.count();
374 while(!hostList.isEmpty())
376 QString currentHost = hostList.takeFirst();
377 qDebug("Testing: %s", currentHost.toLatin1().constData());
378 log("", "Testing:", currentHost, "");
379 QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
380 bool httpOk = false;
381 if(!getFile(currentHost, outFile, 0, &httpOk))
383 if(httpOk)
385 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
387 else
389 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
392 log("", "---");
393 QFile::remove(outFile);
397 ////////////////////////////////////////////////////////////
398 // PRIVATE FUNCTIONS
399 ////////////////////////////////////////////////////////////
401 void UpdateChecker::setStatus(const int status)
403 if(m_status != status)
405 m_status = status;
406 emit statusChanged(status);
410 void UpdateChecker::setProgress(const int progress)
412 if(m_progress != progress)
414 m_progress = progress;
415 emit progressChanged(progress);
419 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
421 if(!str1.isNull()) emit messageLogged(str1);
422 if(!str2.isNull()) emit messageLogged(str2);
423 if(!str3.isNull()) emit messageLogged(str3);
424 if(!str4.isNull()) emit messageLogged(str4);
427 int UpdateChecker::tryContactHost(const QString &url)
429 int result = -1; bool httpOkay = false;
430 const QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
431 log("", "Testing host:", url);
433 if(getFile(url, outFile, 0, &httpOkay))
435 log("Connection to host was established successfully.");
436 result = 2;
438 else
440 if(httpOkay)
442 log("Connection to host timed out after HTTP OK was received.");
443 result = 1;
445 else
447 log("Connection failed: The host could not be reached!");
448 result = 0;
452 QFile::remove(outFile);
453 return result;
456 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url)
458 bool success = false;
459 log("", "Trying mirror:", url);
461 const QString randPart = rand_str();
462 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
463 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
465 if(getUpdateInfo(url, outFileVers, outFileSign))
467 log("", "Download okay, checking signature:");
468 if(checkSignature(outFileVers, outFileSign))
470 log("", "Signature okay, parsing info:");
471 success = parseVersionInfo(outFileVers, updateInfo);
473 else
475 log("", "Bad signature, take care!");
478 else
480 log("", "Download has failed!");
483 QFile::remove(outFileVers);
484 QFile::remove(outFileSign);
486 return success;
489 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
491 log("", "Downloading update info:");
492 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
494 return false;
497 log("", "Downloading signature:");
498 if(!getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
500 return false;
503 return true;
506 bool UpdateChecker::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
508 QFileInfo output(outFile);
509 output.setCaching(false);
510 if(httpOk) *httpOk = false;
512 if(output.exists())
514 QFile::remove(output.canonicalFilePath());
515 if(output.exists())
517 return false;
521 QProcess process;
522 init_process(process, output.absolutePath());
524 QStringList args;
525 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
526 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
527 args << "-O" << output.fileName() << url;
529 QEventLoop loop;
530 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
531 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
532 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
534 QTimer timer;
535 timer.setSingleShot(true);
536 timer.setInterval(25000);
537 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
539 const QRegExp httpResponseOK("200 OK$");
541 process.start(m_binaryWGet, args);
543 if(!process.waitForStarted())
545 return false;
548 timer.start();
550 while(process.state() != QProcess::NotRunning)
552 loop.exec();
553 const bool bTimeOut = (!timer.isActive());
554 while(process.canReadLine())
556 QString line = QString::fromLatin1(process.readLine()).simplified();
557 if(line.contains(httpResponseOK))
559 line.append(" [OK]");
560 if(httpOk) *httpOk = true;
562 log(line);
564 if(bTimeOut)
566 qWarning("WGet process timed out <-- killing!");
567 process.kill();
568 process.waitForFinished();
569 log("!!! TIMEOUT !!!");
570 return false;
574 timer.stop();
575 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
577 log(QString().sprintf("Exited with code %d", process.exitCode()));
578 return (process.exitCode() == 0) && output.exists() && output.isFile();
581 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
583 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
585 qWarning("CheckSignature: File and signature should be in same folder!");
586 return false;
588 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
590 qWarning("CheckSignature: File and keyring should be in same folder!");
591 return false;
594 QProcess process;
595 init_process(process, QFileInfo(file).absolutePath());
597 QEventLoop loop;
598 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
599 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
600 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
602 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
604 if(!process.waitForStarted())
606 return false;
609 while(process.state() == QProcess::Running)
611 loop.exec();
612 while(process.canReadLine())
614 log(QString::fromLatin1(process.readLine()).simplified());
618 log(QString().sprintf("Exited with code %d", process.exitCode()));
619 return (process.exitCode() == 0);
622 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
624 QRegExp value("^(\\w+)=(.+)$");
625 QRegExp section("^\\[(.+)\\]$");
627 QDate updateInfoDate;
628 updateInfo->resetInfo();
630 QFile data(file);
631 if(!data.open(QIODevice::ReadOnly))
633 qWarning("Cannot open update info file for reading!");
634 return false;
637 bool inHdr = false;
638 bool inSec = false;
640 while(!data.atEnd())
642 QString line = QString::fromLatin1(data.readLine()).trimmed();
643 if(section.indexIn(line) >= 0)
645 log(QString("Sec: [%1]").arg(section.cap(1)));
646 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
647 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
648 continue;
650 if(inSec && (value.indexIn(line) >= 0))
652 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
653 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
655 bool ok = false;
656 unsigned int temp = value.cap(2).toUInt(&ok);
657 if(ok) updateInfo->m_buildNo = temp;
659 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
661 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
662 if(temp.isValid()) updateInfo->m_buildDate = temp;
664 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
666 updateInfo->m_downloadSite = value.cap(2).trimmed();
668 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
670 updateInfo->m_downloadAddress = value.cap(2).trimmed();
672 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
674 updateInfo->m_downloadFilename = value.cap(2).trimmed();
676 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
678 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
681 if(inHdr && (value.indexIn(line) >= 0))
683 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
684 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
686 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
687 if(temp.isValid()) updateInfoDate = temp;
692 if(!updateInfoDate.isValid())
694 updateInfo->resetInfo();
695 log("WARNING: Version info timestamp is missing!");
696 return false;
699 const QDate currentDate = OS::current_date();
700 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
702 updateInfo->resetInfo();
703 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
704 return false;
706 else if(currentDate < updateInfoDate)
708 log("Version info is from the future, take care!");
709 qWarning("Version info is from the future, take care!");
712 bool complete = true;
714 if(!(updateInfo->m_buildNo > 0)) complete = false;
715 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
716 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
717 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
718 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
719 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
721 if(!complete)
723 log("WARNING: Version info is incomplete!");
726 return complete;
729 ////////////////////////////////////////////////////////////
730 // SLOTS
731 ////////////////////////////////////////////////////////////
733 /*NONE*/
735 ////////////////////////////////////////////////////////////
736 // EVENTS
737 ////////////////////////////////////////////////////////////
739 /*NONE*/