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();
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())
229 m_status
= UpdateStatus_NotStartedYet
;
232 if(m_binaryWGet
.isEmpty() || m_binaryGnuPG
.isEmpty() || m_binaryKeys
.isEmpty())
234 MUTILS_THROW("Tools not initialized correctly!");
238 UpdateChecker::~UpdateChecker(void)
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 ----- //
259 m_updateInfo
->resetInfo();
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
);
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));
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
);
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);
343 if(tryUpdateMirror(m_updateInfo
, currentMirror
))
354 setProgress(m_maxProgress
);
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
);
368 setStatus(UpdateStatus_CompletedNewVersionOlder
);
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());
396 if(!getFile(currentHost
, outFile
, 0, &httpOk
))
400 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost
.toLatin1().constData());
404 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost
.toLatin1().constData());
408 QFile::remove(outFile
);
412 ////////////////////////////////////////////////////////////
414 ////////////////////////////////////////////////////////////
416 void UpdateChecker::setStatus(const int status
)
418 if(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.");
457 log("Connection to host timed out after HTTP OK was received.");
462 log("Connection failed: The host could not be reached!");
467 QFile::remove(outFile
);
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
);
490 log("", "Bad signature, take care!");
495 log("", "Download has failed!");
498 QFile::remove(outFileVers
);
499 QFile::remove(outFileSign
);
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
))
512 log("", "Downloading signature:");
513 if(!getFile(QString("%1%2.sig").arg(url
, mirror_url_postfix
[m_betaUpdates
? 1 : 0]), outFileSign
))
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;
529 QFile::remove(output
.canonicalFilePath());
537 init_process(process
, output
.absolutePath());
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
;
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()));
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())
565 while(process
.state() != QProcess::NotRunning
)
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;
581 qWarning("WGet process timed out <-- killing!");
583 process
.waitForFinished();
584 log("!!! TIMEOUT !!!");
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!");
604 if(QFileInfo(file
).absolutePath().compare(QFileInfo(m_binaryKeys
).absolutePath(), Qt::CaseInsensitive
) != 0)
606 qWarning("CheckSignature: File and keyring should be in same folder!");
611 init_process(process
, QFileInfo(file
).absolutePath());
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())
625 while(process
.state() == QProcess::Running
)
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();
647 if(!data
.open(QIODevice::ReadOnly
))
649 qWarning("Cannot open update info file for reading!");
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);
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)
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!");
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
)));
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;
739 log("WARNING: Version info is incomplete!");
745 ////////////////////////////////////////////////////////////
747 ////////////////////////////////////////////////////////////
751 ////////////////////////////////////////////////////////////
753 ////////////////////////////////////////////////////////////