Added project/solution files for Visual Studio 2010.
[MUtilities.git] / src / UpdateChecker.cpp
blob173fde7b9297a48d4434b37150f4f3b55ea4e06e
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/",
57 "http://mulder.byethost13.com/",
58 "http://muldersoft.kilu.de/",
59 "http://mulder.pe.hu/",
60 "http://muldersoft.square7.ch/", //"http://muldersoft.zxq.net/",
61 "http://muldersoft.co.nf/",
62 "http://muldersoft.eu.pn/",
63 "http://lamexp.sourceforge.net/",
64 "http://lordmulder.github.io/LameXP/",
65 "http://lord_mulder.bitbucket.org/",
66 "http://www.tricksoft.de/",
67 NULL
70 static const char *update_mirrors_back[] =
72 "http://mplayer.savedonthe.net/",
73 NULL
76 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
78 "http://www.163.com/",
79 "http://www.7-zip.org/",
80 "http://www.ac3filter.net/",
81 "http://www.amazon.com/",
82 "http://antergos.com/",
83 "http://www.aol.com/",
84 "http://www.apache.org/",
85 "http://www.apple.com/",
86 "http://www.adobe.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.cnet.com/",
97 "http://cnzz.com/",
98 "http://www.codeplex.com/",
99 "http://www.ebay.com/",
100 "http://www.equation.com/",
101 "http://fc2.com/",
102 "http://fedoraproject.org/wiki/Fedora_Project_Wiki",
103 "http://blog.fefe.de/",
104 "http://www.ffmpeg.org/",
105 "http://blog.flickr.net/en",
106 "http://free-codecs.com/",
107 "http://blog.gitorious.org/",
108 "http://git-scm.com/",
109 "http://www.gmx.net/",
110 "http://www.gnome.org/",
111 "http://www.gnu.org/",
112 "http://go.com/",
113 "http://code.google.com/",
114 "http://www.heise.de/",
115 "http://www.huffingtonpost.co.uk/",
116 "http://www.iana.org/",
117 "http://www.imdb.com/",
118 "http://www.imgburn.com/",
119 "http://imgur.com/",
120 "http://en.jd.com/",
121 "http://kannmanumdieuhrzeitschonnbierchentrinken.de/",
122 "http://mirrors.kernel.org/",
123 "http://lame.sourceforge.net/",
124 "http://www.libav.org/",
125 "http://blog.linkedin.com/",
126 "http://www.linuxmint.com/",
127 "http://www.livedoor.com/",
128 "http://www.livejournal.com/",
129 "http://go.mail.ru/",
130 "http://www.mediafire.com/",
131 "http://ftp.mozilla.org/",
132 "http://mplayerhq.hu/",
133 "http://www.msn.com/en-us/",
134 "http://oss.netfarm.it/",
135 "http://www.nytimes.com/",
136 "http://www.opera.com/",
137 "http://pastie.org/",
138 "http://www.portablefreeware.com/",
139 "http://www.qt.io/",
140 "http://qt-project.org/",
141 "http://www.quakelive.com/",
142 "http://www.seamonkey-project.org/",
143 "http://www.sina.com.cn/",
144 "http://www.sohu.com/",
145 "http://www.sogou.com/",
146 "http://sourceforge.net/",
147 "http://www.spiegel.de/",
148 "http://tdm-gcc.tdragon.net/",
149 "http://www.tdrsmusic.com/",
150 "http://www.ubuntu.com/",
151 "http://status.twitter.com/",
152 "http://www.uol.com.br/",
153 "http://www.videohelp.com/",
154 "http://www.videolan.org/",
155 "http://virtualdub.org/",
156 "http://blog.virustotal.com/",
157 "http://www.weibo.com/login.php",
158 "http://www.wikipedia.org/",
159 "http://www.winamp.com/",
160 "http://en.support.wordpress.com/",
161 "http://xiph.org/",
162 "http://us.mail.yahoo.com/",
163 "http://www.yandex.ru/",
164 "http://www.youtube.com/yt/about/",
165 "http://www.zedo.com/",
166 "http://ffmpeg.zeranoe.com/",
167 NULL
170 static const int MIN_CONNSCORE = 8;
171 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
172 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
174 //Helper function
175 static int getMaxProgress(void)
177 int counter = MIN_CONNSCORE + 2;
178 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
179 for(int i = 0; update_mirrors_back[i]; i++) counter++;
180 return counter;
183 ////////////////////////////////////////////////////////////
184 // Update Info Class
185 ////////////////////////////////////////////////////////////
187 UpdateCheckerInfo::UpdateCheckerInfo(void)
189 resetInfo();
192 void UpdateCheckerInfo::resetInfo(void)
194 m_buildNo = 0;
195 m_buildDate.setDate(1900, 1, 1);
196 m_downloadSite.clear();
197 m_downloadAddress.clear();
198 m_downloadFilename.clear();
199 m_downloadFilecode.clear();
202 ////////////////////////////////////////////////////////////
203 // Constructor & Destructor
204 ////////////////////////////////////////////////////////////
206 UpdateChecker::UpdateChecker(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
208 m_updateInfo(new UpdateCheckerInfo()),
209 m_binaryWGet(binWGet),
210 m_binaryGnuPG(binGnuPG),
211 m_binaryKeys(binKeys),
212 m_applicationId(applicationId),
213 m_installedBuildNo(installedBuildNo),
214 m_betaUpdates(betaUpdates),
215 m_testMode(testMode),
216 m_maxProgress(getMaxProgress())
218 m_success = false;
219 m_status = UpdateStatus_NotStartedYet;
220 m_progress = 0;
222 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
224 MUTILS_THROW("Tools not initialized correctly!");
228 UpdateChecker::~UpdateChecker(void)
230 delete m_updateInfo;
233 ////////////////////////////////////////////////////////////
234 // Protected functions
235 ////////////////////////////////////////////////////////////
237 void UpdateChecker::run(void)
239 qDebug("Update checker thread started!");
240 MUTILS_EXCEPTION_HANDLER(m_testMode ? testKnownHosts() : checkForUpdates());
241 qDebug("Update checker thread completed.");
244 void UpdateChecker::checkForUpdates(void)
246 // ----- Initialization ----- //
248 m_success = false;
249 m_updateInfo->resetInfo();
250 seed_rand();
251 setProgress(0);
253 // ----- Test Internet Connection ----- //
255 int connectionScore = 0;
256 int maxConnectTries = (3 * MIN_CONNSCORE) / 2;
258 log("Checking internet connection...");
259 setStatus(UpdateStatus_CheckingConnection);
261 const int networkStatus = OS::network_status();
262 if(networkStatus == OS::NETWORK_TYPE_NON)
264 log("", "Operating system reports that the computer is currently offline !!!");
265 setProgress(m_maxProgress);
266 setStatus(UpdateStatus_ErrorNoConnection);
267 return;
270 setProgress(1);
272 // ----- Test Known Hosts Connectivity ----- //
274 QStringList hostList;
275 for(int i = 0; known_hosts[i]; i++)
277 hostList << QString::fromLatin1(known_hosts[i]);
280 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
282 switch(tryContactHost(hostList.takeAt(next_rand32() % hostList.count())))
284 case 01: connectionScore += 1; break;
285 case 02: connectionScore += 2; break;
286 default: maxConnectTries -= 1; break;
288 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
289 msleep(64);
292 if(connectionScore < MIN_CONNSCORE)
294 log("", "Connectivity test has failed: Internet connection appears to be broken!");
295 setProgress(m_maxProgress);
296 setStatus(UpdateStatus_ErrorConnectionTestFailed);
297 return;
300 // ----- Build Mirror List ----- //
302 log("", "----", "", "Checking for updates online...");
303 setStatus(UpdateStatus_FetchingUpdates);
305 QStringList mirrorList;
306 for(int index = 0; update_mirrors_prim[index]; index++)
308 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
311 if(const int len = mirrorList.count())
313 const int rounds = len * 1097;
314 for(int i = 0; i < rounds; i++)
316 mirrorList.swap(i % len, next_rand32() % len);
320 for(int index = 0; update_mirrors_back[index]; index++)
322 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
325 // ----- Fetch Update Info From Server ----- //
327 while(!mirrorList.isEmpty())
329 QString currentMirror = mirrorList.takeFirst();
330 setProgress(m_progress + 1);
331 if(!m_success)
333 if(tryUpdateMirror(m_updateInfo, currentMirror))
335 m_success = true;
338 else
340 msleep(64);
344 setProgress(m_maxProgress);
346 if(m_success)
348 if(m_updateInfo->m_buildNo > m_installedBuildNo)
350 setStatus(UpdateStatus_CompletedUpdateAvailable);
352 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
354 setStatus(UpdateStatus_CompletedNoUpdates);
356 else
358 setStatus(UpdateStatus_CompletedNewVersionOlder);
361 else
363 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
367 void UpdateChecker::testKnownHosts(void)
369 QStringList hostList;
370 for(int i = 0; known_hosts[i]; i++)
372 hostList << QString::fromLatin1(known_hosts[i]);
375 qDebug("\n[Known Hosts]");
376 log("Testing all known hosts...", "", "---");
378 int hostCount = hostList.count();
379 while(!hostList.isEmpty())
381 QString currentHost = hostList.takeFirst();
382 qDebug("Testing: %s", currentHost.toLatin1().constData());
383 log("", "Testing:", currentHost, "");
384 QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
385 bool httpOk = false;
386 if(!getFile(currentHost, outFile, 0, &httpOk))
388 if(httpOk)
390 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
392 else
394 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
397 log("", "---");
398 QFile::remove(outFile);
402 ////////////////////////////////////////////////////////////
403 // PRIVATE FUNCTIONS
404 ////////////////////////////////////////////////////////////
406 void UpdateChecker::setStatus(const int status)
408 if(m_status != status)
410 m_status = status;
411 emit statusChanged(status);
415 void UpdateChecker::setProgress(const int progress)
417 if(m_progress != progress)
419 m_progress = progress;
420 emit progressChanged(progress);
424 void UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
426 if(!str1.isNull()) emit messageLogged(str1);
427 if(!str2.isNull()) emit messageLogged(str2);
428 if(!str3.isNull()) emit messageLogged(str3);
429 if(!str4.isNull()) emit messageLogged(str4);
432 int UpdateChecker::tryContactHost(const QString &url)
434 int result = -1; bool httpOkay = false;
435 const QString outFile = QString("%1/%2.htm").arg(temp_folder(), rand_str());
436 log("", "Testing host:", url);
438 if(getFile(url, outFile, 0, &httpOkay))
440 log("Connection to host was established successfully.");
441 result = 2;
443 else
445 if(httpOkay)
447 log("Connection to host timed out after HTTP OK was received.");
448 result = 1;
450 else
452 log("Connection failed: The host could not be reached!");
453 result = 0;
457 QFile::remove(outFile);
458 return result;
461 bool UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url)
463 bool success = false;
464 log("", "Trying mirror:", url);
466 const QString randPart = rand_str();
467 const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
468 const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
470 if(getUpdateInfo(url, outFileVers, outFileSign))
472 log("", "Download okay, checking signature:");
473 if(checkSignature(outFileVers, outFileSign))
475 log("", "Signature okay, parsing info:");
476 success = parseVersionInfo(outFileVers, updateInfo);
478 else
480 log("", "Bad signature, take care!");
483 else
485 log("", "Download has failed!");
488 QFile::remove(outFileVers);
489 QFile::remove(outFileSign);
491 return success;
494 bool UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
496 log("", "Downloading update info:");
497 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
499 return false;
502 log("", "Downloading signature:");
503 if(!getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
505 return false;
508 return true;
511 bool UpdateChecker::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
513 QFileInfo output(outFile);
514 output.setCaching(false);
515 if(httpOk) *httpOk = false;
517 if(output.exists())
519 QFile::remove(output.canonicalFilePath());
520 if(output.exists())
522 return false;
526 QProcess process;
527 init_process(process, output.absolutePath());
529 QStringList args;
530 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
531 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
532 args << "-O" << output.fileName() << url;
534 QEventLoop loop;
535 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
536 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
537 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
539 QTimer timer;
540 timer.setSingleShot(true);
541 timer.setInterval(25000);
542 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
544 const QRegExp httpResponseOK("200 OK$");
546 process.start(m_binaryWGet, args);
548 if(!process.waitForStarted())
550 return false;
553 timer.start();
555 while(process.state() != QProcess::NotRunning)
557 loop.exec();
558 const bool bTimeOut = (!timer.isActive());
559 while(process.canReadLine())
561 QString line = QString::fromLatin1(process.readLine()).simplified();
562 if(line.contains(httpResponseOK))
564 line.append(" [OK]");
565 if(httpOk) *httpOk = true;
567 log(line);
569 if(bTimeOut)
571 qWarning("WGet process timed out <-- killing!");
572 process.kill();
573 process.waitForFinished();
574 log("!!! TIMEOUT !!!");
575 return false;
579 timer.stop();
580 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
582 log(QString().sprintf("Exited with code %d", process.exitCode()));
583 return (process.exitCode() == 0) && output.exists() && output.isFile();
586 bool UpdateChecker::checkSignature(const QString &file, const QString &signature)
588 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
590 qWarning("CheckSignature: File and signature should be in same folder!");
591 return false;
594 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
596 qWarning("CheckSignature: File and keyring should be in same folder!");
597 return false;
600 QProcess process;
601 init_process(process, QFileInfo(file).absolutePath());
603 QEventLoop loop;
604 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
605 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
606 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
608 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
610 if(!process.waitForStarted())
612 return false;
615 while(process.state() == QProcess::Running)
617 loop.exec();
618 while(process.canReadLine())
620 log(QString::fromLatin1(process.readLine()).simplified());
624 log(QString().sprintf("Exited with code %d", process.exitCode()));
625 return (process.exitCode() == 0);
628 bool UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
630 QRegExp value("^(\\w+)=(.+)$");
631 QRegExp section("^\\[(.+)\\]$");
633 QDate updateInfoDate;
634 updateInfo->resetInfo();
636 QFile data(file);
637 if(!data.open(QIODevice::ReadOnly))
639 qWarning("Cannot open update info file for reading!");
640 return false;
643 bool inHdr = false;
644 bool inSec = false;
646 while(!data.atEnd())
648 QString line = QString::fromLatin1(data.readLine()).trimmed();
649 if(section.indexIn(line) >= 0)
651 log(QString("Sec: [%1]").arg(section.cap(1)));
652 inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
653 inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
654 continue;
656 if(inSec && (value.indexIn(line) >= 0))
658 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
659 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
661 bool ok = false;
662 unsigned int temp = value.cap(2).toUInt(&ok);
663 if(ok) updateInfo->m_buildNo = temp;
665 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
667 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
668 if(temp.isValid()) updateInfo->m_buildDate = temp;
670 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
672 updateInfo->m_downloadSite = value.cap(2).trimmed();
674 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
676 updateInfo->m_downloadAddress = value.cap(2).trimmed();
678 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
680 updateInfo->m_downloadFilename = value.cap(2).trimmed();
682 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
684 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
687 if(inHdr && (value.indexIn(line) >= 0))
689 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
690 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
692 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
693 if(temp.isValid()) updateInfoDate = temp;
698 if(!updateInfoDate.isValid())
700 updateInfo->resetInfo();
701 log("WARNING: Version info timestamp is missing!");
702 return false;
705 const QDate currentDate = OS::current_date();
706 if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
708 updateInfo->resetInfo();
709 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
710 return false;
712 else if(currentDate < updateInfoDate)
714 log("Version info is from the future, take care!");
715 qWarning("Version info is from the future, take care!");
718 bool complete = true;
720 if(!(updateInfo->m_buildNo > 0)) complete = false;
721 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
722 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
723 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
724 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
725 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
727 if(!complete)
729 log("WARNING: Version info is incomplete!");
732 return complete;
735 ////////////////////////////////////////////////////////////
736 // SLOTS
737 ////////////////////////////////////////////////////////////
739 /*NONE*/
741 ////////////////////////////////////////////////////////////
742 // EVENTS
743 ////////////////////////////////////////////////////////////
745 /*NONE*/