OSDN Git Service

54972c087191224b62c33bd53440c42799c9e14b
[mutilities/MUtilities.git] / src / UpdateChecker.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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.
14 //
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
18 //
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
21
22 #include <MUtils/Global.h>
23 #include <MUtils/UpdateChecker.h>
24 #include <MUtils/OSSupport.h>
25 #include <MUtils/Exception.h>
26
27 #include <QStringList>
28 #include <QFile>
29 #include <QFileInfo>
30 #include <QDir>
31 #include <QProcess>
32 #include <QUrl>
33 #include <QEventLoop>
34 #include <QTimer>
35 #include <QElapsedTimer>
36 #include <QSet>
37 #include <QHash>
38
39 #include "Mirrors.h"
40
41 ///////////////////////////////////////////////////////////////////////////////
42 // CONSTANTS
43 ///////////////////////////////////////////////////////////////////////////////
44
45 static const char *header_id = "!Update";
46
47 static const char *mirror_url_postfix[] = 
48 {
49         "update.ver",
50         "update_beta.ver",
51         NULL
52 };
53
54 static const int MIN_CONNSCORE = 5;
55 static const int QUICK_MIRRORS = 3;
56 static const int MAX_CONN_TIMEOUT = 16000;
57 static const int DOWNLOAD_TIMEOUT = 30000;
58
59 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
60 static char *USER_AGENT_STR = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"; /*use something innocuous*/
61
62 #define CHECK_CANCELLED() do \
63 { \
64         if(MUTILS_BOOLIFY(m_cancelled)) \
65         { \
66                 m_success.fetchAndStoreOrdered(0); \
67                 log("", "Update check has been cancelled by user!"); \
68                 setProgress(m_maxProgress); \
69                 setStatus(UpdateStatus_CancelledByUser); \
70                 return; \
71         } \
72 } \
73 while(0)
74
75 ////////////////////////////////////////////////////////////
76 // Helper Functions
77 ////////////////////////////////////////////////////////////
78
79 static int getMaxProgress(void)
80 {
81         int counter = 0;
82         while (update_mirrors[counter])
83         {
84                 counter++;
85         }
86         counter += MIN_CONNSCORE + QUICK_MIRRORS + 2;
87         return counter; ;
88 }
89
90 static QStringList buildRandomList(const char *const values[])
91 {
92         QStringList list;
93         for (int index = 0; values[index]; index++)
94         {
95                 const int pos = MUtils::next_rand_u32() % (index + 1);
96                 list.insert(pos, QString::fromLatin1(values[index]));
97         }
98         return list;
99 }
100
101 static const QHash<QString, QString> *initEnvVars(void)
102 {
103         QHash<QString, QString> *const environment = new QHash<QString, QString>();
104         environment->insert(QLatin1String("CURL_HOME"), QDir::toNativeSeparators(MUtils::temp_folder()));
105         return environment;
106 }
107
108 ////////////////////////////////////////////////////////////
109 // Update Info Class
110 ////////////////////////////////////////////////////////////
111
112 MUtils::UpdateCheckerInfo::UpdateCheckerInfo(void)
113 {
114         resetInfo();
115 }
116         
117 void MUtils::UpdateCheckerInfo::resetInfo(void)
118 {
119         m_buildNo = 0;
120         m_buildDate.setDate(1900, 1, 1);
121         m_downloadSite.clear();
122         m_downloadAddress.clear();
123         m_downloadFilename.clear();
124         m_downloadFilecode.clear();
125         m_downloadChecksum.clear();
126 }
127
128 bool MUtils::UpdateCheckerInfo::isComplete(void)
129 {
130         if(this->m_buildNo < 1)                return false;
131         if(this->m_buildDate.year() < 2010)    return false;
132         if(this->m_downloadSite.isEmpty())     return false;
133         if(this->m_downloadAddress.isEmpty())  return false;
134         if(this->m_downloadFilename.isEmpty()) return false;
135         if(this->m_downloadFilecode.isEmpty()) return false;
136         if(this->m_downloadChecksum.isEmpty()) return false;
137
138         return true;
139 }
140
141 ////////////////////////////////////////////////////////////
142 // Constructor & Destructor
143 ////////////////////////////////////////////////////////////
144
145 MUtils::UpdateChecker::UpdateChecker(const QString &binCurl, const QString &binGnuPG, const QString &binKeys, const QString &applicationId, const quint32 &installedBuildNo, const bool betaUpdates, const bool testMode)
146 :
147         m_updateInfo(new UpdateCheckerInfo()),
148         m_binaryCurl(binCurl),
149         m_binaryGnuPG(binGnuPG),
150         m_binaryKeys(binKeys),
151         m_applicationId(applicationId),
152         m_installedBuildNo(installedBuildNo),
153         m_betaUpdates(betaUpdates),
154         m_testMode(testMode),
155         m_maxProgress(getMaxProgress()),
156         m_environment(initEnvVars())
157 {
158         m_status = UpdateStatus_NotStartedYet;
159         m_progress = 0;
160
161         if(m_binaryCurl.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
162         {
163                 MUTILS_THROW("Tools not initialized correctly!");
164         }
165 }
166
167 MUtils::UpdateChecker::~UpdateChecker(void)
168 {
169 }
170
171 ////////////////////////////////////////////////////////////
172 // Public slots
173 ////////////////////////////////////////////////////////////
174
175 void MUtils::UpdateChecker::start(Priority priority)
176 {
177         m_success.fetchAndStoreOrdered(0);
178         m_cancelled.fetchAndStoreOrdered(0);
179         QThread::start(priority);
180 }
181
182 ////////////////////////////////////////////////////////////
183 // Protected functions
184 ////////////////////////////////////////////////////////////
185
186 void MUtils::UpdateChecker::run(void)
187 {
188         qDebug("Update checker thread started!");
189         MUTILS_EXCEPTION_HANDLER(m_testMode ? testMirrorsList() : checkForUpdates());
190         qDebug("Update checker thread completed.");
191 }
192
193 void MUtils::UpdateChecker::checkForUpdates(void)
194 {
195         // ----- Initialization ----- //
196
197         m_updateInfo->resetInfo();
198         setProgress(0);
199
200         // ----- Test Internet Connection ----- //
201
202         log("Checking your Internet connection...", "");
203         setStatus(UpdateStatus_CheckingConnection);
204
205         const int networkStatus = OS::network_status();
206         if(networkStatus == OS::NETWORK_TYPE_NON)
207         {
208                 log("Operating system reports that the computer is currently offline !!!");
209                 setProgress(m_maxProgress);
210                 setStatus(UpdateStatus_ErrorNoConnection);
211                 return;
212         }
213         
214         msleep(500);
215         setProgress(1);
216
217         // ----- Test Known Hosts Connectivity ----- //
218
219         int connectionScore = 0;
220         QStringList mirrorList = buildRandomList(known_hosts);
221
222         for(int connectionTimout = 1000; connectionTimout <= MAX_CONN_TIMEOUT; connectionTimout *= 2)
223         {
224                 QElapsedTimer elapsedTimer;
225                 elapsedTimer.start();
226                 const int globalTimout = 2 * MIN_CONNSCORE * connectionTimout;
227                 while (!elapsedTimer.hasExpired(globalTimout))
228                 {
229                         const QString hostName = mirrorList.takeFirst();
230                         if (tryContactHost(hostName, connectionTimout))
231                         {
232                                 connectionScore += 1;
233                                 setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
234                                 elapsedTimer.restart();
235                                 if (connectionScore >= MIN_CONNSCORE)
236                                 {
237                                         goto endLoop; /*success*/
238                                 }
239                         }
240                         else
241                         {
242                                 mirrorList.append(hostName); /*re-schedule*/
243                         }
244                         CHECK_CANCELLED();
245                         msleep(1);
246                 }
247         }
248
249 endLoop:
250         if(connectionScore < MIN_CONNSCORE)
251         {
252                 log("", "Connectivity test has failed: Internet connection appears to be broken!");
253                 setProgress(m_maxProgress);
254                 setStatus(UpdateStatus_ErrorConnectionTestFailed);
255                 return;
256         }
257
258         // ----- Fetch Update Info From Server ----- //
259
260         log("----", "", "Internet connection is operational, checking for updates online...");
261         setStatus(UpdateStatus_FetchingUpdates);
262
263         int mirrorCount = 0;
264         mirrorList = buildRandomList(update_mirrors);
265
266         while(!mirrorList.isEmpty())
267         {
268                 setProgress(m_progress + 1);
269                 const QString currentMirror = mirrorList.takeFirst();
270                 const bool isQuick = (mirrorCount++ < QUICK_MIRRORS);
271                 if(tryUpdateMirror(m_updateInfo.data(), currentMirror, isQuick))
272                 {
273                         m_success.ref(); /*success*/
274                         break;
275                 }
276                 if (isQuick)
277                 {
278                         mirrorList.append(currentMirror); /*re-schedule*/
279                 }
280                 CHECK_CANCELLED();
281                 msleep(1);
282         }
283         
284         while (m_progress < m_maxProgress)
285         {
286                 msleep(16);
287                 setProgress(m_progress + 1);
288                 CHECK_CANCELLED();
289         }
290
291         // ----- Generate final result ----- //
292
293         if(MUTILS_BOOLIFY(m_success))
294         {
295                 if(m_updateInfo->m_buildNo > m_installedBuildNo)
296                 {
297                         setStatus(UpdateStatus_CompletedUpdateAvailable);
298                 }
299                 else if(m_updateInfo->m_buildNo == m_installedBuildNo)
300                 {
301                         setStatus(UpdateStatus_CompletedNoUpdates);
302                 }
303                 else
304                 {
305                         setStatus(UpdateStatus_CompletedNewVersionOlder);
306                 }
307         }
308         else
309         {
310                 setStatus(UpdateStatus_ErrorFetchUpdateInfo);
311         }
312 }
313
314 void MUtils::UpdateChecker::testMirrorsList(void)
315 {
316         // ----- Test update mirrors ----- //
317
318         QStringList mirrorList;
319         for(int i = 0; update_mirrors[i]; i++)
320         {
321                 mirrorList << QString::fromLatin1(update_mirrors[i]);
322         }
323
324         qDebug("\n[Mirror Sites]");
325         log("Testing all known mirror sites...", "", "---");
326
327         UpdateCheckerInfo updateInfo;
328         while (!mirrorList.isEmpty())
329         {
330                 const QString currentMirror = mirrorList.takeFirst();
331                 bool success = false;
332                 qDebug("Testing: %s", MUTILS_L1STR(currentMirror));
333                 log("", "Testing:", currentMirror, "");
334                 for (quint8 attempt = 0; attempt < 3; ++attempt)
335                 {
336                         updateInfo.resetInfo();
337                         if (tryUpdateMirror(&updateInfo, currentMirror, (!attempt)))
338                         {
339                                 success = true;
340                                 break;
341                         }
342                 }
343                 if (!success)
344                 {
345                         qWarning("\nUpdate mirror seems to be unavailable:\n%s\n", MUTILS_L1STR(currentMirror));
346                 }
347                 log("", "---");
348         }
349
350         // ----- Test known hosts ----- //
351
352         QStringList knownHostList;
353         for (int i = 0; known_hosts[i]; i++)
354         {
355                 knownHostList << QString::fromLatin1(known_hosts[i]);
356         }
357
358         qDebug("\n[Known Hosts]");
359         log("Testing all known hosts...", "", "---");
360
361         while(!knownHostList.isEmpty())
362         {
363                 const QString currentHost = knownHostList.takeFirst();
364                 qDebug("Testing: %s", MUTILS_L1STR(currentHost));
365                 log(QLatin1String(""), "Testing:", currentHost, "");
366                 if (!tryContactHost(currentHost, DOWNLOAD_TIMEOUT))
367                 {
368                         qWarning("\nConnectivity test FAILED on the following host:\n%s\n", MUTILS_L1STR(currentHost));
369                 }
370                 log("", "---");
371         }
372 }
373
374 ////////////////////////////////////////////////////////////
375 // PRIVATE FUNCTIONS
376 ////////////////////////////////////////////////////////////
377
378 void MUtils::UpdateChecker::setStatus(const int status)
379 {
380         if(m_status != status)
381         {
382                 m_status = status;
383                 emit statusChanged(status);
384         }
385 }
386
387 void MUtils::UpdateChecker::setProgress(const int progress)
388 {
389         if(m_progress != progress)
390         {
391                 m_progress = progress;
392                 emit progressChanged(progress);
393         }
394 }
395
396 void MUtils::UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
397 {
398         if(!str1.isNull()) emit messageLogged(str1);
399         if(!str2.isNull()) emit messageLogged(str2);
400         if(!str3.isNull()) emit messageLogged(str3);
401         if(!str4.isNull()) emit messageLogged(str4);
402 }
403
404 bool MUtils::UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url, const bool &quick)
405 {
406         bool success = false;
407         log("", "Trying mirror:", url, "");
408
409         if (quick)
410         {
411                 if (!tryContactHost(QUrl(url).host(), (MAX_CONN_TIMEOUT / 8)))
412                 {
413                         log("", "Mirror is too slow, skipping!");
414                         return false;
415                 }
416         }
417
418         const QString randPart = next_rand_str();
419         const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
420         const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
421
422         if (getUpdateInfo(url, outFileVers, outFileSign))
423         {
424                 log("Download completed, verifying signature:", "");
425                 if (checkSignature(outFileVers, outFileSign))
426                 {
427                         log("", "Signature is valid, parsing info:", "");
428                         success = parseVersionInfo(outFileVers, updateInfo);
429                 }
430                 else
431                 {
432                         log("", "Bad signature, take care !!!");
433                 }
434         }
435         else
436         {
437                 log("", "Download has failed!");
438         }
439
440         QFile::remove(outFileVers);
441         QFile::remove(outFileSign);
442         
443         return success;
444 }
445
446 bool MUtils::UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
447 {
448         log("Downloading update info:", "");
449         if(getFile(QUrl(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileVers))
450         {
451                 if (!m_cancelled)
452                 {
453                         log( "Downloading signature file:", "");
454                         if (getFile(QUrl(QString("%1%2.sig2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileSign))
455                         {
456                                 return true;
457                         }
458                 }
459         }
460         return false;
461 }
462
463 bool MUtils::UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
464 {
465         QRegExp value("^(\\w+)=(.+)$");
466         QRegExp section("^\\[(.+)\\]$");
467
468         QDate updateInfoDate;
469         updateInfo->resetInfo();
470
471         QFile data(file);
472         if(!data.open(QIODevice::ReadOnly))
473         {
474                 qWarning("Cannot open update info file for reading!");
475                 return false;
476         }
477         
478         bool inHdr = false;
479         bool inSec = false;
480         
481         while(!data.atEnd())
482         {
483                 QString line = QString::fromLatin1(data.readLine()).trimmed();
484                 if(section.indexIn(line) >= 0)
485                 {
486                         log(QString("Sec: [%1]").arg(section.cap(1)));
487                         inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
488                         inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
489                         continue;
490                 }
491                 if(inSec && (value.indexIn(line) >= 0))
492                 {
493                         log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
494                         if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
495                         {
496                                 bool ok = false;
497                                 const unsigned int temp = value.cap(2).toUInt(&ok);
498                                 if(ok) updateInfo->m_buildNo = temp;
499                         }
500                         else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
501                         {
502                                 const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
503                                 if(temp.isValid()) updateInfo->m_buildDate = temp;
504                         }
505                         else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
506                         {
507                                 updateInfo->m_downloadSite = value.cap(2).trimmed();
508                         }
509                         else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
510                         {
511                                 updateInfo->m_downloadAddress = value.cap(2).trimmed();
512                         }
513                         else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
514                         {
515                                 updateInfo->m_downloadFilename = value.cap(2).trimmed();
516                         }
517                         else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
518                         {
519                                 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
520                         }
521                         else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
522                         {
523                                 updateInfo->m_downloadChecksum = value.cap(2).trimmed();
524                         }
525                 }
526                 if(inHdr && (value.indexIn(line) >= 0))
527                 {
528                         log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
529                         if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
530                         {
531                                 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
532                                 if(temp.isValid()) updateInfoDate = temp;
533                         }
534                 }
535         }
536
537         if(!updateInfoDate.isValid())
538         {
539                 updateInfo->resetInfo();
540                 log("WARNING: Version info timestamp is missing!");
541                 return false;
542         }
543         
544         const QDate currentDate = OS::current_date();
545         if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
546         {
547                 updateInfo->resetInfo();
548                 log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
549                 return false;
550         }
551         else if(currentDate < updateInfoDate)
552         {
553                 log("Version info is from the future, take care!");
554                 qWarning("Version info is from the future, take care!");
555         }
556         
557         if(!updateInfo->isComplete())
558         {
559                 log("WARNING: Version info is incomplete!");
560                 return false;
561         }
562
563         return true;
564 }
565
566 //----------------------------------------------------------
567 // EXTERNAL TOOLS
568 //----------------------------------------------------------
569
570 bool MUtils::UpdateChecker::getFile(const QUrl &url, const QString &outFile, const unsigned int maxRedir)
571 {
572         QFileInfo output(outFile);
573         output.setCaching(false);
574
575         if (output.exists())
576         {
577                 QFile::remove(output.canonicalFilePath());
578                 if (output.exists())
579                 {
580                         qWarning("Existing output file could not be found!");
581                         return false;
582                 }
583         }
584         
585         QStringList args(QLatin1String("-vsSNqkfL"));
586         args << "-m" << QString::number(DOWNLOAD_TIMEOUT / 1000);
587         args << "--max-redirs" << QString::number(maxRedir);
588         args << "-A" << USER_AGENT_STR;
589         args << "-e" << QString("%1://%2/;auto").arg(url.scheme(), url.host());
590         args << "-o" << output.fileName() << url.toString();
591
592         return invokeCurl(args, output.absolutePath(), DOWNLOAD_TIMEOUT);
593 }
594
595 bool MUtils::UpdateChecker::tryContactHost(const QString &hostname, const int &timeoutMsec)
596 {
597         log(QString("Connecting to host: %1").arg(hostname), "");
598
599         QStringList args(QLatin1String("-vsSNqkI"));
600         args << "-m" << QString::number(qMax(1, timeoutMsec / 1000));
601         args << "-A" << USER_AGENT_STR;
602         args << "-o" << OS::null_device() << QString("http://%1/").arg(hostname);
603         
604         return invokeCurl(args, temp_folder(), timeoutMsec);
605 }
606
607 bool MUtils::UpdateChecker::invokeCurl(const QStringList &args, const QString &workingDir, const int timeout)
608 {
609         QProcess process;
610         init_process(process, workingDir, true, NULL, m_environment.data());
611
612         QEventLoop loop;
613         connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
614         connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
615         connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
616
617         QTimer timer;
618         timer.setSingleShot(true);
619         connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
620
621         process.start(m_binaryCurl, args);
622         if (!process.waitForStarted())
623         {
624                 return false;
625         }
626
627         bool bAborted = false;
628         timer.start(qMax((timeout + (timeout / 2)), 1500));
629
630         while (process.state() != QProcess::NotRunning)
631         {
632                 loop.exec();
633                 while (process.canReadLine())
634                 {
635                         const QString line = QString::fromLatin1(process.readLine()).simplified();
636                         if ((!line.isEmpty()) && line.compare(QLatin1String("<")) && line.compare(QLatin1String(">")))
637                         {
638                                 log(line);
639                         }
640                 }
641                 const bool bCancelled = MUTILS_BOOLIFY(m_cancelled);
642                 if (bAborted = (bCancelled || ((!timer.isActive()) && (!process.waitForFinished(125)))))
643                 {
644                         log(bCancelled ? "CANCELLED BY USER !!!" : "PROCESS TIMEOUT !!!", "");
645                         qWarning("WARNING: cURL process %s!", bCancelled ? "cancelled" : "timed out");
646                         break; /*abort process*/
647                 }
648         }
649
650         timer.stop();
651         timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
652
653         if (bAborted)
654         {
655                 process.kill();
656                 process.waitForFinished(-1);
657         }
658
659         while (process.canReadLine())
660         {
661                 const QString line = QString::fromLatin1(process.readLine()).simplified();
662                 if ((!line.isEmpty()) && line.compare(QLatin1String("<")) && line.compare(QLatin1String(">")))
663                 {
664                         log(line);
665                 }
666         }
667
668         if (!bAborted)
669         {
670                 const int exitCode = process.exitCode();
671                 switch (exitCode)
672                 {
673                         case -1:
674                         case  0: log(QLatin1String("DONE: Transfer completed successfully."), "");                     break;
675                         case  6: log(QLatin1String("ERROR: Remote host could not be resolved!"), "");                  break;
676                         case  7: log(QLatin1String("ERROR: Connection to remote host could not be established!"), ""); break;
677                         case 22: log(QLatin1String("ERROR: Requested URL was not found or returned an error!"), "");   break;
678                         case 28: log(QLatin1String("ERROR: Operation timed out !!!"), "");                             break;
679                         default: log(QString().sprintf("ERROR: Terminated with unknown code %d", exitCode), "");       break;
680                 }
681                 return (exitCode == 0);
682         }
683         
684         return false; /*aborted*/
685 }
686
687 bool MUtils::UpdateChecker::checkSignature(const QString &file, const QString &signature)
688 {
689         if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
690         {
691                 qWarning("CheckSignature: File and signature should be in same folder!");
692                 return false;
693         }
694
695         QString keyRingPath(m_binaryKeys);
696         bool removeKeyring = false;
697         if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
698         {
699                 keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
700                 removeKeyring = true;
701                 if (!QFile::copy(m_binaryKeys, keyRingPath))
702                 {
703                         qWarning("CheckSignature: Failed to copy the key-ring file!");
704                         return false;
705                 }
706         }
707
708         QProcess process;
709         init_process(process, QFileInfo(file).absolutePath());
710
711         QEventLoop loop;
712         connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
713         connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
714         connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
715
716         process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(keyRingPath).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
717
718         if (!process.waitForStarted())
719         {
720                 if (removeKeyring)
721                 {
722                         remove_file(keyRingPath);
723                 }
724                 return false;
725         }
726
727         while (process.state() != QProcess::NotRunning)
728         {
729                 loop.exec();
730                 while (process.canReadLine())
731                 {
732                         const QString line = QString::fromLatin1(process.readLine()).simplified();
733                         if (!line.isEmpty())
734                         {
735                                 log(line);
736                         }
737                 }
738         }
739
740         if (removeKeyring)
741         {
742                 remove_file(keyRingPath);
743         }
744
745         log(QString().sprintf("Exited with code %d", process.exitCode()));
746         return (process.exitCode() == 0);
747 }
748
749 ////////////////////////////////////////////////////////////
750 // SLOTS
751 ////////////////////////////////////////////////////////////
752
753 /*NONE*/
754
755 ////////////////////////////////////////////////////////////
756 // EVENTS
757 ////////////////////////////////////////////////////////////
758
759 /*NONE*/