Updated Ukrainian translation.
[LameXP.git] / src / Thread_CheckUpdate.cpp
blobe528f88647ac9e3c4a04d7d901e4dbd79695dbe5
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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://lamexp.berlios.de/",
61 "http://lordmulder.github.com/LameXP/",
62 "http://lord_mulder.bitbucket.org/",
63 "http://www.tricksoft.de/",
64 NULL
67 static const char *update_mirrors_back[] =
69 "http://mplayer.savedonthe.net/",
70 NULL
73 static const char *known_hosts[] = //Taken form: http://www.alexa.com/topsites !!!
75 "http://www.163.com/",
76 "http://www.ac3filter.net/",
77 "http://www.amazon.com/",
78 "http://www.aol.com/",
79 "http://www.apache.org/",
80 "http://www.apple.com/",
81 "http://www.adobe.com/",
82 "http://www.avidemux.org/",
83 "http://www.babylon.com/",
84 "http://www.baidu.com/",
85 "http://www.bbc.co.uk/",
86 "http://www.berlios.de/",
87 "http://www.bing.com/",
88 "http://www.cnet.com/",
89 "http://cnzz.com/",
90 "http://codecs.com/",
91 "http://www.codeplex.com/",
92 "http://qt.digia.com/",
93 "http://www.ebay.com/",
94 "http://www.equation.com/",
95 "http://fc2.com/",
96 "http://www.ffmpeg.org/",
97 "http://www.flickr.com/",
98 "http://blog.gitorious.org/",
99 "http://git-scm.com/",
100 "http://www.gnome.org/",
101 "http://www.gnu.org/",
102 "http://go.com/",
103 "http://code.google.com/",
104 "http://www.heise.de/",
105 "http://www.huffingtonpost.co.uk/",
106 "http://www.iana.org/",
107 "http://www.imdb.com/",
108 "http://www.imgburn.com/",
109 "http://imgur.com/",
110 "http://en.jd.com/",
111 "http://mirrors.kernel.org/",
112 "http://www.libav.org/",
113 "http://www.linkedin.com/about-us",
114 "http://www.livedoor.com/",
115 "http://www.livejournal.com/",
116 "http://mail.ru/",
117 "http://www.mediafire.com/",
118 "http://www.mozilla.org/en-US/",
119 "http://mplayerhq.hu/",
120 "http://www.msn.com/?st=1",
121 "http://oss.netfarm.it/",
122 "http://www.nytimes.com/",
123 "http://www.opera.com/",
124 "http://www.portablefreeware.com/",
125 "http://qt-project.org/",
126 "http://www.quakelive.com/",
127 "http://www.seamonkey-project.org/",
128 "http://www.sina.com.cn/",
129 "http://www.sohu.com/",
130 "http://www.soso.com/",
131 "http://sourceforge.net/",
132 "http://www.spiegel.de/",
133 "http://tdm-gcc.tdragon.net/",
134 "http://www.tdrsmusic.com/",
135 "http://www.ubuntu.com/",
136 "http://status.twitter.com/",
137 "http://www.uol.com.br/",
138 "http://www.videohelp.com/",
139 "http://www.videolan.org/",
140 "http://www.weibo.com/",
141 "http://www.wikipedia.org/",
142 "http://www.winamp.com/",
143 "http://wordpress.com/",
144 "http://us.yahoo.com/",
145 "http://www.yandex.ru/",
146 "http://www.youtube.com/",
147 "http://www.zedo.com/",
148 "http://ffmpeg.zeranoe.com/",
149 NULL
152 static const int MIN_CONNSCORE = 8;
153 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
154 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
156 //Helper function
157 static int getMaxProgress(void)
159 int counter = MIN_CONNSCORE + 2;
160 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
161 for(int i = 0; update_mirrors_back[i]; i++) counter++;
162 return counter;
165 ////////////////////////////////////////////////////////////
166 // Update Info Class
167 ////////////////////////////////////////////////////////////
169 UpdateInfo::UpdateInfo(void)
171 resetInfo();
174 void UpdateInfo::resetInfo(void)
176 m_buildNo = 0;
177 m_buildDate.setDate(1900, 1, 1);
178 m_downloadSite.clear();
179 m_downloadAddress.clear();
180 m_downloadFilename.clear();
181 m_downloadFilecode.clear();
184 ////////////////////////////////////////////////////////////
185 // Constructor & Destructor
186 ////////////////////////////////////////////////////////////
188 UpdateCheckThread::UpdateCheckThread(const bool betaUpdates, const bool testMode)
190 m_updateInfo(new UpdateInfo()),
191 m_betaUpdates(betaUpdates),
192 m_testMode(testMode),
193 m_binaryWGet(lamexp_lookup_tool("wget.exe")),
194 m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
195 m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
196 m_maxProgress(getMaxProgress())
198 m_success = false;
199 m_status = UpdateStatus_NotStartedYet;
200 m_progress = 0;
202 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
204 THROW("Tools not initialized correctly!");
208 UpdateCheckThread::~UpdateCheckThread(void)
210 delete m_updateInfo;
213 ////////////////////////////////////////////////////////////
214 // Protected functions
215 ////////////////////////////////////////////////////////////
217 void UpdateCheckThread::run(void)
219 qDebug("Update checker thread started!");
223 m_testMode ? testKnownHosts() : checkForUpdates();
225 catch(const std::exception &error)
227 fflush(stdout); fflush(stderr);
228 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
229 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
231 catch(...)
233 fflush(stdout); fflush(stderr);
234 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
235 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
238 qDebug("Update checker thread completed.");
241 void UpdateCheckThread::checkForUpdates(void)
243 // ----- Initialization ----- //
245 m_success = false;
246 m_updateInfo->resetInfo();
247 setProgress(0);
249 // ----- Test Internet Connection ----- //
251 int connectionScore = 0;
253 log("Checking internet connection...");
254 setStatus(UpdateStatus_CheckingConnection);
256 const int networkStatus = lamexp_network_status();
257 if(networkStatus == lamexp_network_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 lamexp_seed_rand();
276 while(!hostList.isEmpty())
278 QString currentHost = hostList.takeAt(lamexp_rand() % hostList.count());
279 if(connectionScore < MIN_CONNSCORE)
281 log("", "Testing host:", currentHost);
282 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
283 bool httpOk = false;
284 if(getFile(currentHost, outFile, 0, &httpOk))
286 connectionScore++;
287 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
288 lamexp_sleep(64);
290 if(httpOk)
292 connectionScore++;
293 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
294 lamexp_sleep(64);
296 QFile::remove(outFile);
300 if(connectionScore < MIN_CONNSCORE)
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 bool UpdateCheckThread::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
442 bool success = false;
443 log("", "Trying mirror:", url);
445 QString randPart = lamexp_rand_str();
446 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
447 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
449 log("", "Downloading update info:");
450 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
452 log("", "Downloading signature:");
453 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
455 if(ok1 && ok2)
457 log("", "Download okay, checking signature:");
458 if(checkSignature(outFileVersionInfo, outFileSignature))
460 log("", "Signature okay, parsing info:");
461 success = parseVersionInfo(outFileVersionInfo, updateInfo);
463 else
465 log("", "Bad signature, take care!");
468 else
470 log("", "Download has failed!");
473 QFile::remove(outFileVersionInfo);
474 QFile::remove(outFileSignature);
476 return success;
479 bool UpdateCheckThread::getFile(const QString &url, const QString &outFile, unsigned int maxRedir, bool *httpOk)
481 QFileInfo output(outFile);
482 output.setCaching(false);
483 if(httpOk) *httpOk = false;
485 if(output.exists())
487 QFile::remove(output.canonicalFilePath());
488 if(output.exists())
490 return false;
494 QProcess process;
495 lamexp_init_process(process, output.absolutePath());
497 QStringList args;
498 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
499 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
500 args << "-O" << output.fileName() << url;
502 QEventLoop loop;
503 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
504 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
505 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
507 QTimer timer;
508 timer.setSingleShot(true);
509 timer.setInterval(25000);
510 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
512 const QRegExp httpResponseOK("200 OK$");
514 process.start(m_binaryWGet, args);
516 if(!process.waitForStarted())
518 return false;
521 timer.start();
523 while(process.state() == QProcess::Running)
525 loop.exec();
526 bool bTimeOut = (!timer.isActive());
527 while(process.canReadLine())
529 QString line = QString::fromLatin1(process.readLine()).simplified();
530 if(line.contains(httpResponseOK))
532 line.append(" [OK]");
533 if(httpOk) *httpOk = true;
535 log(line);
537 if(bTimeOut)
539 qWarning("WGet process timed out <-- killing!");
540 process.kill();
541 process.waitForFinished();
542 log("!!! TIMEOUT !!!");
543 return false;
547 timer.stop();
548 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
550 log(QString().sprintf("Exited with code %d", process.exitCode()));
551 return (process.exitCode() == 0) && output.exists() && output.isFile();
554 bool UpdateCheckThread::checkSignature(const QString &file, const QString &signature)
556 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
558 qWarning("CheckSignature: File and signature should be in same folder!");
559 return false;
561 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
563 qWarning("CheckSignature: File and keyring should be in same folder!");
564 return false;
567 QProcess process;
568 lamexp_init_process(process, QFileInfo(file).absolutePath());
570 QEventLoop loop;
571 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
572 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
573 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
575 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
577 if(!process.waitForStarted())
579 return false;
582 while(process.state() == QProcess::Running)
584 loop.exec();
585 while(process.canReadLine())
587 log(QString::fromLatin1(process.readLine()).simplified());
591 log(QString().sprintf("Exited with code %d", process.exitCode()));
592 return (process.exitCode() == 0);
595 bool UpdateCheckThread::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
597 QRegExp value("^(\\w+)=(.+)$");
598 QRegExp section("^\\[(.+)\\]$");
600 QDate updateInfoDate;
601 updateInfo->resetInfo();
603 QFile data(file);
604 if(!data.open(QIODevice::ReadOnly))
606 qWarning("Cannot open update info file for reading!");
607 return false;
610 bool inHeader = false;
611 bool inSection = false;
613 while(!data.atEnd())
615 QString line = QString::fromLatin1(data.readLine()).trimmed();
616 if(section.indexIn(line) >= 0)
618 log(QString("Sec: [%1]").arg(section.cap(1)));
619 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
620 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
621 continue;
623 if(inSection && (value.indexIn(line) >= 0))
625 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
626 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
628 bool ok = false;
629 unsigned int temp = value.cap(2).toUInt(&ok);
630 if(ok) updateInfo->m_buildNo = temp;
632 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
634 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
635 if(temp.isValid()) updateInfo->m_buildDate = temp;
637 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
639 updateInfo->m_downloadSite = value.cap(2).trimmed();
641 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
643 updateInfo->m_downloadAddress = value.cap(2).trimmed();
645 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
647 updateInfo->m_downloadFilename = value.cap(2).trimmed();
649 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
651 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
654 if(inHeader && (value.indexIn(line) >= 0))
656 log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
657 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
659 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
660 if(temp.isValid()) updateInfoDate = temp;
665 if(!updateInfoDate.isValid())
667 updateInfo->resetInfo();
668 log("WARNING: Version info timestamp is missing!");
669 return false;
671 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < lamexp_current_date_safe())
673 updateInfo->resetInfo();
674 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
675 return false;
677 else if(lamexp_current_date_safe() < updateInfoDate)
679 log("Version info is from the future, take care!");
680 qWarning("Version info is from the future, take care!");
683 bool complete = true;
685 if(!(updateInfo->m_buildNo > 0)) complete = false;
686 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
687 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
688 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
689 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
690 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
692 if(!complete)
694 log("WARNING: Version info is incomplete!");
697 return complete;
700 ////////////////////////////////////////////////////////////
701 // SLOTS
702 ////////////////////////////////////////////////////////////
704 /*NONE*/
706 ////////////////////////////////////////////////////////////
707 // EVENTS
708 ////////////////////////////////////////////////////////////
710 /*NONE*/