Updated SoX binary to v14.4.2-Git (2014-10-06), compiled with ICL 15.0 and MSVC 12.0.
[LameXP.git] / src / Thread_CheckUpdate.cpp
blobe7d68a41142a3c20578cd34915665f506e1d087c
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Thread_CheckUpdate.h"
25 #include "Global.h"
27 #include <QStringList>
28 #include <QFile>
29 #include <QFileInfo>
30 #include <QProcess>
31 #include <QUrl>
32 #include <QEventLoop>
33 #include <QTimer>
35 ///////////////////////////////////////////////////////////////////////////////
36 // CONSTANTS
37 ///////////////////////////////////////////////////////////////////////////////
39 static const char *header_id = "!Update";
40 static const char *section_id = "LameXP";
42 static const char *mirror_url_postfix[] =
44 "update.ver",
45 "update_beta.ver",
46 NULL
49 static const char *update_mirrors_prim[] =
51 "http://muldersoft.com/",
52 "http://mulder.bplaced.net/",
53 "http://mulder.cwsurf.de/",
54 "http://mulder.6te.net/",
55 "http://mulder.webuda.com/",
56 "http://mulder.byethost13.com/",
57 "http://muldersoft.kilu.de/",
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/",
63 NULL
66 static const char *update_mirrors_back[] =
68 "http://mplayer.savedonthe.net/",
69 NULL
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.cnet.com/",
91 "http://cnzz.com/",
92 "http://www.codeplex.com/",
93 "http://qt.digia.com/",
94 "http://www.ebay.com/",
95 "http://www.equation.com/",
96 "http://fc2.com/",
97 "http://fedoraproject.org/",
98 "http://www.ffmpeg.org/",
99 "http://blog.flickr.net/en",
100 "http://free-codecs.com/",
101 "http://blog.gitorious.org/",
102 "http://git-scm.com/",
103 "http://www.gmx.net/",
104 "http://www.gnome.org/",
105 "http://www.gnu.org/",
106 "http://go.com/",
107 "http://code.google.com/",
108 "http://www.heise.de/",
109 "http://www.huffingtonpost.co.uk/",
110 "http://www.iana.org/",
111 "http://www.imdb.com/",
112 "http://www.imgburn.com/",
113 "http://imgur.com/",
114 "http://en.jd.com/",
115 "http://kannmanumdieuhrzeitschonnbierchentrinken.de/",
116 "http://mirrors.kernel.org/",
117 "http://lame.sourceforge.net/",
118 "http://www.libav.org/",
119 "http://www.linkedin.com/about-us",
120 "http://www.linuxmint.com/",
121 "http://www.livedoor.com/",
122 "http://www.livejournal.com/",
123 "http://go.mail.ru/",
124 "http://www.mediafire.com/",
125 "http://ftp.mozilla.org/",
126 "http://mplayerhq.hu/",
127 "http://www.msn.com/?st=1",
128 "http://oss.netfarm.it/",
129 "http://www.nytimes.com/",
130 "http://www.opera.com/",
131 "http://pastie.org/",
132 "http://www.portablefreeware.com/",
133 "http://qt-project.org/",
134 "http://www.quakelive.com/",
135 "http://www.seamonkey-project.org/",
136 "http://www.sina.com.cn/",
137 "http://www.sohu.com/",
138 "http://www.soso.com/",
139 "http://sourceforge.net/",
140 "http://www.spiegel.de/",
141 "http://tdm-gcc.tdragon.net/",
142 "http://www.tdrsmusic.com/",
143 "http://www.ubuntu.com/",
144 "http://status.twitter.com/",
145 "http://www.uol.com.br/",
146 "http://www.videohelp.com/",
147 "http://www.videolan.org/",
148 "http://virtualdub.org/",
149 "http://blog.virustotal.com/",
150 "http://weibo.com/login.php",
151 "http://www.wikipedia.org/",
152 "http://www.winamp.com/",
153 "http://wordpress.com/about/",
154 "http://xiph.org/",
155 "http://us.mail.yahoo.com/",
156 "http://www.yandex.ru/",
157 "http://www.youtube.com/yt/about/",
158 "http://www.zedo.com/",
159 "http://ffmpeg.zeranoe.com/",
160 NULL
163 static const int MIN_CONNSCORE = 8;
164 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
165 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
167 //Helper function
168 static int getMaxProgress(void)
170 int counter = MIN_CONNSCORE + 2;
171 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
172 for(int i = 0; update_mirrors_back[i]; i++) counter++;
173 return counter;
176 ////////////////////////////////////////////////////////////
177 // Update Info Class
178 ////////////////////////////////////////////////////////////
180 UpdateInfo::UpdateInfo(void)
182 resetInfo();
185 void UpdateInfo::resetInfo(void)
187 m_buildNo = 0;
188 m_buildDate.setDate(1900, 1, 1);
189 m_downloadSite.clear();
190 m_downloadAddress.clear();
191 m_downloadFilename.clear();
192 m_downloadFilecode.clear();
195 ////////////////////////////////////////////////////////////
196 // Constructor & Destructor
197 ////////////////////////////////////////////////////////////
199 UpdateCheckThread::UpdateCheckThread(const QString &binWGet, const QString &binGnuPG, const QString &binKeys, const bool betaUpdates, const bool testMode)
201 m_updateInfo(new UpdateInfo()),
202 m_binaryWGet(binWGet),
203 m_binaryGnuPG(binGnuPG),
204 m_binaryKeys(binKeys),
205 m_betaUpdates(betaUpdates),
206 m_testMode(testMode),
207 m_maxProgress(getMaxProgress())
209 m_success = false;
210 m_status = UpdateStatus_NotStartedYet;
211 m_progress = 0;
213 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
215 THROW("Tools not initialized correctly!");
219 UpdateCheckThread::~UpdateCheckThread(void)
221 delete m_updateInfo;
224 ////////////////////////////////////////////////////////////
225 // Protected functions
226 ////////////////////////////////////////////////////////////
228 void UpdateCheckThread::run(void)
230 qDebug("Update checker thread started!");
234 m_testMode ? testKnownHosts() : checkForUpdates();
236 catch(const std::exception &error)
238 PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
239 lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
241 catch(...)
243 PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
244 lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
247 qDebug("Update checker thread completed.");
250 void UpdateCheckThread::checkForUpdates(void)
252 // ----- Initialization ----- //
254 m_success = false;
255 m_updateInfo->resetInfo();
256 setProgress(0);
258 // ----- Test Internet Connection ----- //
260 int connectionScore = 0;
261 int maxConnectTries = (3 * MIN_CONNSCORE) / 2;
263 log("Checking internet connection...");
264 setStatus(UpdateStatus_CheckingConnection);
266 const int networkStatus = lamexp_network_status();
267 if(networkStatus == lamexp_network_non)
269 log("", "Operating system reports that the computer is currently offline !!!");
270 setProgress(m_maxProgress);
271 setStatus(UpdateStatus_ErrorNoConnection);
272 return;
275 setProgress(1);
277 // ----- Test Known Hosts Connectivity ----- //
279 QStringList hostList;
280 for(int i = 0; known_hosts[i]; i++)
282 hostList << QString::fromLatin1(known_hosts[i]);
285 lamexp_seed_rand();
287 while(!(hostList.isEmpty() || (connectionScore >= MIN_CONNSCORE) || (maxConnectTries < 1)))
289 switch(tryContactHost(hostList.takeAt(lamexp_rand() % hostList.count())))
291 case 01: connectionScore += 1; break;
292 case 02: connectionScore += 2; break;
293 default: maxConnectTries -= 1; break;
295 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
296 lamexp_sleep(64);
299 if(connectionScore < MIN_CONNSCORE)
301 log("", "Connectivity test has failed: Internet connection appears to be broken!");
302 setProgress(m_maxProgress);
303 setStatus(UpdateStatus_ErrorConnectionTestFailed);
304 return;
307 // ----- Build Mirror List ----- //
309 log("", "----", "", "Checking for updates online...");
310 setStatus(UpdateStatus_FetchingUpdates);
312 QStringList mirrorList;
313 for(int index = 0; update_mirrors_prim[index]; index++)
315 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
318 lamexp_seed_rand();
319 if(const int len = mirrorList.count())
321 const int rounds = len * 1097;
322 for(int i = 0; i < rounds; i++)
324 mirrorList.swap(i % len, lamexp_rand() % len);
328 for(int index = 0; update_mirrors_back[index]; index++)
330 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
333 // ----- Fetch Update Info From Server ----- //
335 while(!mirrorList.isEmpty())
337 QString currentMirror = mirrorList.takeFirst();
338 setProgress(m_progress + 1);
339 if(!m_success)
341 if(tryUpdateMirror(m_updateInfo, currentMirror))
343 m_success = true;
346 else
348 lamexp_sleep(64);
352 setProgress(m_maxProgress);
354 if(m_success)
356 if(m_updateInfo->m_buildNo > lamexp_version_build())
358 setStatus(UpdateStatus_CompletedUpdateAvailable);
360 else if(m_updateInfo->m_buildNo == lamexp_version_build())
362 setStatus(UpdateStatus_CompletedNoUpdates);
364 else
366 setStatus(UpdateStatus_CompletedNewVersionOlder);
369 else
371 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
375 void UpdateCheckThread::testKnownHosts(void)
377 QStringList hostList;
378 for(int i = 0; known_hosts[i]; i++)
380 hostList << QString::fromLatin1(known_hosts[i]);
383 qDebug("\n[Known Hosts]");
384 log("Testing all known hosts...", "", "---");
386 int hostCount = hostList.count();
387 while(!hostList.isEmpty())
389 QString currentHost = hostList.takeFirst();
390 qDebug("Testing: %s", currentHost.toLatin1().constData());
391 log("", "Testing:", currentHost, "");
392 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
393 bool httpOk = false;
394 if(!getFile(currentHost, outFile, 0, &httpOk))
396 if(httpOk)
398 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost.toLatin1().constData());
400 else
402 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost.toLatin1().constData());
405 log("", "---");
406 QFile::remove(outFile);
410 ////////////////////////////////////////////////////////////
411 // PRIVATE FUNCTIONS
412 ////////////////////////////////////////////////////////////
414 void UpdateCheckThread::setStatus(const int status)
416 if(m_status != status)
418 m_status = status;
419 emit statusChanged(status);
423 void UpdateCheckThread::setProgress(const int progress)
425 if(m_progress != progress)
427 m_progress = progress;
428 emit progressChanged(progress);
432 void UpdateCheckThread::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
434 if(!str1.isNull()) emit messageLogged(str1);
435 if(!str2.isNull()) emit messageLogged(str2);
436 if(!str3.isNull()) emit messageLogged(str3);
437 if(!str4.isNull()) emit messageLogged(str4);
440 int UpdateCheckThread::tryContactHost(const QString &url)
442 int result = -1; bool httpOkay = false;
443 const QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
444 log("", "Testing host:", url);
446 if(getFile(url, outFile, 0, &httpOkay))
448 log("Connection to host was established successfully.");
449 result = 2;
451 else
453 if(httpOkay)
455 log("Connection to host timed out after HTTP OK was received.");
456 result = 1;
458 else
460 log("Connection failed: The host could not be reached!");
461 result = 0;
465 QFile::remove(outFile);
466 return result;
469 bool UpdateCheckThread::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
471 bool success = false;
472 log("", "Trying mirror:", url);
474 QString randPart = lamexp_rand_str();
475 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
476 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
478 log("", "Downloading update info:");
479 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
481 log("", "Downloading signature:");
482 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
484 if(ok1 && ok2)
486 log("", "Download okay, checking signature:");
487 if(checkSignature(outFileVersionInfo, outFileSignature))
489 log("", "Signature okay, parsing info:");
490 success = parseVersionInfo(outFileVersionInfo, updateInfo);
492 else
494 log("", "Bad signature, take care!");
497 else
499 log("", "Download has failed!");
502 QFile::remove(outFileVersionInfo);
503 QFile::remove(outFileSignature);
505 return success;
508 bool UpdateCheckThread::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
510 QFileInfo output(outFile);
511 output.setCaching(false);
512 if(httpOk) *httpOk = false;
514 if(output.exists())
516 QFile::remove(output.canonicalFilePath());
517 if(output.exists())
519 return false;
523 QProcess process;
524 lamexp_init_process(process, output.absolutePath());
526 QStringList args;
527 args << "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
528 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
529 args << "-O" << output.fileName() << url;
531 QEventLoop loop;
532 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
533 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
534 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
536 QTimer timer;
537 timer.setSingleShot(true);
538 timer.setInterval(25000);
539 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
541 const QRegExp httpResponseOK("200 OK$");
543 process.start(m_binaryWGet, args);
545 if(!process.waitForStarted())
547 return false;
550 timer.start();
552 while(process.state() != QProcess::NotRunning)
554 loop.exec();
555 const bool bTimeOut = (!timer.isActive());
556 while(process.canReadLine())
558 QString line = QString::fromLatin1(process.readLine()).simplified();
559 if(line.contains(httpResponseOK))
561 line.append(" [OK]");
562 if(httpOk) *httpOk = true;
564 log(line);
566 if(bTimeOut)
568 qWarning("WGet process timed out <-- killing!");
569 process.kill();
570 process.waitForFinished();
571 log("!!! TIMEOUT !!!");
572 return false;
576 timer.stop();
577 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
579 log(QString().sprintf("Exited with code %d", process.exitCode()));
580 return (process.exitCode() == 0) && output.exists() && output.isFile();
583 bool UpdateCheckThread::checkSignature(const QString &file, const QString &signature)
585 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
587 qWarning("CheckSignature: File and signature should be in same folder!");
588 return false;
590 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
592 qWarning("CheckSignature: File and keyring should be in same folder!");
593 return false;
596 QProcess process;
597 lamexp_init_process(process, QFileInfo(file).absolutePath());
599 QEventLoop loop;
600 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
601 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
602 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
604 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
606 if(!process.waitForStarted())
608 return false;
611 while(process.state() == QProcess::Running)
613 loop.exec();
614 while(process.canReadLine())
616 log(QString::fromLatin1(process.readLine()).simplified());
620 log(QString().sprintf("Exited with code %d", process.exitCode()));
621 return (process.exitCode() == 0);
624 bool UpdateCheckThread::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
626 QRegExp value("^(\\w+)=(.+)$");
627 QRegExp section("^\\[(.+)\\]$");
629 QDate updateInfoDate;
630 updateInfo->resetInfo();
632 QFile data(file);
633 if(!data.open(QIODevice::ReadOnly))
635 qWarning("Cannot open update info file for reading!");
636 return false;
639 bool inHeader = false;
640 bool inSection = false;
642 while(!data.atEnd())
644 QString line = QString::fromLatin1(data.readLine()).trimmed();
645 if(section.indexIn(line) >= 0)
647 log(QString("Sec: [%1]").arg(section.cap(1)));
648 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
649 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
650 continue;
652 if(inSection && (value.indexIn(line) >= 0))
654 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
655 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
657 bool ok = false;
658 unsigned int temp = value.cap(2).toUInt(&ok);
659 if(ok) updateInfo->m_buildNo = temp;
661 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
663 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
664 if(temp.isValid()) updateInfo->m_buildDate = temp;
666 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
668 updateInfo->m_downloadSite = value.cap(2).trimmed();
670 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
672 updateInfo->m_downloadAddress = value.cap(2).trimmed();
674 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
676 updateInfo->m_downloadFilename = value.cap(2).trimmed();
678 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
680 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
683 if(inHeader && (value.indexIn(line) >= 0))
685 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
686 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
688 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
689 if(temp.isValid()) updateInfoDate = temp;
694 if(!updateInfoDate.isValid())
696 updateInfo->resetInfo();
697 log("WARNING: Version info timestamp is missing!");
698 return false;
700 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < lamexp_current_date_safe())
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(lamexp_current_date_safe() < 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*/