OSDN Git Service

Use simplified() method to clean-up input lines.
[mutilities/MUtilities.git] / src / UpdateChecker.cpp
index 3cf5dc9..a829f41 100644 (file)
@@ -35,6 +35,7 @@
 #include <QElapsedTimer>
 #include <QSet>
 #include <QHash>
+#include <QQueue>
 
 #include "Mirrors.h"
 
@@ -42,9 +43,9 @@
 // CONSTANTS
 ///////////////////////////////////////////////////////////////////////////////
 
-static const char *header_id = "!Update";
+static const char *GLOBALHEADER_ID = "!Update";
 
-static const char *mirror_url_postfix[] = 
+static const char *MIRROR_URL_POSTFIX[] = 
 {
        "update.ver",
        "update_beta.ver",
@@ -59,6 +60,10 @@ static const int DOWNLOAD_TIMEOUT = 30000;
 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
 static char *USER_AGENT_STR = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"; /*use something innocuous*/
 
+////////////////////////////////////////////////////////////
+// Utility Macros
+////////////////////////////////////////////////////////////
+
 #define CHECK_CANCELLED() do \
 { \
        if(MUTILS_BOOLIFY(m_cancelled)) \
@@ -72,28 +77,27 @@ static char *USER_AGENT_STR = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Geck
 } \
 while(0)
 
+#define LOG_MESSAGE_HELPER(X) do \
+{ \
+       if (!(X).isNull()) \
+       { \
+               emit messageLogged((X)); \
+       } \
+} \
+while(0)
+
+#define STRICMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
+
 ////////////////////////////////////////////////////////////
 // Helper Functions
 ////////////////////////////////////////////////////////////
 
-static int getMaxProgress(void)
-{
-       int counter = 0;
-       while (update_mirrors[counter])
-       {
-               counter++;
-       }
-       counter += MIN_CONNSCORE + QUICK_MIRRORS + 2;
-       return counter; ;
-}
-
-static QStringList buildRandomList(const char *const values[])
+static QQueue<QString> buildRandomList(const char *const *values)
 {
-       QStringList list;
-       for (int index = 0; values[index]; index++)
+       QQueue<QString> list;
+       while(*values)
        {
-               const int pos = MUtils::next_rand_u32() % (index + 1);
-               list.insert(pos, QString::fromLatin1(values[index]));
+               list.insert(MUtils::next_rand_u32(list.size() + 1), QString::fromLatin1(*(values++)));
        }
        return list;
 }
@@ -127,15 +131,13 @@ void MUtils::UpdateCheckerInfo::resetInfo(void)
 
 bool MUtils::UpdateCheckerInfo::isComplete(void)
 {
-       if(this->m_buildNo < 1)                return false;
-       if(this->m_buildDate.year() < 2010)    return false;
-       if(this->m_downloadSite.isEmpty())     return false;
-       if(this->m_downloadAddress.isEmpty())  return false;
-       if(this->m_downloadFilename.isEmpty()) return false;
-       if(this->m_downloadFilecode.isEmpty()) return false;
-       if(this->m_downloadChecksum.isEmpty()) return false;
-
-       return true;
+       return (this->m_buildNo > 0) &&
+               (this->m_buildDate.year() >= 2010) &&
+               (!this->m_downloadSite.isEmpty()) &&
+               (!this->m_downloadAddress.isEmpty()) &&
+               (!this->m_downloadFilename.isEmpty()) &&
+               (!this->m_downloadFilecode.isEmpty()) &&
+               (!this->m_downloadChecksum.isEmpty());
 }
 
 ////////////////////////////////////////////////////////////
@@ -152,7 +154,7 @@ MUtils::UpdateChecker::UpdateChecker(const QString &binCurl, const QString &binG
        m_installedBuildNo(installedBuildNo),
        m_betaUpdates(betaUpdates),
        m_testMode(testMode),
-       m_maxProgress(getMaxProgress()),
+       m_maxProgress(MIN_CONNSCORE + 5),
        m_environment(initEnvVars())
 {
        m_status = UpdateStatus_NotStartedYet;
@@ -205,33 +207,35 @@ void MUtils::UpdateChecker::checkForUpdates(void)
        const int networkStatus = OS::network_status();
        if(networkStatus == OS::NETWORK_TYPE_NON)
        {
-               log("Operating system reports that the computer is currently offline !!!");
-               setProgress(m_maxProgress);
-               setStatus(UpdateStatus_ErrorNoConnection);
-               return;
+               if (!MUtils::OS::arguments().contains("ignore-network-status"))
+               {
+                       log("Operating system reports that the computer is currently offline !!!");
+                       setProgress(m_maxProgress);
+                       setStatus(UpdateStatus_ErrorNoConnection);
+                       return;
+               }
        }
        
-       msleep(500);
+       msleep(333);
        setProgress(1);
 
        // ----- Test Known Hosts Connectivity ----- //
 
        int connectionScore = 0;
-       QStringList mirrorList = buildRandomList(known_hosts);
+       QQueue<QString> mirrorList = buildRandomList(known_hosts);
 
-       for(int connectionTimout = 1000; connectionTimout <= MAX_CONN_TIMEOUT; connectionTimout *= 2)
+       for(int connectionTimeout = 1000; connectionTimeout <= MAX_CONN_TIMEOUT; connectionTimeout *= 2)
        {
                QElapsedTimer elapsedTimer;
                elapsedTimer.start();
-               const int globalTimout = 2 * MIN_CONNSCORE * connectionTimout;
-               while (!elapsedTimer.hasExpired(globalTimout))
+               const int globalTimeout = 2 * MIN_CONNSCORE * connectionTimeout, count = mirrorList.count();
+               for(int i = 0; i < count; ++i)
                {
-                       const QString hostName = mirrorList.takeFirst();
-                       if (tryContactHost(hostName, connectionTimout))
+                       Q_ASSERT(!mirrorList.isEmpty());
+                       const QString hostName = mirrorList.dequeue();
+                       if (tryContactHost(hostName, connectionTimeout))
                        {
-                               connectionScore += 1;
-                               setProgress(qBound(1, connectionScore + 1, MIN_CONNSCORE + 1));
-                               elapsedTimer.restart();
+                               setProgress(1 + (++connectionScore));
                                if (connectionScore >= MIN_CONNSCORE)
                                {
                                        goto endLoop; /*success*/
@@ -239,10 +243,13 @@ void MUtils::UpdateChecker::checkForUpdates(void)
                        }
                        else
                        {
-                               mirrorList.append(hostName); /*re-schedule*/
+                               mirrorList.enqueue(hostName);
+                               if(elapsedTimer.hasExpired(globalTimeout))
+                               {
+                                       break; /*timer expired*/
+                               }
                        }
                        CHECK_CANCELLED();
-                       msleep(1);
                }
        }
 
@@ -265,7 +272,6 @@ endLoop:
 
        while(!mirrorList.isEmpty())
        {
-               setProgress(m_progress + 1);
                const QString currentMirror = mirrorList.takeFirst();
                const bool isQuick = (mirrorCount++ < QUICK_MIRRORS);
                if(tryUpdateMirror(m_updateInfo.data(), currentMirror, isQuick))
@@ -280,13 +286,9 @@ endLoop:
                CHECK_CANCELLED();
                msleep(1);
        }
-       
-       while (m_progress < m_maxProgress)
-       {
-               msleep(16);
-               setProgress(m_progress + 1);
-               CHECK_CANCELLED();
-       }
+
+       msleep(333);
+       setProgress(MIN_CONNSCORE + 5);
 
        // ----- Generate final result ----- //
 
@@ -313,24 +315,24 @@ endLoop:
 
 void MUtils::UpdateChecker::testMirrorsList(void)
 {
-       // ----- Test update mirrors ----- //
-
-       QStringList mirrorList;
+       QQueue<QString> mirrorList;
        for(int i = 0; update_mirrors[i]; i++)
        {
-               mirrorList << QString::fromLatin1(update_mirrors[i]);
+               mirrorList.enqueue(QString::fromLatin1(update_mirrors[i]));
        }
 
+       // ----- Test update mirrors ----- //
+
        qDebug("\n[Mirror Sites]");
        log("Testing all known mirror sites...", "", "---");
 
        UpdateCheckerInfo updateInfo;
        while (!mirrorList.isEmpty())
        {
-               const QString currentMirror = mirrorList.takeFirst();
+               const QString currentMirror = mirrorList.dequeue();
                bool success = false;
                qDebug("Testing: %s", MUTILS_L1STR(currentMirror));
-               log("", "Testing:", currentMirror, "");
+               log("", "Testing mirror:", currentMirror, "");
                for (quint8 attempt = 0; attempt < 3; ++attempt)
                {
                        updateInfo.resetInfo();
@@ -349,25 +351,25 @@ void MUtils::UpdateChecker::testMirrorsList(void)
 
        // ----- Test known hosts ----- //
 
-       QStringList knownHostList;
+       mirrorList.clear();
        for (int i = 0; known_hosts[i]; i++)
        {
-               knownHostList << QString::fromLatin1(known_hosts[i]);
+               mirrorList.enqueue(QString::fromLatin1(known_hosts[i]));
        }
 
        qDebug("\n[Known Hosts]");
        log("Testing all known hosts...", "", "---");
 
-       while(!knownHostList.isEmpty())
+       while(!mirrorList.isEmpty())
        {
-               const QString currentHost = knownHostList.takeFirst();
+               const QString currentHost = mirrorList.dequeue();
                qDebug("Testing: %s", MUTILS_L1STR(currentHost));
-               log(QLatin1String(""), "Testing:", currentHost, "");
+               log(QLatin1String(""), "Testing host:", currentHost, "");
                if (!tryContactHost(currentHost, DOWNLOAD_TIMEOUT))
                {
                        qWarning("\nConnectivity test FAILED on the following host:\n%s\n", MUTILS_L1STR(currentHost));
                }
-               log("", "---");
+               log("---");
        }
 }
 
@@ -386,28 +388,29 @@ void MUtils::UpdateChecker::setStatus(const int status)
 
 void MUtils::UpdateChecker::setProgress(const int progress)
 {
-       if(m_progress != progress)
+       const int value = qBound(0, progress, m_maxProgress);
+       if(m_progress != value)
        {
-               m_progress = progress;
-               emit progressChanged(progress);
+               emit progressChanged(m_progress = value);
        }
 }
 
 void MUtils::UpdateChecker::log(const QString &str1, const QString &str2, const QString &str3, const QString &str4)
 {
-       if(!str1.isNull()) emit messageLogged(str1);
-       if(!str2.isNull()) emit messageLogged(str2);
-       if(!str3.isNull()) emit messageLogged(str3);
-       if(!str4.isNull()) emit messageLogged(str4);
+       LOG_MESSAGE_HELPER(str1);
+       LOG_MESSAGE_HELPER(str2);
+       LOG_MESSAGE_HELPER(str3);
+       LOG_MESSAGE_HELPER(str4);
 }
 
 bool MUtils::UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const QString &url, const bool &quick)
 {
        bool success = false;
-       log("", "Trying mirror:", url, "");
+       log("", "Trying update mirror:", url, "");
 
        if (quick)
        {
+               setProgress(MIN_CONNSCORE + 1);
                if (!tryContactHost(QUrl(url).host(), (MAX_CONN_TIMEOUT / 8)))
                {
                        log("", "Mirror is too slow, skipping!");
@@ -419,53 +422,91 @@ bool MUtils::UpdateChecker::tryUpdateMirror(UpdateCheckerInfo *updateInfo, const
        const QString outFileVers = QString("%1/%2.ver").arg(temp_folder(), randPart);
        const QString outFileSign = QString("%1/%2.sig").arg(temp_folder(), randPart);
 
-       if (getUpdateInfo(url, outFileVers, outFileSign))
+       if (!getUpdateInfo(url, outFileVers, outFileSign))
        {
-               log("Download completed, verifying signature:", "");
-               if (checkSignature(outFileVers, outFileSign))
-               {
-                       log("", "Signature is valid, parsing info:", "");
-                       success = parseVersionInfo(outFileVers, updateInfo);
-               }
-               else
-               {
-                       log("", "Bad signature, take care !!!");
-               }
+               log("", "Oops: Download of update information has failed!");
+               goto cleanUp;
        }
-       else
+
+       log("Download completed, verifying signature:", "");
+       setProgress(MIN_CONNSCORE + 4);
+       if (!checkSignature(outFileVers, outFileSign))
        {
-               log("", "Download has failed!");
+               log("", "Bad signature detected, take care !!!");
+               goto cleanUp;
        }
 
+       log("", "Signature is valid, parsing update information:", "");
+       success = parseVersionInfo(outFileVers, updateInfo);
+
+cleanUp:
        QFile::remove(outFileVers);
        QFile::remove(outFileSign);
-       
        return success;
 }
 
 bool MUtils::UpdateChecker::getUpdateInfo(const QString &url, const QString &outFileVers, const QString &outFileSign)
 {
-       log("Downloading update info:", "");
-       if(getFile(QUrl(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileVers))
+       log("Downloading update information:", "");
+       setProgress(MIN_CONNSCORE + 2);
+       if(getFile(QUrl(QString("%1%2").arg(url, MIRROR_URL_POSTFIX[m_betaUpdates ? 1 : 0])), outFileVers))
        {
                if (!m_cancelled)
                {
                        log( "Downloading signature file:", "");
-                       if (getFile(QUrl(QString("%1%2.sig2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0])), outFileSign))
+                       setProgress(MIN_CONNSCORE + 3);
+                       if (getFile(QUrl(QString("%1%2.sig2").arg(url, MIRROR_URL_POSTFIX[m_betaUpdates ? 1 : 0])), outFileSign))
                        {
-                               return true;
+                               return true; /*completed*/
                        }
                }
        }
        return false;
 }
 
-bool MUtils::UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *updateInfo)
-{
-       QRegExp value("^(\\w+)=(.+)$");
-       QRegExp section("^\\[(.+)\\]$");
+//----------------------------------------------------------
+// PARSE UPDATE INFO
+//----------------------------------------------------------
 
-       QDate updateInfoDate;
+#define _CHECK_HEADER(ID,NAME) \
+       if (STRICMP(name, (NAME))) \
+       { \
+               sectionId = (ID); \
+               continue; \
+       }
+
+#define _PARSE_TEXT(OUT,KEY) \
+       if (STRICMP(key, (KEY))) \
+       { \
+               (OUT) = val; \
+               break; \
+       }
+
+#define _PARSE_UINT(OUT,KEY) \
+       if (STRICMP(key, (KEY))) \
+       { \
+               bool _ok = false; \
+               const unsigned int _tmp = val.toUInt(&_ok); \
+               if (_ok) \
+               { \
+                       (OUT) = _tmp; \
+                       break; \
+               } \
+       }
+
+#define _PARSE_DATE(OUT,KEY) \
+       if (STRICMP(key, (KEY))) \
+       { \
+               const QDate _tmp = QDate::fromString(val, Qt::ISODate); \
+               if (_tmp.isValid()) \
+               { \
+                       (OUT) = _tmp; \
+                       break; \
+               } \
+       }
+
+bool MUtils::UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerInfo *const updateInfo)
+{
        updateInfo->resetInfo();
 
        QFile data(file);
@@ -474,93 +515,73 @@ bool MUtils::UpdateChecker::parseVersionInfo(const QString &file, UpdateCheckerI
                qWarning("Cannot open update info file for reading!");
                return false;
        }
-       
-       bool inHdr = false;
-       bool inSec = false;
-       
+
+       QDate updateInfoDate;
+       int sectionId = 0;
+       QRegExp regex_sec("^\\[(.+)\\]$"), regex_val("^([^=]+)=(.+)$");
+
        while(!data.atEnd())
        {
-               QString line = QString::fromLatin1(data.readLine()).trimmed();
-               if(section.indexIn(line) >= 0)
+               QString line = QString::fromLatin1(data.readLine()).simplified();
+               if (regex_sec.indexIn(line) >= 0)
                {
-                       log(QString("Sec: [%1]").arg(section.cap(1)));
-                       inSec = (section.cap(1).compare(m_applicationId, Qt::CaseInsensitive) == 0);
-                       inHdr = (section.cap(1).compare(QString::fromLatin1(header_id), Qt::CaseInsensitive) == 0);
+                       sectionId = 0; /*unknown section*/
+                       const QString name = regex_sec.cap(1).trimmed();
+                       log(QString("Sec: [%1]").arg(name));
+                       _CHECK_HEADER(1, GLOBALHEADER_ID)
+                       _CHECK_HEADER(2, m_applicationId)
                        continue;
                }
-               if(inSec && (value.indexIn(line) >= 0))
+               if (regex_val.indexIn(line) >= 0)
                {
-                       log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
-                       if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
-                       {
-                               bool ok = false;
-                               const unsigned int temp = value.cap(2).toUInt(&ok);
-                               if(ok) updateInfo->m_buildNo = temp;
-                       }
-                       else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
-                       {
-                               const QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
-                               if(temp.isValid()) updateInfo->m_buildDate = temp;
-                       }
-                       else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
-                       {
-                               updateInfo->m_downloadSite = value.cap(2).trimmed();
-                       }
-                       else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
-                       {
-                               updateInfo->m_downloadAddress = value.cap(2).trimmed();
-                       }
-                       else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
+                       const QString key = regex_val.cap(1).trimmed();
+                       const QString val = regex_val.cap(2).trimmed();
+                       log(QString("Val: \"%1\" = \"%2\"").arg(key, val));
+                       switch (sectionId)
                        {
-                               updateInfo->m_downloadFilename = value.cap(2).trimmed();
-                       }
-                       else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
-                       {
-                               updateInfo->m_downloadFilecode = value.cap(2).trimmed();
-                       }
-                       else if(value.cap(1).compare("DownloadChecksum", Qt::CaseInsensitive) == 0)
-                       {
-                               updateInfo->m_downloadChecksum = value.cap(2).trimmed();
-                       }
-               }
-               if(inHdr && (value.indexIn(line) >= 0))
-               {
-                       log(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
-                       if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
-                       {
-                               QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
-                               if(temp.isValid()) updateInfoDate = temp;
+                       case 1:
+                               _PARSE_DATE(updateInfoDate, "TimestampCreated")
+                               break;
+                       case 2:
+                               _PARSE_UINT(updateInfo->m_buildNo,          "BuildNo")
+                               _PARSE_DATE(updateInfo->m_buildDate,        "BuildDate")
+                               _PARSE_TEXT(updateInfo->m_downloadSite,     "DownloadSite")
+                               _PARSE_TEXT(updateInfo->m_downloadAddress,  "DownloadAddress")
+                               _PARSE_TEXT(updateInfo->m_downloadFilename, "DownloadFilename")
+                               _PARSE_TEXT(updateInfo->m_downloadFilecode, "DownloadFilecode")
+                               _PARSE_TEXT(updateInfo->m_downloadChecksum, "DownloadChecksum")
+                               break;
                        }
                }
        }
 
-       if(!updateInfoDate.isValid())
+       if (!updateInfo->isComplete())
        {
-               updateInfo->resetInfo();
-               log("WARNING: Version info timestamp is missing!");
-               return false;
+               log("", "WARNING: Update information is incomplete!");
+               goto failure;
        }
-       
-       const QDate currentDate = OS::current_date();
-       if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < currentDate)
-       {
-               updateInfo->resetInfo();
-               log(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
-               return false;
-       }
-       else if(currentDate < updateInfoDate)
+
+       if(updateInfoDate.isValid())
        {
-               log("Version info is from the future, take care!");
-               qWarning("Version info is from the future, take care!");
+               const QDate expiredDate = updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS);
+               if (expiredDate < OS::current_date())
+               {
+                       log("", QString("WARNING: Update information has expired at %1!").arg(expiredDate.toString(Qt::ISODate)));
+                       goto failure;
+               }
        }
-       
-       if(!updateInfo->isComplete())
+       else
        {
-               log("WARNING: Version info is incomplete!");
-               return false;
+               log("", "WARNING: Timestamp is missing from update information header!");
+               goto failure;
        }
 
-       return true;
+       log("", "Success: Update information is complete.");
+       return true; /*success*/
+
+failure:
+       updateInfo->resetInfo();
+       return false;
 }
 
 //----------------------------------------------------------
@@ -589,7 +610,7 @@ bool MUtils::UpdateChecker::getFile(const QUrl &url, const QString &outFile, con
        args << "-e" << QString("%1://%2/;auto").arg(url.scheme(), url.host());
        args << "-o" << output.fileName() << url.toString();
 
-       return invokeCurl(args, output.absolutePath(), DOWNLOAD_TIMEOUT);
+       return execCurl(args, output.absolutePath(), DOWNLOAD_TIMEOUT);
 }
 
 bool MUtils::UpdateChecker::tryContactHost(const QString &hostname, const int &timeoutMsec)
@@ -601,136 +622,133 @@ bool MUtils::UpdateChecker::tryContactHost(const QString &hostname, const int &t
        args << "-A" << USER_AGENT_STR;
        args << "-o" << OS::null_device() << QString("http://%1/").arg(hostname);
        
-       return invokeCurl(args, temp_folder(), timeoutMsec);
+       return execCurl(args, temp_folder(), timeoutMsec);
 }
 
-bool MUtils::UpdateChecker::invokeCurl(const QStringList &args, const QString &workingDir, const int timeout)
+bool MUtils::UpdateChecker::checkSignature(const QString &file, const QString &signature)
 {
-       QProcess process;
-       init_process(process, workingDir, true, NULL, m_environment.data());
-
-       QEventLoop loop;
-       connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
-       connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
-       connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
-
-       QTimer timer;
-       timer.setSingleShot(true);
-       connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
-
-       process.start(m_binaryCurl, args);
-       if (!process.waitForStarted())
+       if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
        {
+               qWarning("CheckSignature: File and signature should be in same folder!");
                return false;
        }
 
-       bool bAborted = false;
-       timer.start(qMax(2 * timeout, 2500));
-
-       while (process.state() != QProcess::NotRunning)
+       QString keyRingPath(m_binaryKeys);
+       bool removeKeyring = false;
+       if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
        {
-               loop.exec();
-               while (process.canReadLine())
-               {
-                       const QString line = QString::fromLatin1(process.readLine()).simplified();
-                       if ((!line.isEmpty()) && line.compare(QLatin1String("<")) && line.compare(QLatin1String(">")))
-                       {
-                               log(line);
-                       }
-               }
-               const bool bCancelled = MUTILS_BOOLIFY(m_cancelled);
-               if (bAborted = (bCancelled || ((!timer.isActive()) && (!process.waitForFinished(15)))))
+               keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
+               removeKeyring = true;
+               if (!QFile::copy(m_binaryKeys, keyRingPath))
                {
-                       log(bCancelled ? "CANCELLED BY USER !!!" : "PROCESS TIMEOUT !!!", "");
-                       qWarning("WARNING: cURL process %s!", bCancelled ? "cancelled" : "timed out");
-                       break; /*abort process*/
+                       qWarning("CheckSignature: Failed to copy the key-ring file!");
+                       return false;
                }
        }
 
-       timer.stop();
-       timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
+       QStringList args;
+       args << QStringList() << "--homedir" << ".";
+       args << "--keyring" << QFileInfo(keyRingPath).fileName();
+       args << QFileInfo(signature).fileName();
+       args << QFileInfo(file).fileName();
 
-       if (bAborted)
+       const int exitCode = execProcess(m_binaryGnuPG, args, QFileInfo(file).absolutePath(), DOWNLOAD_TIMEOUT);
+       if (exitCode != INT_MAX)
        {
-               process.kill();
-               process.waitForFinished(-1);
-               return false;
+               log(QString().sprintf("Exited with code %d", exitCode));
        }
 
-       const int exitCode = process.exitCode();
-       switch (exitCode)
+       if (removeKeyring)
        {
-               case  0: log(QLatin1String("DONE: Transfer completed successfully."), "");                     break;
-               case  6: log(QLatin1String("ERROR: Remote host could not be resolved!"), "");                  break;
-               case  7: log(QLatin1String("ERROR: Connection to remote host could not be established!"), ""); break;
-               case 22: log(QLatin1String("ERROR: Requested URL was not found or returned an error!"), "");   break;
-               case 28: log(QLatin1String("ERROR: Operation timed out !!!"), "");                             break;
-               default: log(QString().sprintf("ERROR: Terminated with unknown code %d", exitCode), "");       break;
+               remove_file(keyRingPath);
        }
-       
-       return (exitCode == 0);
+
+       return (exitCode == 0); /*completed*/
 }
 
-bool MUtils::UpdateChecker::checkSignature(const QString &file, const QString &signature)
+bool MUtils::UpdateChecker::execCurl(const QStringList &args, const QString &workingDir, const int timeout)
 {
-       if (QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
-       {
-               qWarning("CheckSignature: File and signature should be in same folder!");
-               return false;
-       }
-
-       QString keyRingPath(m_binaryKeys);
-       bool removeKeyring = false;
-       if (QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
+       const int exitCode = execProcess(m_binaryCurl, args, workingDir, timeout + (timeout / 2));
+       if (exitCode != INT_MAX)
        {
-               keyRingPath = make_temp_file(QFileInfo(file).absolutePath(), "gpg");
-               removeKeyring = true;
-               if (!QFile::copy(m_binaryKeys, keyRingPath))
+               switch (exitCode)
                {
-                       qWarning("CheckSignature: Failed to copy the key-ring file!");
-                       return false;
+                       case  0: log(QLatin1String("DONE: Transfer completed successfully."), "");                     break;
+                       case  6: log(QLatin1String("ERROR: Remote host could not be resolved!"), "");                  break;
+                       case  7: log(QLatin1String("ERROR: Connection to remote host could not be established!"), ""); break;
+                       case 22: log(QLatin1String("ERROR: Requested URL was not found or returned an error!"), "");   break;
+                       case 28: log(QLatin1String("ERROR: Operation timed out !!!"), "");                             break;
+                       default: log(QString().sprintf("ERROR: Terminated with unknown code %d", exitCode), "");       break;
                }
        }
 
+       return (exitCode == 0); /*completed*/
+}
+
+int MUtils::UpdateChecker::execProcess(const QString &programFile, const QStringList &args, const QString &workingDir, const int timeout)
+{
        QProcess process;
-       init_process(process, QFileInfo(file).absolutePath());
+       init_process(process, workingDir, true, NULL, m_environment.data());
 
        QEventLoop loop;
        connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
        connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &loop, SLOT(quit()));
        connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
 
-       process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(keyRingPath).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
+       QTimer timer;
+       timer.setSingleShot(true);
+       connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
 
+       process.start(programFile, args);
        if (!process.waitForStarted())
        {
-               if (removeKeyring)
-               {
-                       remove_file(keyRingPath);
-               }
-               return false;
+               log("PROCESS FAILED TO START !!!", "");
+               qWarning("WARNING: %s process could not be created!", MUTILS_UTF8(QFileInfo(programFile).fileName()));
+               return INT_MAX; /*failed to start*/
        }
 
-       while (process.state() == QProcess::Running)
+       bool bAborted = false;
+       timer.start(qMax(timeout, 1500));
+
+       while (process.state() != QProcess::NotRunning)
        {
                loop.exec();
                while (process.canReadLine())
                {
                        const QString line = QString::fromLatin1(process.readLine()).simplified();
-                       if (!line.isEmpty())
+                       if (line.length() > 1)
                        {
                                log(line);
                        }
                }
+               const bool bCancelled = MUTILS_BOOLIFY(m_cancelled);
+               if (bAborted = (bCancelled || ((!timer.isActive()) && (!process.waitForFinished(125)))))
+               {
+                       log(bCancelled ? "CANCELLED BY USER !!!" : "PROCESS TIMEOUT !!!", "");
+                       qWarning("WARNING: %s process %s!", MUTILS_UTF8(QFileInfo(programFile).fileName()), bCancelled ? "cancelled" : "timed out");
+                       break; /*abort process*/
+               }
        }
 
-       if (removeKeyring)
+       timer.stop();
+       timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
+
+       if (bAborted)
        {
-               remove_file(keyRingPath);
+               process.kill();
+               process.waitForFinished(-1);
+       }
+
+       while (process.canReadLine())
+       {
+               const QString line = QString::fromLatin1(process.readLine()).simplified();
+               if (line.length() > 1)
+               {
+                       log(line);
+               }
        }
 
-       log(QString().sprintf("Exited with code %d", process.exitCode()));
-       return (process.exitCode() == 0);
+       return bAborted ? INT_MAX : process.exitCode();
 }
 
 ////////////////////////////////////////////////////////////