1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
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, 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"
27 #include <QStringList>
35 ///////////////////////////////////////////////////////////////////////////////
37 ///////////////////////////////////////////////////////////////////////////////
39 static const char *header_id
= "!Update";
40 static const char *section_id
= "LameXP";
42 static const char *mirror_url_postfix
[] =
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/",
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.ac3filter.net/",
76 "http://www.amazon.com/",
77 "http://antergos.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/",
90 "http://www.codeplex.com/",
91 "http://qt.digia.com/",
92 "http://www.ebay.com/",
93 "http://www.equation.com/",
95 "http://fedoraproject.org/",
96 "http://www.ffmpeg.org/",
97 "http://blog.flickr.net/en",
98 "http://free-codecs.com/",
99 "http://blog.gitorious.org/",
100 "http://git-scm.com/",
101 "http://www.gnome.org/",
102 "http://www.gnu.org/",
104 "http://code.google.com/",
105 "http://www.heise.de/",
106 "http://www.huffingtonpost.co.uk/",
107 "http://www.iana.org/",
108 "http://www.imdb.com/",
109 "http://www.imgburn.com/",
112 "http://mirrors.kernel.org/",
113 "http://lame.sourceforge.net/",
114 "http://www.libav.org/",
115 "http://www.linkedin.com/about-us",
116 "http://www.linuxmint.com/",
117 "http://www.livedoor.com/",
118 "http://www.livejournal.com/",
120 "http://www.mediafire.com/",
121 "http://www.mozilla.org/en-US/",
122 "http://mplayerhq.hu/",
123 "http://www.msn.com/?st=1",
124 "http://oss.netfarm.it/",
125 "http://www.nytimes.com/",
126 "http://www.opera.com/",
127 "http://www.portablefreeware.com/",
128 "http://qt-project.org/",
129 "http://www.quakelive.com/",
130 "http://www.seamonkey-project.org/",
131 "http://www.sina.com.cn/",
132 "http://www.sohu.com/",
133 "http://www.soso.com/",
134 "http://sourceforge.net/",
135 "http://www.spiegel.de/",
136 "http://tdm-gcc.tdragon.net/",
137 "http://www.tdrsmusic.com/",
138 "http://www.ubuntu.com/",
139 "http://status.twitter.com/",
140 "http://www.uol.com.br/",
141 "http://www.videohelp.com/",
142 "http://www.videolan.org/",
143 "http://virtualdub.org/",
144 "http://www.weibo.com/",
145 "http://www.wikipedia.org/",
146 "http://www.winamp.com/",
147 "http://wordpress.com/",
149 "http://us.mail.yahoo.com/",
150 "http://www.yandex.ru/",
151 "http://www.youtube.com/",
152 "http://www.zedo.com/",
153 "http://ffmpeg.zeranoe.com/",
157 static const int MIN_CONNSCORE
= 8;
158 static const int VERSION_INFO_EXPIRES_MONTHS
= 6;
159 static char *USER_AGENT_STR
= "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20111106 IceCat/7.0.1";
162 static int getMaxProgress(void)
164 int counter
= MIN_CONNSCORE
+ 2;
165 for(int i
= 0; update_mirrors_prim
[i
]; i
++) counter
++;
166 for(int i
= 0; update_mirrors_back
[i
]; i
++) counter
++;
170 ////////////////////////////////////////////////////////////
172 ////////////////////////////////////////////////////////////
174 UpdateInfo::UpdateInfo(void)
179 void UpdateInfo::resetInfo(void)
182 m_buildDate
.setDate(1900, 1, 1);
183 m_downloadSite
.clear();
184 m_downloadAddress
.clear();
185 m_downloadFilename
.clear();
186 m_downloadFilecode
.clear();
189 ////////////////////////////////////////////////////////////
190 // Constructor & Destructor
191 ////////////////////////////////////////////////////////////
193 UpdateCheckThread::UpdateCheckThread(const QString
&binWGet
, const QString
&binGnuPG
, const QString
&binKeys
, const bool betaUpdates
, const bool testMode
)
195 m_updateInfo(new UpdateInfo()),
196 m_binaryWGet(binWGet
),
197 m_binaryGnuPG(binGnuPG
),
198 m_binaryKeys(binKeys
),
199 m_betaUpdates(betaUpdates
),
200 m_testMode(testMode
),
201 m_maxProgress(getMaxProgress())
204 m_status
= UpdateStatus_NotStartedYet
;
207 if(m_binaryWGet
.isEmpty() || m_binaryGnuPG
.isEmpty() || m_binaryKeys
.isEmpty())
209 THROW("Tools not initialized correctly!");
213 UpdateCheckThread::~UpdateCheckThread(void)
218 ////////////////////////////////////////////////////////////
219 // Protected functions
220 ////////////////////////////////////////////////////////////
222 void UpdateCheckThread::run(void)
224 qDebug("Update checker thread started!");
228 m_testMode
? testKnownHosts() : checkForUpdates();
230 catch(const std::exception
&error
)
232 fflush(stdout
); fflush(stderr
);
233 fprintf(stderr
, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error
.what());
234 lamexp_fatal_exit(L
"Unhandeled C++ exception error, application will exit!");
238 fflush(stdout
); fflush(stderr
);
239 fprintf(stderr
, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
240 lamexp_fatal_exit(L
"Unhandeled C++ exception error, application will exit!");
243 qDebug("Update checker thread completed.");
246 void UpdateCheckThread::checkForUpdates(void)
248 // ----- Initialization ----- //
251 m_updateInfo
->resetInfo();
254 // ----- Test Internet Connection ----- //
256 int connectionScore
= 0;
257 int maxConnectTries
= (3 * MIN_CONNSCORE
) / 2;
259 log("Checking internet connection...");
260 setStatus(UpdateStatus_CheckingConnection
);
262 const int networkStatus
= lamexp_network_status();
263 if(networkStatus
== lamexp_network_non
)
265 log("", "Operating system reports that the computer is currently offline !!!");
266 setProgress(m_maxProgress
);
267 setStatus(UpdateStatus_ErrorNoConnection
);
273 // ----- Test Known Hosts Connectivity ----- //
275 QStringList hostList
;
276 for(int i
= 0; known_hosts
[i
]; i
++)
278 hostList
<< QString::fromLatin1(known_hosts
[i
]);
283 while(!(hostList
.isEmpty() || (connectionScore
>= MIN_CONNSCORE
) || (maxConnectTries
< 1)))
285 switch(tryContactHost(hostList
.takeAt(lamexp_rand() % hostList
.count())))
287 case 01: connectionScore
+= 1; break;
288 case 02: connectionScore
+= 2; break;
289 default: maxConnectTries
-= 1; break;
291 setProgress(qBound(1, connectionScore
+ 1, MIN_CONNSCORE
+ 1));
295 if(connectionScore
< MIN_CONNSCORE
)
297 log("", "Connectivity test has failed: Internet connection appears to be broken!");
298 setProgress(m_maxProgress
);
299 setStatus(UpdateStatus_ErrorConnectionTestFailed
);
303 // ----- Build Mirror List ----- //
305 log("", "----", "", "Checking for updates online...");
306 setStatus(UpdateStatus_FetchingUpdates
);
308 QStringList mirrorList
;
309 for(int index
= 0; update_mirrors_prim
[index
]; index
++)
311 mirrorList
<< QString::fromLatin1(update_mirrors_prim
[index
]);
315 if(const int len
= mirrorList
.count())
317 const int rounds
= len
* 1097;
318 for(int i
= 0; i
< rounds
; i
++)
320 mirrorList
.swap(i
% len
, lamexp_rand() % len
);
324 for(int index
= 0; update_mirrors_back
[index
]; index
++)
326 mirrorList
<< QString::fromLatin1(update_mirrors_back
[index
]);
329 // ----- Fetch Update Info From Server ----- //
331 while(!mirrorList
.isEmpty())
333 QString currentMirror
= mirrorList
.takeFirst();
334 setProgress(m_progress
+ 1);
337 if(tryUpdateMirror(m_updateInfo
, currentMirror
))
348 setProgress(m_maxProgress
);
352 if(m_updateInfo
->m_buildNo
> lamexp_version_build())
354 setStatus(UpdateStatus_CompletedUpdateAvailable
);
356 else if(m_updateInfo
->m_buildNo
== lamexp_version_build())
358 setStatus(UpdateStatus_CompletedNoUpdates
);
362 setStatus(UpdateStatus_CompletedNewVersionOlder
);
367 setStatus(UpdateStatus_ErrorFetchUpdateInfo
);
371 void UpdateCheckThread::testKnownHosts(void)
373 QStringList hostList
;
374 for(int i
= 0; known_hosts
[i
]; i
++)
376 hostList
<< QString::fromLatin1(known_hosts
[i
]);
379 qDebug("\n[Known Hosts]");
380 log("Testing all known hosts...", "", "---");
382 int hostCount
= hostList
.count();
383 while(!hostList
.isEmpty())
385 QString currentHost
= hostList
.takeFirst();
386 qDebug("Testing: %s", currentHost
.toLatin1().constData());
387 log("", "Testing:", currentHost
, "");
388 QString outFile
= QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
390 if(!getFile(currentHost
, outFile
, 0, &httpOk
))
394 qWarning("\nConnectivity test was SLOW on the following site:\n%s\n", currentHost
.toLatin1().constData());
398 qWarning("\nConnectivity test FAILED on the following site:\n%s\n", currentHost
.toLatin1().constData());
402 QFile::remove(outFile
);
406 ////////////////////////////////////////////////////////////
408 ////////////////////////////////////////////////////////////
410 void UpdateCheckThread::setStatus(const int status
)
412 if(m_status
!= status
)
415 emit
statusChanged(status
);
419 void UpdateCheckThread::setProgress(const int progress
)
421 if(m_progress
!= progress
)
423 m_progress
= progress
;
424 emit
progressChanged(progress
);
428 void UpdateCheckThread::log(const QString
&str1
, const QString
&str2
, const QString
&str3
, const QString
&str4
)
430 if(!str1
.isNull()) emit
messageLogged(str1
);
431 if(!str2
.isNull()) emit
messageLogged(str2
);
432 if(!str3
.isNull()) emit
messageLogged(str3
);
433 if(!str4
.isNull()) emit
messageLogged(str4
);
436 int UpdateCheckThread::tryContactHost(const QString
&url
)
438 int result
= -1; bool httpOkay
= false;
439 const QString outFile
= QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
440 log("", "Testing host:", url
);
442 if(getFile(url
, outFile
, 0, &httpOkay
))
444 log("Connection to host was established successfully.");
451 log("Connection to host timed out after HTTP OK was received.");
456 log("Connection failed: The host could not be reached!");
461 QFile::remove(outFile
);
465 bool UpdateCheckThread::tryUpdateMirror(UpdateInfo
*updateInfo
, const QString
&url
)
467 bool success
= false;
468 log("", "Trying mirror:", url
);
470 QString randPart
= lamexp_rand_str();
471 QString outFileVersionInfo
= QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart
);
472 QString outFileSignature
= QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart
);
474 log("", "Downloading update info:");
475 bool ok1
= getFile(QString("%1%2").arg(url
, mirror_url_postfix
[m_betaUpdates
? 1 : 0]), outFileVersionInfo
);
477 log("", "Downloading signature:");
478 bool ok2
= getFile(QString("%1%2.sig").arg(url
, mirror_url_postfix
[m_betaUpdates
? 1 : 0]), outFileSignature
);
482 log("", "Download okay, checking signature:");
483 if(checkSignature(outFileVersionInfo
, outFileSignature
))
485 log("", "Signature okay, parsing info:");
486 success
= parseVersionInfo(outFileVersionInfo
, updateInfo
);
490 log("", "Bad signature, take care!");
495 log("", "Download has failed!");
498 QFile::remove(outFileVersionInfo
);
499 QFile::remove(outFileSignature
);
504 bool UpdateCheckThread::getFile(const QString
&url
, const QString
&outFile
, unsigned int maxRedir
, bool *httpOk
)
506 QFileInfo
output(outFile
);
507 output
.setCaching(false);
508 if(httpOk
) *httpOk
= false;
512 QFile::remove(output
.canonicalFilePath());
520 lamexp_init_process(process
, output
.absolutePath());
523 args
<< "-T" << "15" << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir
);
524 args
<< QString("--referer=%1://%2/").arg(QUrl(url
).scheme(), QUrl(url
).host()) << "-U" << USER_AGENT_STR
;
525 args
<< "-O" << output
.fileName() << url
;
528 connect(&process
, SIGNAL(error(QProcess::ProcessError
)), &loop
, SLOT(quit()));
529 connect(&process
, SIGNAL(finished(int,QProcess::ExitStatus
)), &loop
, SLOT(quit()));
530 connect(&process
, SIGNAL(readyRead()), &loop
, SLOT(quit()));
533 timer
.setSingleShot(true);
534 timer
.setInterval(25000);
535 connect(&timer
, SIGNAL(timeout()), &loop
, SLOT(quit()));
537 const QRegExp
httpResponseOK("200 OK$");
539 process
.start(m_binaryWGet
, args
);
541 if(!process
.waitForStarted())
548 while(process
.state() != QProcess::NotRunning
)
551 const bool bTimeOut
= (!timer
.isActive());
552 while(process
.canReadLine())
554 QString line
= QString::fromLatin1(process
.readLine()).simplified();
555 if(line
.contains(httpResponseOK
))
557 line
.append(" [OK]");
558 if(httpOk
) *httpOk
= true;
564 qWarning("WGet process timed out <-- killing!");
566 process
.waitForFinished();
567 log("!!! TIMEOUT !!!");
573 timer
.disconnect(&timer
, SIGNAL(timeout()), &loop
, SLOT(quit()));
575 log(QString().sprintf("Exited with code %d", process
.exitCode()));
576 return (process
.exitCode() == 0) && output
.exists() && output
.isFile();
579 bool UpdateCheckThread::checkSignature(const QString
&file
, const QString
&signature
)
581 if(QFileInfo(file
).absolutePath().compare(QFileInfo(signature
).absolutePath(), Qt::CaseInsensitive
) != 0)
583 qWarning("CheckSignature: File and signature should be in same folder!");
586 if(QFileInfo(file
).absolutePath().compare(QFileInfo(m_binaryKeys
).absolutePath(), Qt::CaseInsensitive
) != 0)
588 qWarning("CheckSignature: File and keyring should be in same folder!");
593 lamexp_init_process(process
, QFileInfo(file
).absolutePath());
596 connect(&process
, SIGNAL(error(QProcess::ProcessError
)), &loop
, SLOT(quit()));
597 connect(&process
, SIGNAL(finished(int,QProcess::ExitStatus
)), &loop
, SLOT(quit()));
598 connect(&process
, SIGNAL(readyRead()), &loop
, SLOT(quit()));
600 process
.start(m_binaryGnuPG
, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys
).fileName() << QFileInfo(signature
).fileName() << QFileInfo(file
).fileName());
602 if(!process
.waitForStarted())
607 while(process
.state() == QProcess::Running
)
610 while(process
.canReadLine())
612 log(QString::fromLatin1(process
.readLine()).simplified());
616 log(QString().sprintf("Exited with code %d", process
.exitCode()));
617 return (process
.exitCode() == 0);
620 bool UpdateCheckThread::parseVersionInfo(const QString
&file
, UpdateInfo
*updateInfo
)
622 QRegExp
value("^(\\w+)=(.+)$");
623 QRegExp
section("^\\[(.+)\\]$");
625 QDate updateInfoDate
;
626 updateInfo
->resetInfo();
629 if(!data
.open(QIODevice::ReadOnly
))
631 qWarning("Cannot open update info file for reading!");
635 bool inHeader
= false;
636 bool inSection
= false;
640 QString line
= QString::fromLatin1(data
.readLine()).trimmed();
641 if(section
.indexIn(line
) >= 0)
643 log(QString("Sec: [%1]").arg(section
.cap(1)));
644 inSection
= (section
.cap(1).compare(section_id
, Qt::CaseInsensitive
) == 0);
645 inHeader
= (section
.cap(1).compare(header_id
, Qt::CaseInsensitive
) == 0);
648 if(inSection
&& (value
.indexIn(line
) >= 0))
650 log(QString("Val: '%1' ==> '%2").arg(value
.cap(1), value
.cap(2)));
651 if(value
.cap(1).compare("BuildNo", Qt::CaseInsensitive
) == 0)
654 unsigned int temp
= value
.cap(2).toUInt(&ok
);
655 if(ok
) updateInfo
->m_buildNo
= temp
;
657 else if(value
.cap(1).compare("BuildDate", Qt::CaseInsensitive
) == 0)
659 QDate temp
= QDate::fromString(value
.cap(2).trimmed(), Qt::ISODate
);
660 if(temp
.isValid()) updateInfo
->m_buildDate
= temp
;
662 else if(value
.cap(1).compare("DownloadSite", Qt::CaseInsensitive
) == 0)
664 updateInfo
->m_downloadSite
= value
.cap(2).trimmed();
666 else if(value
.cap(1).compare("DownloadAddress", Qt::CaseInsensitive
) == 0)
668 updateInfo
->m_downloadAddress
= value
.cap(2).trimmed();
670 else if(value
.cap(1).compare("DownloadFilename", Qt::CaseInsensitive
) == 0)
672 updateInfo
->m_downloadFilename
= value
.cap(2).trimmed();
674 else if(value
.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive
) == 0)
676 updateInfo
->m_downloadFilecode
= value
.cap(2).trimmed();
679 if(inHeader
&& (value
.indexIn(line
) >= 0))
681 log(QString("Val: '%1' ==> '%2").arg(value
.cap(1), value
.cap(2)));
682 if(value
.cap(1).compare("TimestampCreated", Qt::CaseInsensitive
) == 0)
684 QDate temp
= QDate::fromString(value
.cap(2).trimmed(), Qt::ISODate
);
685 if(temp
.isValid()) updateInfoDate
= temp
;
690 if(!updateInfoDate
.isValid())
692 updateInfo
->resetInfo();
693 log("WARNING: Version info timestamp is missing!");
696 else if(updateInfoDate
.addMonths(VERSION_INFO_EXPIRES_MONTHS
) < lamexp_current_date_safe())
698 updateInfo
->resetInfo();
699 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate
.addMonths(VERSION_INFO_EXPIRES_MONTHS
).toString(Qt::ISODate
)));
702 else if(lamexp_current_date_safe() < updateInfoDate
)
704 log("Version info is from the future, take care!");
705 qWarning("Version info is from the future, take care!");
708 bool complete
= true;
710 if(!(updateInfo
->m_buildNo
> 0)) complete
= false;
711 if(!(updateInfo
->m_buildDate
.year() >= 2010)) complete
= false;
712 if(updateInfo
->m_downloadSite
.isEmpty()) complete
= false;
713 if(updateInfo
->m_downloadAddress
.isEmpty()) complete
= false;
714 if(updateInfo
->m_downloadFilename
.isEmpty()) complete
= false;
715 if(updateInfo
->m_downloadFilecode
.isEmpty()) complete
= false;
719 log("WARNING: Version info is incomplete!");
725 ////////////////////////////////////////////////////////////
727 ////////////////////////////////////////////////////////////
731 ////////////////////////////////////////////////////////////
733 ////////////////////////////////////////////////////////////