1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program 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
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "thread_updater.h"
26 #include <QStringList>
34 ///////////////////////////////////////////////////////////////////////////////
36 ///////////////////////////////////////////////////////////////////////////////
38 static const char *header_id = "!Update";
39 static const char *section_id = "Simple x264 Launcher";
41 static const char *mirror_url_postfix[] =
48 static const char *update_mirrors_prim[] =
50 "http://muldersoft.com/",
51 "http://mulder.bplaced.net/",
52 "http://mulder.cwsurf.de/",
53 "http://mulder.6te.net/",
54 "http://mulder.webuda.com/",
55 "http://mulder.byethost13.com/",
56 "http://muldersoft.kilu.de/",
57 "http://mulder.pe.hu/",
58 "http://muldersoft.zxq.net/",
59 "http://lamexp.sourceforge.net/",
60 "http://lordmulder.github.io/LameXP/",
61 "http://lord_mulder.bitbucket.org/",
62 "http://www.tricksoft.de/",
66 static const char *update_mirrors_back[] =
68 "http://mplayer.savedonthe.net/",
72 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
74 "http://www.163.com/",
75 "http://www.7-zip.org/",
76 "http://www.ac3filter.net/",
77 "http://www.amazon.com/",
78 "http://antergos.com/",
79 "http://www.aol.com/",
80 "http://www.apache.org/",
81 "http://www.apple.com/",
82 "http://www.adobe.com/",
83 "http://www.avidemux.org/",
84 "http://www.babylon.com/",
85 "http://www.baidu.com/",
86 "http://bandcamp.com/",
87 "http://www.bbc.co.uk/",
88 "http://www.berlios.de/",
89 "http://www.bing.com/",
90 "http://www.bucketheadpikes.com/",
92 "http://www.cnet.com/",
94 "http://www.codeplex.com/",
95 "http://www.ebay.com/",
96 "http://www.equation.com/",
98 "http://fedoraproject.org/wiki/Fedora_Project_Wiki",
99 "http://blog.fefe.de/",
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/",
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/",
117 "http://kannmanumdieuhrzeitschonnbierchentrinken.de/",
118 "http://mirrors.kernel.org/",
119 "http://lame.sourceforge.net/",
120 "http://www.libav.org/",
121 "http://blog.linkedin.com/",
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/en-us/",
130 "http://oss.netfarm.it/",
131 "http://www.nytimes.com/",
132 "http://www.opera.com/",
133 "http://pastie.org/",
134 "http://www.portablefreeware.com/",
136 "http://qt-project.org/",
137 "http://www.quakelive.com/",
138 "http://www.seamonkey-project.org/",
139 "http://www.sina.com.cn/",
140 "http://www.sohu.com/",
141 "http://www.soso.com/",
142 "http://sourceforge.net/",
143 "http://www.spiegel.de/",
144 "http://tdm-gcc.tdragon.net/",
145 "http://www.tdrsmusic.com/",
146 "http://www.ubuntu.com/",
147 "http://status.twitter.com/",
148 "http://www.uol.com.br/",
149 "http://www.videohelp.com/",
150 "http://www.videolan.org/",
151 "http://virtualdub.org/",
152 "http://blog.virustotal.com/",
153 "http://www.weibo.com/login.php",
154 "http://www.wikipedia.org/",
155 "http://www.winamp.com/",
156 "http://en.support.wordpress.com/",
158 "http://us.mail.yahoo.com/",
159 "http://www.yandex.ru/",
160 "http://www.youtube.com/yt/about/",
161 "http://www.zedo.com/",
162 "http://ffmpeg.zeranoe.com/",
166 static const int MIN_CONNSCORE = 8;
167 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
168 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
171 static int getMaxProgress(void)
173 int counter = MIN_CONNSCORE + 2;
174 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
175 for(int i = 0; update_mirrors_back[i]; i++) counter++;
179 ////////////////////////////////////////////////////////////
181 ////////////////////////////////////////////////////////////
183 UpdateInfo::UpdateInfo(void)
188 void UpdateInfo::resetInfo(void)
191 m_buildDate.setDate(1900, 1, 1);
192 m_downloadSite.clear();
193 m_downloadAddress.clear();
194 m_downloadFilename.clear();
195 m_downloadFilecode.clear();
198 ////////////////////////////////////////////////////////////
199 // Constructor & Destructor
200 ////////////////////////////////////////////////////////////
202 UpdateCheckThread::UpdateCheckThread(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const bool betaUpdates, const bool testMode)
204 m_updateInfo(new UpdateInfo()),
205 m_binaryWGet(binWGet),
206 m_binaryGnuPG(binGnuPG),
207 m_binaryKeys(binKeys),
208 m_betaUpdates(betaUpdates),
209 m_testMode(testMode),
210 m_maxProgress(getMaxProgress())
213 m_status = UpdateStatus_NotStartedYet;
216 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
218 THROW("Tools not initialized correctly!");
222 UpdateCheckThread::~UpdateCheckThread(void)
227 ////////////////////////////////////////////////////////////
228 // Protected functions
229 ////////////////////////////////////////////////////////////
231 void UpdateCheckThread::run(void)
233 qDebug("Update checker thread started!");
237 m_testMode ? testKnownHosts() : checkForUpdates();
239 catch(const std::exception &error)
241 fflush(stdout); fflush(stderr);
242 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
243 x264_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
247 fflush(stdout); fflush(stderr);
248 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
249 x264_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
252 qDebug("Update checker thread completed.");
255 void UpdateCheckThread::checkForUpdates(void)
257 // ----- Initialization ----- //
260 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 = x264_network_status();
272 if(networkStatus == x264_network_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]);
292 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
294 switch(tryContactHost(hostList.takeAt(x264_rand() % hostList.count())))
296 case 01: connectionScore += 1; break;
297 case 02: connectionScore += 2; break;
298 default: maxConnectTries -= 1; break;
300 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
304 if(connectionScore < MIN_CONNSCORE)
306 log("", "Connectivity test has failed: Internet connection appears to be broken!");
307 setProgress(m_maxProgress);
308 setStatus(UpdateStatus_ErrorConnectionTestFailed);
312 // ----- Build Mirror List ----- //
314 log("", "----", "", "Checking for updates online...");
315 setStatus(UpdateStatus_FetchingUpdates);
317 QStringList mirrorList;
318 for(int index = 0; update_mirrors_prim[index]; index++)
320 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
324 if(const int len = mirrorList.count())
326 const int rounds = len * 1097;
327 for(int i = 0; i < rounds; i++)
329 mirrorList.swap(i % len, x264_rand() % len);
333 for(int index = 0; update_mirrors_back[index]; index++)
335 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
338 // ----- Fetch Update Info From Server ----- //
340 while(!mirrorList.isEmpty())
342 QString currentMirror = mirrorList.takeFirst();
343 setProgress(m_progress + 1);
346 if(tryUpdateMirror(m_updateInfo, currentMirror))
357 setProgress(m_maxProgress);
361 if(m_updateInfo->m_buildNo > x264_version_build())
363 setStatus(UpdateStatus_CompletedUpdateAvailable);
365 else if(m_updateInfo->m_buildNo == x264_version_build())
367 setStatus(UpdateStatus_CompletedNoUpdates);
371 setStatus(UpdateStatus_CompletedNewVersionOlder);
376 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
380 void UpdateCheckThread::testKnownHosts(void)
382 QStringList hostList;
383 for(int i = 0; known_hosts[i]; i++)
385 hostList << QString::fromLatin1(known_hosts[i]);
388 qDebug("\n[Known Hosts]");
389 log("Testing all known hosts...", "", "---");
391 int hostCount = hostList.count();
392 while(!hostList.isEmpty())
394 QString currentHost = hostList.takeFirst();
395 qDebug("Testing: %s", currentHost.toLatin1().constData());
396 log("", "Testing:", currentHost, "");
397 QString outFile = QString("%1/%2.htm").arg(x264_temp_directory(), x264_rand_str());
399 if(!getFile(currentHost, outFile, 0, &httpOk))
403 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
407 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
411 QFile::remove(outFile);
415 ////////////////////////////////////////////////////////////
417 ////////////////////////////////////////////////////////////
419 void UpdateCheckThread::setStatus(const int status)
421 if(m_status != status)
424 emit statusChanged(status);
428 void UpdateCheckThread::setProgress(const int progress)
430 if(m_progress != progress)
432 m_progress = progress;
433 emit progressChanged(progress);
437 void UpdateCheckThread::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
439 if(!str1.isNull()) emit messageLogged(str1);
440 if(!str2.isNull()) emit messageLogged(str2);
441 if(!str3.isNull()) emit messageLogged(str3);
442 if(!str4.isNull()) emit messageLogged(str4);
445 int UpdateCheckThread::tryContactHost(const QString &url)
447 int result = -1; bool httpOkay = false;
448 const QString outFile = QString("%1/%2.htm").arg(x264_temp_directory(), x264_rand_str());
449 log("", "Testing host:", url);
451 if(getFile(url, outFile, 0, &httpOkay))
453 log("Connection to host was established successfully.");
460 log("Connection to host timed out after HTTP OK was received.");
465 log("Connection failed: The host could not be reached!");
470 QFile::remove(outFile);
474 bool UpdateCheckThread::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
476 bool success = false;
477 log("", "Trying mirror:", url);
479 const QString randPart = x264_rand_str();
480 const QString outFileVers = QString("%1/%2.ver").arg(x264_temp_directory(), randPart);
481 const QString outFileSign = QString("%1/%2.sig").arg(x264_temp_directory(), randPart);
483 if(getUpdateInfo(url, outFileVers, outFileSign))
485 log("", "Download okay, checking signature:");
486 if(checkSignature(outFileVers, outFileSign))
488 log("", "Signature okay, parsing info:");
489 success = parseVersionInfo(outFileVers, updateInfo);
493 log("", "Bad signature, take care!");
498 log("", "Download has failed!");
501 QFile::remove(outFileVers);
502 QFile::remove(outFileSign);
507 bool UpdateCheckThread::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
509 log("", "Downloading update info:");
510 if(!getFile(QString("%1%2" ).arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVers))
515 log("", "Downloading signature:");
516 if(!getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSign))
524 bool UpdateCheckThread::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
526 QFileInfo output(outFile);
527 output.setCaching(false);
528 if(httpOk) *httpOk = false;
532 QFile::remove(output.canonicalFilePath());
540 x264_init_process(process, output.absolutePath());
543 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
544 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
545 args << "-O" << output.fileName() << url;
548 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
549 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
550 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
553 timer.setSingleShot(true);
554 timer.setInterval(25000);
555 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
557 const QRegExp httpResponseOK("200 OK$");
559 process.start(m_binaryWGet, args);
561 if(!process.waitForStarted())
568 while(process.state() != QProcess::NotRunning)
571 const bool bTimeOut = (!timer.isActive());
572 while(process.canReadLine())
574 QString line = QString::fromLatin1(process.readLine()).simplified();
575 if(line.contains(httpResponseOK))
577 line.append(" [OK]");
578 if(httpOk) *httpOk = true;
584 qWarning("WGet process timed out <-- killing!");
586 process.waitForFinished();
587 log("!!! TIMEOUT !!!");
593 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
595 log(QString().sprintf("Exited with code %d", process.exitCode()));
596 return (process.exitCode() == 0) && output.exists() && output.isFile();
599 bool UpdateCheckThread::checkSignature(const QString &file, const QString &signature)
601 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
603 qWarning("CheckSignature: File and signature should be in same folder!");
606 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
608 qWarning("CheckSignature: File and keyring should be in same folder!");
613 x264_init_process(process, QFileInfo(file).absolutePath());
616 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
617 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
618 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
620 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
622 if(!process.waitForStarted())
627 while(process.state() == QProcess::Running)
630 while(process.canReadLine())
632 log(QString::fromLatin1(process.readLine()).simplified());
636 log(QString().sprintf("Exited with code %d", process.exitCode()));
637 return (process.exitCode() == 0);
640 bool UpdateCheckThread::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
642 QRegExp value("^(\\w+)=(.+)$");
643 QRegExp section("^\\[(.+)\\]$");
645 QDate updateInfoDate;
646 updateInfo->resetInfo();
649 if(!data.open(QIODevice::ReadOnly))
651 qWarning("Cannot open update info file for reading!");
655 bool inHeader = false;
656 bool inSection = false;
660 QString line = QString::fromLatin1(data.readLine()).trimmed();
661 if(section.indexIn(line) >= 0)
663 log(QString("Sec: [%1]").arg(section.cap(1)));
664 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
665 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
668 if(inSection && (value.indexIn(line) >= 0))
670 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
671 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
674 unsigned int temp = value.cap(2).toUInt(&ok);
675 if(ok) updateInfo->m_buildNo = temp;
677 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
679 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
680 if(temp.isValid()) updateInfo->m_buildDate = temp;
682 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
684 updateInfo->m_downloadSite = value.cap(2).trimmed();
686 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
688 updateInfo->m_downloadAddress = value.cap(2).trimmed();
690 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
692 updateInfo->m_downloadFilename = value.cap(2).trimmed();
694 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
696 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
699 if(inHeader && (value.indexIn(line) >= 0))
701 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
702 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
704 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
705 if(temp.isValid()) updateInfoDate = temp;
710 if(!updateInfoDate.isValid())
712 updateInfo->resetInfo();
713 log("WARNING: Version info timestamp is missing!");
716 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < x264_current_date_safe())
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(x264_current_date_safe() < 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 ////////////////////////////////////////////////////////////