From 9fabc0bd3cb496dc77c872993ea2b54cbd2e71bf Mon Sep 17 00:00:00 2001 From: Jonathan Bauer Date: Tue, 21 Feb 2012 19:06:08 +0100 Subject: globals in extra class, new javascript interface classes for fbgui and ndgui, various cleanups in ndgui... --- src/fbgui/CMakeLists.txt | 13 +- src/fbgui/agui.cpp | 4 +- src/fbgui/agui.h | 6 +- src/fbgui/fbgui.cpp | 426 ++++++++-------------- src/fbgui/fbgui.h | 43 --- src/fbgui/globals.cpp | 27 ++ src/fbgui/globals.h | 46 +++ src/fbgui/interfaceconfiguration.cpp | 45 ++- src/fbgui/interfaceconfiguration.h | 12 +- src/fbgui/javascriptinterface.cpp | 166 ++------- src/fbgui/javascriptinterface.h | 22 +- src/fbgui/javascriptinterfacefbgui.cpp | 115 ++++++ src/fbgui/javascriptinterfacefbgui.h | 53 +++ src/fbgui/javascriptinterfacendgui.cpp | 194 ++++++++++ src/fbgui/javascriptinterfacendgui.h | 48 +++ src/fbgui/main.cpp | 1 + src/fbgui/ndgui.cpp | 309 ++-------------- src/fbgui/ndgui.h | 80 ++--- src/fbgui/networkdiscovery.cpp | 630 +++++++++++++-------------------- src/fbgui/networkdiscovery.h | 26 +- src/fbgui/sysinfo.cpp | 8 +- testApp.sh | 3 +- 22 files changed, 1042 insertions(+), 1235 deletions(-) create mode 100644 src/fbgui/globals.cpp create mode 100644 src/fbgui/globals.h create mode 100644 src/fbgui/javascriptinterfacefbgui.cpp create mode 100644 src/fbgui/javascriptinterfacefbgui.h create mode 100644 src/fbgui/javascriptinterfacendgui.cpp create mode 100644 src/fbgui/javascriptinterfacendgui.h diff --git a/src/fbgui/CMakeLists.txt b/src/fbgui/CMakeLists.txt index e0806b5..4502a58 100644 --- a/src/fbgui/CMakeLists.txt +++ b/src/fbgui/CMakeLists.txt @@ -16,16 +16,19 @@ set(QT_USE_QTWEBKIT TRUE) file(GLOB FBGUI_SOURCES *.cpp) file(GLOB FBGUI_HEADERS *.h ../common/*.h) -file(GLOB FBGUI_MOC_HEADERS +file(GLOB FBGUI_MOC_HEADERS +agui.h +console.h +globals.h +fbgui.h downloadmanager.h -interfaceconfiguration.h javascriptinterface.h +javascriptinterfacendgui.h +javascriptinterfacefbgui.h ndgui.h networkdiscovery.h networkmanager.h -fbgui.h -agui.h -console.h) +interfaceconfiguration.h) file(GLOB FBGUI_UIS *.ui) file(GLOB FBGUI_RCS *.qrc) diff --git a/src/fbgui/agui.cpp b/src/fbgui/agui.cpp index 3f2fd68..84c2322 100644 --- a/src/fbgui/agui.cpp +++ b/src/fbgui/agui.cpp @@ -5,6 +5,7 @@ * Author: joe */ +#include "globals.h" #include "agui.h" #include "console.h" @@ -15,9 +16,6 @@ using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr aguiCoreLogger(Logger::getLogger("agui.core")); -QString logFilePath(""); -int debugMode = -1; - agui::agui() { setupLayout(); createActions(); diff --git a/src/fbgui/agui.h b/src/fbgui/agui.h index 0639981..f685c5a 100644 --- a/src/fbgui/agui.h +++ b/src/fbgui/agui.h @@ -10,9 +10,11 @@ #include #include +#include "globals.h" -extern QString logFilePath; -extern int debugMode; + +//extern QString logFilePath; +//extern int debugMode; class agui: public QMainWindow { diff --git a/src/fbgui/fbgui.cpp b/src/fbgui/fbgui.cpp index 5ef9a9c..3a9f686 100644 --- a/src/fbgui/fbgui.cpp +++ b/src/fbgui/fbgui.cpp @@ -1,8 +1,7 @@ #include "fbgui.h" #include "sysinfo.h" #include "downloadmanager.h" -#include "javascriptinterface.h" - +#include "javascriptinterfacefbgui.h" #include #include "qlog4cxx.h" @@ -15,19 +14,6 @@ LoggerPtr coreLogger(Logger::getLogger("fbgui.core")); #include #include -QThread dmThread; -QString ipConfigFilePath(""); -QString binPath(""); -QUrl baseURL(""); -QString downloadPath(""); -int updateInterval = -1; -QString fileToTriggerURL(""); -QString serialLocation(""); -QString sessionID(""); -bool sslSupport; -//int debugMode=-1; -//QString logFilePath(""); - //------------------------------------------------------------------------------------------- /** * A constructor. @@ -40,10 +26,10 @@ bool sslSupport; * @see DownloadManager */ fbgui::fbgui() : - agui(){ + agui() { } -fbgui::~fbgui(){ - dmThread.quit(); +fbgui::~fbgui() { + dmThread.quit(); } /** @@ -52,13 +38,14 @@ fbgui::~fbgui(){ void fbgui::init() { // start fbgui LOG4CXX_DEBUG(coreLogger, "Initializing fbgui..."); + setWindowTitle("fbgui"); - if(sslSupport) + if (sslSupport) LOG4CXX_DEBUG(coreLogger, "SSL enabled."); // initialize javascript interface - JavascriptInterface* jsi = new JavascriptInterface( - _webView->page()->mainFrame()); + JavascriptInterfaceFBGUI* jsi = new JavascriptInterfaceFBGUI( + this->_webView->page()->mainFrame()); QObject::connect(jsi, SIGNAL(quitFbgui()), this, SLOT(close())); QObject::connect(jsi, SIGNAL(shutDownClient()), this, SLOT(shutdownSystem())); @@ -73,10 +60,8 @@ void fbgui::init() { SLOT(notify(const QString&))); QObject::connect(jsi, SIGNAL(requestFile(const QString&)), dm, SLOT(downloadFile(const QString&))); - QObject::connect( - dm, - SIGNAL(updateProgress(const int&, const double&, const QString&)), - jsi, + QObject::connect(dm, + SIGNAL(updateProgress(const int&, const double&, const QString&)), jsi, SLOT(updateProgressBar(const int&, const double&, const QString&))); QObject::connect(dm, SIGNAL(downloadQueueEmpty()), jsi, SLOT( callbackOnFinished())); @@ -88,9 +73,8 @@ void fbgui::init() { loadURL(); - // set properties - setWindowTitle("fbgui"); showFullScreen(); + } //------------------------------------------------------------------------------------------- // Preparations for URL load @@ -102,15 +86,16 @@ void fbgui::init() { * The host is from the URL given through the configuration. */ bool fbgui::checkHost() const { - QHostInfo hostInfo = QHostInfo::fromName(baseURL.host()); - if (hostInfo.error() != QHostInfo::NoError) { - LOG4CXX_DEBUG(coreLogger, "Lookup of " << baseURL.host() << "failed."); - LOG4CXX_DEBUG(coreLogger, "Host can not be reached."); - return false; - } else { - LOG4CXX_DEBUG(coreLogger, "Lookup of " << baseURL.host() << " succeeded."); - return true; - } + QHostInfo hostInfo = QHostInfo::fromName(baseURL.host()); + if (hostInfo.error() != QHostInfo::NoError) { + LOG4CXX_DEBUG(coreLogger, "Lookup of " << baseURL.host() << "failed."); + LOG4CXX_DEBUG(coreLogger, "Host can not be reached."); + return false; + } else { + LOG4CXX_DEBUG(coreLogger, + "Lookup of " << baseURL.host() << " succeeded."); + return true; + } } //------------------------------------------------------------------------------------------- /** @@ -124,155 +109,38 @@ bool fbgui::checkHost() const { * @see fbgui::generatePOSTData() */ void fbgui::loadURL() { - if (checkHost()) { - LOG4CXX_DEBUG(coreLogger, "Loading URL: " << baseURL.toString() << " ..."); - - // Generate POST identification data needed by PBS. - QByteArray postData = generatePOSTData(); - // Generate a Network Request Object - _qnr = new QNetworkRequest(baseURL); - - //Add OpenSLX Certificate to SSLConfiguration - QList certList = QSslCertificate::fromPath(QLatin1String("/usr/lib/ssl/openslx/CA/certs/openslx-cert.pem")); - certList.append(QSslCertificate::fromPath(QLatin1String("/usr/lib/ssl/openslx/CA/certs/pbsfr-cert.pem"))); - setCACertificates(certList); - - //Ignore the SelfSignedCertificateInChain-error for the OpenSLX-Certificate - QSslError error(QSslError::SelfSignedCertificateInChain, certList.at(0)); - _expectedSslErrors.append(error); - - //Add User Certificate to SSLConfiguration - QList userCertList = QSslCertificate::fromPath(QLatin1String("/usr/lib/ssl/openslx/CA/certs/guest-cert.pem")); - setLocalCertificate(userCertList.at(0)); - - //Add User PrivateKey to SSLConfiguration - QFile keyFile("/usr/lib/ssl/openslx/CA/private/guest.pem"); - Q_ASSERT(keyFile.open(QIODevice::ReadOnly)); - QByteArray keyContent = keyFile.readAll(); - setPrivateKey(QSslKey(keyContent, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, QByteArray("guest"))); - - - - //Connect webViews NetworkAccessManager to SSLErrorHandler SLOT - QObject::connect(_webView->page()->networkAccessManager(), - SIGNAL(finished(QNetworkReply*)), - this, - SLOT(httpErrorHandler(QNetworkReply*))); + if (checkHost()) { + LOG4CXX_DEBUG(coreLogger, + "Loading URL: " << baseURL.toString() << " ..."); + + // Generate POST identification data needed by PBS. + QByteArray postData = generatePOSTData(); + // Generate a Network Request Object + QNetworkRequest req(baseURL); + + // show cursor again since user is about to interact. + req.setHeader(QNetworkRequest::ContentTypeHeader, + "application/x-www-form-urlencoded"); + QObject::connect(_webView, SIGNAL(loadFinished(bool)), this, + SLOT(loadURLDone(bool))); + _webView->load(req, QNetworkAccessManager::PostOperation, postData); - //Connect webViews NetworkAccessManager to ErrorHandler SLOT - QObject::connect(_webView->page()->networkAccessManager(), - SIGNAL(sslErrors(QNetworkReply*, const QList & )), - this, - SLOT(sslErrorHandler(QNetworkReply*, const QList & ))); - - // show cursor again since user is about to interact. - //QWSServer::instance()->setCursorVisible(true); //TODO: ?enabled in original - _qnr->setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - QObject::connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(loadURLDone(bool))); - _webView->load(*_qnr, QNetworkAccessManager::PostOperation, postData); - -// ////////////////////TEST/////////////////////// -// QSslSocket qssReg = new QSslSocket(this); -// qssReg.setSslConfiguration(_qnr->sslConfiguration()); -// -// QHttp http = new QHttp(QLatin1String("pbs2.mp.openslx.org"), QHttp::ConnectionModeHttps, 443, this); -// http.setSocket(&qssReg); -// -// //QObject::connect(http, SIGNAL(done(bool)), this, SLOT(done(bool))); -// QObject::connect(&http, SIGNAL(sslErrors(const QList &)), this, -// SLOT(sslErrorHandler(const QList & ))); - - } - // TODO: error page if no host. -} - -void fbgui::loadURLDone(bool success) { - // done contains the success of the loading: false / true - if (!success) { - LOG4CXX_DEBUG(coreLogger, "Loading failed. URL: " << _webView->url().toString()); - LOG4CXX_DEBUG(coreLogger, "You can quit with CTRL + X ..."); - // TODO handle failure properly... - } else { - LOG4CXX_DEBUG(coreLogger, "Loaded URL: " << _webView->url().toString()); - } -} - - -//Handles QNetworkReply SSL Errors -void fbgui::sslErrorHandler(QNetworkReply* reply, const QList & errlist) { - - foreach (QSslError err, errlist) - LOG4CXX_DEBUG(coreLogger, "SSL Error: " << err.error()); - -// QSslConfiguration replySslConf = reply->sslConfiguration(); -// foreach (QSslCertificate cert, replySslConf.peerCertificateChain()) -// LOG4CXX_DEBUG(coreLogger,"Cert info: \n" << cert.toPem()); - - reply->ignoreSslErrors(_expectedSslErrors); -} - -//Handles QNetworkReply Errors -void fbgui::httpErrorHandler(QNetworkReply* reply) { - if(reply->error() != QNetworkReply::NoError ) - LOG4CXX_DEBUG(coreLogger, "HTTP Error: " << reply->errorString()); -} - -//Dump all Certificates in SSLConfiguration -void fbgui::dumpSSLConfiguration(){ - QSslConfiguration sslConfig = _qnr->sslConfiguration(); - - LOG4CXX_DEBUG(coreLogger,"****************SSLConfiguration************************** \n"); - LOG4CXX_DEBUG(coreLogger,"CACertificates: \n"); - foreach (QSslCertificate cert, sslConfig.caCertificates()){ - LOG4CXX_DEBUG(coreLogger,cert.toPem() << "\n"); } - LOG4CXX_DEBUG(coreLogger,"----------------------------------------------------- \n"); - LOG4CXX_DEBUG(coreLogger,"LocalCertificate: \n"); - LOG4CXX_DEBUG(coreLogger,sslConfig.localCertificate().toPem() << "\n"); - LOG4CXX_DEBUG(coreLogger,"----------------------------------------------------- \n"); - LOG4CXX_DEBUG(coreLogger,"Private Key: \n"); - LOG4CXX_DEBUG(coreLogger,sslConfig.privateKey().toPem() << "\n"); - LOG4CXX_DEBUG(coreLogger,"********************************************************** \n"); + // TODO: error page if no host. } -//Saves CACertificates to SslConfiguration -void fbgui::setCACertificates(const QList & certificates){ - - foreach (QSslCertificate cert, certificates){ - LOG4CXX_DEBUG(coreLogger,"Is cert valid: " << cert.isValid()); - LOG4CXX_DEBUG(coreLogger,"Cert Issuer: " << cert.issuerInfo(QSslCertificate::CommonName)); - LOG4CXX_DEBUG(coreLogger,"Cert Subject: " << cert.subjectInfo(QSslCertificate::CommonName)); +void fbgui::loadURLDone(bool success) { + // done contains the success of the loading: false / true + if (!success) { + LOG4CXX_DEBUG(coreLogger, + "Loading failed. URL: " << _webView->url().toString()); + LOG4CXX_DEBUG(coreLogger, "You can quit with CTRL + X ..."); + // TODO handle failure properly... + } else { + LOG4CXX_DEBUG(coreLogger, "Loaded URL: " << _webView->url().toString()); } - - QSslConfiguration sslConfig = _qnr->sslConfiguration(); - - QList caCerts = sslConfig.caCertificates(); - caCerts.append(certificates); - sslConfig.setCaCertificates(caCerts); - _qnr->setSslConfiguration(sslConfig); - -} - -//Saves User Certificate to SslConfiguration -void fbgui::setLocalCertificate(const QSslCertificate& cert){ - LOG4CXX_DEBUG(coreLogger,"Is cert valid: " << cert.isValid()); - LOG4CXX_DEBUG(coreLogger,"Cert Issuer: " << cert.issuerInfo(QSslCertificate::CommonName)); - LOG4CXX_DEBUG(coreLogger,"Cert Subject: " << cert.subjectInfo(QSslCertificate::CommonName)); - - QSslConfiguration sslConfig = _qnr->sslConfiguration(); - sslConfig.setLocalCertificate(cert); - _qnr->setSslConfiguration(sslConfig); -} - -//Saves PrivateKey to SslConfiguration -void fbgui::setPrivateKey(const QSslKey & key){ - LOG4CXX_DEBUG(coreLogger,"Key length: " << key.length()); - QSslConfiguration sslConfig = _qnr->sslConfiguration(); - sslConfig.setPrivateKey(key); - _qnr->setSslConfiguration(sslConfig); } - //------------------------------------------------------------------------------------------- /** * This method generates the POST data body. @@ -289,51 +157,57 @@ void fbgui::setPrivateKey(const QSslKey & key){ * @see SysInfo::getMainboardSerial() */ QByteArray fbgui::generatePOSTData() { - LOG4CXX_DEBUG(coreLogger, "Generating POST data..."); - // use MAC address as base data - SysInfo si; - QByteArray data(si.getInfo("mac").toUtf8()); - // append mainboard serial to the mac address for more unique hardwarehash - QByteArray mbserial(si.getInfo("mbserial").toUtf8()); - if (!mbserial.isEmpty()) - data.append(mbserial); - else { - LOG4CXX_DEBUG(coreLogger, "Mainboard serial was empty. Not appending to base hash data."); - } - LOG4CXX_DEBUG(coreLogger, "[post] Hashing: " << data); - // generate MD5 hash of data - QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); - LOG4CXX_DEBUG(coreLogger, "[post] MD5 Hash: " << hash.toHex()); - - // fetch serial number from usb - QByteArray serial; - QFile file(serialLocation); - if (!file.open(QIODevice::ReadOnly)) { - LOG4CXX_DEBUG(coreLogger, "[post] No such file: " << file.fileName()); - } - // everything ok, read data - serial = file.readAll(); - file.close(); - serial.chop(1); // chop EOF - LOG4CXX_DEBUG(coreLogger, "[post] Serial number is: " << serial); - - // construct final byte array - QByteArray postData("mac="); - postData.append(si.getInfo("mac")); - postData.append("&hardwarehash=" + hash.toHex()); - postData.append("&serialnumber=" + serial); - LOG4CXX_DEBUG(coreLogger, "[post] POST data: " << postData); - return postData; + LOG4CXX_DEBUG(coreLogger, "Generating POST data..."); + // use MAC address as base data + SysInfo si; + QByteArray data; + QByteArray macAdress(si.getInfo("mac").toUtf8()); + if (!macAdress.isEmpty()) + data.append(macAdress); + else { + LOG4CXX_DEBUG(coreLogger, "No readable MAC Address."); + } + // append mainboard serial to the mac address for more unique hardwarehash + QByteArray mbserial(si.getInfo("mbserial").toUtf8()); + if (!mbserial.isEmpty()) + data.append(mbserial); + else { + LOG4CXX_DEBUG(coreLogger, + "Mainboard serial was empty. Not appending to base hash data."); + }LOG4CXX_DEBUG(coreLogger, "[post] Hashing: " << data); + // generate MD5 hash of data + QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); + LOG4CXX_DEBUG(coreLogger, "[post] MD5 Hash: " << hash.toHex()); + + // fetch serial number from usb + QByteArray serial; + QFile file(serialLocation); + if (!file.open(QIODevice::ReadOnly)) { + LOG4CXX_DEBUG(coreLogger, "[post] No such file: " << file.fileName()); + } + // everything ok, read data + serial = file.readAll(); + file.close(); + serial.chop(1); // chop EOF + LOG4CXX_DEBUG(coreLogger, "[post] Serial number is: " << serial); + + // construct final byte array + QByteArray postData("mac="); + postData.append(si.getInfo("mac")); + postData.append("&hardwarehash=" + hash.toHex()); + postData.append("&serialnumber=" + serial); + LOG4CXX_DEBUG(coreLogger, "[post] POST data: " << postData); + return postData; } //------------------------------------------------------------------------------------------- // Preparing Kernel Switch per kexec (initiating Stage 3) //------------------------------------------------------------------------------------------- void fbgui::loadSystem() { - //show loading system page. - //_webView->disconnect(this); - //QObject::connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(prepareKexec())); - _webView->load(QUrl("qrc:/html/loadsystem.html")); - QTimer::singleShot(1000, this, SLOT(prepareKexec())); + //show loading system page. + //_webView->disconnect(this); + //QObject::connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(prepareKexec())); + _webView->load(QUrl("qrc:/html/loadsystem.html")); + QTimer::singleShot(1000, this, SLOT(prepareKexec())); } //------------------------------------------------------------------------------------------- /** @@ -352,55 +226,57 @@ void fbgui::loadSystem() { */ void fbgui::prepareKexec() { - LOG4CXX_DEBUG(coreLogger, "Preparing kexec ..."); - // try to read KCL file that was downloaded. - QFile file(downloadPath + "/kcl"); - if (!file.open(QIODevice::ReadOnly)) { - LOG4CXX_DEBUG(coreLogger, "No such file: " << file.fileName()); - } - // everything ok, read data. - QString kcl = file.readAll(); - file.close(); - LOG4CXX_DEBUG(coreLogger, "KCL from PBS: " << kcl); - - // try to read ipconfig file generated by udhcpc. - file.setFileName("/tmp/ip_config_fbgui"); - if (!file.open(QIODevice::ReadOnly)) { - LOG4CXX_DEBUG(coreLogger, "No such file: " << file.fileName()); - } - // everything ok, read data. - QString ipConfig = file.readAll(); - file.close(); - LOG4CXX_DEBUG(coreLogger, "IP config: " << ipConfig); - - // append ipConfig - kcl.append(" ip="); - kcl.append(ipConfig); - LOG4CXX_DEBUG(coreLogger, "Complete KCL: " << kcl); - - // load the kernel + initramfs + append of kcl into kexec. - QProcess *process = new QProcess(this); - QString cmdline = "kexec -l " + downloadPath.toUtf8() + "/kernel --initrd=" - + downloadPath.toUtf8() + "/initramfs --append=\"" + kcl.toUtf8() - + "\""; - LOG4CXX_DEBUG(coreLogger, "kexec cmdline: " << cmdline); - process->start(cmdline); - bool ret = process->waitForFinished(); - if (!ret) { - LOG4CXX_DEBUG(coreLogger, "Failed to execute: " << cmdline); - LOG4CXX_DEBUG(coreLogger, "Exiting in 5 seconds..."); - QTimer::singleShot(5000, this, SLOT(close())); - } else { - LOG4CXX_DEBUG(coreLogger, "Kexec load was successfull."); - if (debugMode < 0) { - // if process successfully finished, try to run kexec -e - runKexec(); - } else { - LOG4CXX_DEBUG(coreLogger, "Skipping execution of kexec - open debug shell."); - LOG4CXX_DEBUG(coreLogger, "To start the system execute \"kexec -e\" in your shell."); - close(); - } - } + LOG4CXX_DEBUG(coreLogger, "Preparing kexec ..."); + // try to read KCL file that was downloaded. + QFile file(downloadPath + "/kcl"); + if (!file.open(QIODevice::ReadOnly)) { + LOG4CXX_DEBUG(coreLogger, "No such file: " << file.fileName()); + } + // everything ok, read data. + QString kcl = file.readAll(); + file.close(); + LOG4CXX_DEBUG(coreLogger, "KCL from PBS: " << kcl); + + // try to read ipconfig file generated by udhcpc. + file.setFileName("/tmp/ip_config_fbgui"); + if (!file.open(QIODevice::ReadOnly)) { + LOG4CXX_DEBUG(coreLogger, "No such file: " << file.fileName()); + } + // everything ok, read data. + QString ipConfig = file.readAll(); + file.close(); + LOG4CXX_DEBUG(coreLogger, "IP config: " << ipConfig); + + // append ipConfig + kcl.append(" ip="); + kcl.append(ipConfig); + LOG4CXX_DEBUG(coreLogger, "Complete KCL: " << kcl); + + // load the kernel + initramfs + append of kcl into kexec. + QProcess *process = new QProcess(this); + QString cmdline = "kexec -l " + downloadPath.toUtf8() + "/kernel --initrd=" + + downloadPath.toUtf8() + "/initramfs --append=\"" + kcl.toUtf8() + + "\""; + LOG4CXX_DEBUG(coreLogger, "kexec cmdline: " << cmdline); + process->start(cmdline); + bool ret = process->waitForFinished(); + if (!ret) { + LOG4CXX_DEBUG(coreLogger, "Failed to execute: " << cmdline); + LOG4CXX_DEBUG(coreLogger, "Exiting in 5 seconds..."); + QTimer::singleShot(5000, this, SLOT(close())); + } else { + LOG4CXX_DEBUG(coreLogger, "Kexec load was successfull."); + if (debugMode < 0) { + // if process successfully finished, try to run kexec -e + runKexec(); + } else { + LOG4CXX_DEBUG(coreLogger, + "Skipping execution of kexec - open debug shell."); + LOG4CXX_DEBUG(coreLogger, + "To start the system execute \"kexec -e\" in your shell."); + close(); + } + } } //------------------------------------------------------------------------------------------- /** @@ -410,12 +286,12 @@ void fbgui::prepareKexec() { * */ void fbgui::runKexec() { - QProcess *process = new QProcess(this); - process->start("kexec -e"); - if (!process->waitForStarted()) { - LOG4CXX_DEBUG(coreLogger, "Failed to execute: kexec -e"); - LOG4CXX_DEBUG(coreLogger, "Exiting in 5 seconds..."); - QTimer::singleShot(5000, this, SLOT(close())); - //TODO: Handle failure properly... - } + QProcess *process = new QProcess(this); + process->start("kexec -e"); + if (!process->waitForStarted()) { + LOG4CXX_DEBUG(coreLogger, "Failed to execute: kexec -e"); + LOG4CXX_DEBUG(coreLogger, "Exiting in 5 seconds..."); + QTimer::singleShot(5000, this, SLOT(close())); + //TODO: Handle failure properly... + } } diff --git a/src/fbgui/fbgui.h b/src/fbgui/fbgui.h index 8afb496..c300387 100644 --- a/src/fbgui/fbgui.h +++ b/src/fbgui/fbgui.h @@ -25,31 +25,6 @@ #include "agui.h" -// Internal default settings -#define DEFAULT_URL "http://www.google.com" -#define DEFAULT_DOWNLOAD_DIR "/tmp/fbgui" -#define DEFAULT_CONFIG_PATH "/etc/fbgui.conf" -#define DEFAULT_LOG_FILE_PATH "/tmp/fbgui.log" -#define DEFAULT_UPDATE_INTERVAL 1; -#define DEFAULT_QRC_HTML_DIR ":/html" -#define DEFAULT_FILE_TRIGGER "/tmp/fbgui/trigger" -#define DEFAULT_SSL_SUPPORT false; - -// Global settings variables -extern QString logFilePath; -extern QString ipConfigFilePath; -extern QThread dmThread; -extern QString serialLocation; -extern QString fileToTriggerURL; -extern QString sessionID; -extern QString binPath; -extern QString downloadPath; -extern QUrl baseURL; -extern int debugMode; -extern int updateInterval; -extern QString interfaceName; -extern bool sslSupport; - class fbgui : public agui { Q_OBJECT @@ -65,32 +40,14 @@ private: bool checkHost() const; void loadURL(); - //Dump all Certificates in SSLConfiguration - void dumpSSLConfiguration(); QByteArray generatePOSTData(); // QNetworkRequest for the Network Request QNetworkRequest* _qnr; - // List for expected SSL Errors, like selfsigned certificate error - QList _expectedSslErrors; private slots: void loadURLDone(bool success); - //SSL Error Handler for SSL Requests - void sslErrorHandler(QNetworkReply*, const QList &); - - //Error Handler for http Requests - void httpErrorHandler(QNetworkReply*); - - //Sets CaCertificates in QSslConfiguration - void setCACertificates(const QList & ); - - //Sets LocalCertificate in QSslConfiguration - void setLocalCertificate(const QSslCertificate & ); - - //Sets PrivateKey in QSslConfiguration - void setPrivateKey(const QSslKey &); void loadSystem(); // prepares kexec by loading downloaded initramfs, kernel into kexec void prepareKexec(); diff --git a/src/fbgui/globals.cpp b/src/fbgui/globals.cpp new file mode 100644 index 0000000..0d7037c --- /dev/null +++ b/src/fbgui/globals.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include "globals.h" + +// agui globals +QString logFilePath(""); +int debugMode = -1; + +// fbgui globals +QThread dmThread; +QString ipConfigFilePath(""); +QString binPath(""); +QUrl baseURL(""); +QString downloadPath(""); +int updateInterval = -1; +QString fileToTriggerURL(""); +QString serialLocation(""); +QString sessionID(""); +bool sslSupport; + +// ndgui globals +QString gServerIp(""); +bool gAutoUp = true; +QString gSocketServerPath(""); +QString gPathToDhcpExe(""); +QString gInterfaceName(""); diff --git a/src/fbgui/globals.h b/src/fbgui/globals.h new file mode 100644 index 0000000..353bda3 --- /dev/null +++ b/src/fbgui/globals.h @@ -0,0 +1,46 @@ +#ifndef GLOBALS_H_ +#define GLOBALS_H_ + +// fbgui default settings +#define DEFAULT_URL "http://www.google.com" +#define DEFAULT_DOWNLOAD_DIR "/tmp/fbgui" +#define DEFAULT_CONFIG_PATH "/etc/fbgui.conf" +#define DEFAULT_LOG_FILE_PATH "/tmp/fbgui.log" +#define DEFAULT_UPDATE_INTERVAL 1; +#define DEFAULT_QRC_HTML_DIR ":/html" +#define DEFAULT_FILE_TRIGGER "/tmp/fbgui/trigger" +#define DEFAULT_SSL_SUPPORT false; + +// ndgui stuff +#define DEFAULT_PATHTODHCPCDEXE "/bin/cdhcpcd" + +class QString; +class QUrl; +class QThread; + +// agui globals +extern QString logFilePath; +extern int debugMode; + +// fbgui globals +extern QString logFilePath; +extern QString ipConfigFilePath; +extern QThread dmThread; +extern QString serialLocation; +extern QString fileToTriggerURL; +extern QString sessionID; +extern QString binPath; +extern QString downloadPath; +extern QUrl baseURL; +extern int debugMode; +extern int updateInterval; +extern QString gInterfaceName; +extern bool sslSupport; + +// ndgui globals +extern QString gServerIp; +extern bool gAutoUp; +extern QString gSocketServerPath; +extern QString gPathToDhcpExe; + +#endif /* GLOBALS_H_ */ diff --git a/src/fbgui/interfaceconfiguration.cpp b/src/fbgui/interfaceconfiguration.cpp index d9d72df..37dd3f9 100644 --- a/src/fbgui/interfaceconfiguration.cpp +++ b/src/fbgui/interfaceconfiguration.cpp @@ -1,5 +1,5 @@ /** - * @class interfaceconfiguration + * @class InterfaceConfiguration * * @brief reads and stores a interface configuration. * @@ -19,11 +19,10 @@ using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr ndifLogger(Logger::getLogger("fbgui.nd.ifconf")); -interfaceconfiguration::interfaceconfiguration() { - _tag = "[nd:InterfaceConfiguration]"; +InterfaceConfiguration::InterfaceConfiguration() { } -interfaceconfiguration::~interfaceconfiguration() { +InterfaceConfiguration::~InterfaceConfiguration() { // TODO Auto-generated destructor stub } @@ -37,14 +36,14 @@ interfaceconfiguration::~interfaceconfiguration() { * @param pathToConfig * contains the path to the configuration file. */ -bool interfaceconfiguration::readConfigOutOfFile(QString pathToConfig) { +bool InterfaceConfiguration::readConfigOutOfFile(QString pathToConfig) { QFile file(pathToConfig); if (file.exists()) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - LOG4CXX_DEBUG(ndifLogger, _tag << "couldn't open file:" << pathToConfig); + LOG4CXX_DEBUG(ndifLogger, "Couldn't open file:" << pathToConfig); return false; } - LOG4CXX_DEBUG(ndifLogger, _tag << "read config file"); + LOG4CXX_DEBUG(ndifLogger, "read config file"); while (!file.atEnd()) { QString line(file.readLine()); QStringList splitedLine = line.split("="); @@ -81,67 +80,67 @@ bool interfaceconfiguration::readConfigOutOfFile(QString pathToConfig) { } else if (name.compare("DHCPCHADDR") == 0) { this->dhcpchaddr = values; } else { - LOG4CXX_DEBUG(ndifLogger, _tag << "read unknown name" << name << values); + LOG4CXX_DEBUG(ndifLogger, "read unknown name" << name << values); } } } else { - LOG4CXX_DEBUG(ndifLogger, _tag << "file doesn't exist:" << pathToConfig); + LOG4CXX_DEBUG(ndifLogger, "file doesn't exist:" << pathToConfig); return false; } return true; } -QString interfaceconfiguration::getBroadcast() { +QString InterfaceConfiguration::getBroadcast() { return broadcast; } -QString interfaceconfiguration::getClientid() { +QString InterfaceConfiguration::getClientid() { return clientid; } -QString interfaceconfiguration::getDhcpchaddr() { +QString InterfaceConfiguration::getDhcpchaddr() { return dhcpchaddr; } -QString interfaceconfiguration::getDhcpsid() { +QString InterfaceConfiguration::getDhcpsid() { return dhcpsid; } -QString interfaceconfiguration::getDnssearch() { +QString InterfaceConfiguration::getDnssearch() { return dnssearch; } -QString interfaceconfiguration::getDnsservers() { +QString InterfaceConfiguration::getDnsservers() { return dnsservers; } -QString interfaceconfiguration::getGateways() { +QString InterfaceConfiguration::getGateways() { return gateways; } -QString interfaceconfiguration::getGateway() { +QString InterfaceConfiguration::getGateway() { return gateway; } -QString interfaceconfiguration::getHostname() { +QString InterfaceConfiguration::getHostname() { return hostname; } -QString interfaceconfiguration::getInterface() { +QString InterfaceConfiguration::getInterface() { return interface; } -QString interfaceconfiguration::getIpAddress() { +QString InterfaceConfiguration::getIpAddress() { return ipAddress; } -QString interfaceconfiguration::getNetmask() { +QString InterfaceConfiguration::getNetmask() { return netmask; } -QString interfaceconfiguration::getNetwork() { +QString InterfaceConfiguration::getNetwork() { return network; } -QString interfaceconfiguration::getRoutes() { +QString InterfaceConfiguration::getRoutes() { return routes; } diff --git a/src/fbgui/interfaceconfiguration.h b/src/fbgui/interfaceconfiguration.h index 9376fbb..b487623 100644 --- a/src/fbgui/interfaceconfiguration.h +++ b/src/fbgui/interfaceconfiguration.h @@ -18,16 +18,16 @@ #include -class interfaceconfiguration: public QObject +class InterfaceConfiguration: public QObject { Q_OBJECT public: - interfaceconfiguration(); - interfaceconfiguration(const interfaceconfiguration &other); + InterfaceConfiguration(); + InterfaceConfiguration(const InterfaceConfiguration &other); - interfaceconfiguration &operator=(const interfaceconfiguration &other); - virtual ~interfaceconfiguration(); + InterfaceConfiguration &operator=(const InterfaceConfiguration &other); + virtual ~InterfaceConfiguration(); bool readConfigOutOfFile(QString pathToConfig); QString getBroadcast(); @@ -46,8 +46,6 @@ public: QString getRoutes(); private: - QString _tag; - QString ipAddress; QString netmask; QString network; diff --git a/src/fbgui/javascriptinterface.cpp b/src/fbgui/javascriptinterface.cpp index 8260fab..72d0844 100644 --- a/src/fbgui/javascriptinterface.cpp +++ b/src/fbgui/javascriptinterface.cpp @@ -1,8 +1,8 @@ #include "fbgui.h" +#include "ndgui.h" #include "javascriptinterface.h" #include "sysinfo.h" - #include #include "qlog4cxx.h" @@ -10,7 +10,6 @@ using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr jsiLogger(Logger::getLogger("fbgui.jsi")); - //------------------------------------------------------------------------------------------------------- // Initialisation //------------------------------------------------------------------------------------------------------- @@ -21,8 +20,8 @@ LoggerPtr jsiLogger(Logger::getLogger("fbgui.jsi")); * Is of type QWebFrame. */ JavascriptInterface::JavascriptInterface(QWebFrame *parent) { - LOG4CXX_DEBUG(jsiLogger, "Initializing javascript interface..."); - _parent = parent; + LOG4CXX_DEBUG(jsiLogger, "Initializing javascript interface..."); + _targetFrame = parent; } //------------------------------------------------------------------------------------------------------- /** @@ -42,8 +41,8 @@ JavascriptInterface::~JavascriptInterface() { /* destructor dummy */ * @see JavascriptInterface::loadJQuery() */ void JavascriptInterface::attachToDOM() { - _parent->addToJavaScriptWindowObject(QString("fbgui"), this); - loadJQuery(); + _targetFrame->addToJavaScriptWindowObject(QString("fbgui"), this); + loadJQuery(); } //------------------------------------------------------------------------------------------------------- /** @@ -58,88 +57,29 @@ void JavascriptInterface::attachToDOM() { * @see JavascriptInterface::attachToDOM() */ void JavascriptInterface::loadJQuery() { - // to test if this actually works... - QString js; - QString pathToJsDir(DEFAULT_QRC_HTML_DIR); - pathToJsDir.append("/js"); + // to test if this actually works... + QString js; + QString pathToJsDir(DEFAULT_QRC_HTML_DIR); + pathToJsDir.append("/js"); - QDir qrcJSDir(pathToJsDir); - QFileInfoList fiList = qrcJSDir.entryInfoList(); - QFileInfo fi; -foreach(fi, fiList) -{ - if (fi.suffix() == "js") { - //qDebug()<< fi.fileName(); - //LOG4CXX_DEBUG(jsiLogger, fi.fileName()); - if (fi.fileName() != "test.js") { - QFile file; - file.setFileName(pathToJsDir + "/" + fi.fileName()); - file.open(QIODevice::ReadOnly); - js = file.readAll(); - file.close(); + QDir qrcJSDir(pathToJsDir); + QFileInfoList fiList = qrcJSDir.entryInfoList(); + QFileInfo fi; - _parent->evaluateJavaScript(js); - //LOG4CXX_DEBUG(jsiLogger, "evaluated " + fi.fileName()); - } - } -} -} -//------------------------------------------------------------------------------------------------------- -// Javascript functions for webpage -//------------------------------------------------------------------------------------------------------- -/** - * This method start a download. - * - * This method start a download. - * Can be called from inside a JavaScript function of the HTML page. - * Emits the JavascriptInterface::requestFile(const QString) signal. - */ -void JavascriptInterface::startDownload(const QString& filename) { - // ignore if empty filename - if (filename.isEmpty()) { - _parent->evaluateJavaScript("alert(\"No filename!\")"); - return; - } - emit requestFile(filename); -} -//------------------------------------------------------------------------------------------------------- -/** - * This method start a download. - * - * This method start a download. - * Can be called from inside a JavaScript function of the HTML page. - * - * @todo add some more informations - */ -void JavascriptInterface::setCallbackOnFinished(const QString& function) { - LOG4CXX_DEBUG(jsiLogger, "Callback set: " << function); - _callbackOnDownloadsFinished = QString(function); -} -//------------------------------------------------------------------------------------------------------- -/** - * This method delivers system informations. - * - * This method delivers system informations. Type of informations, are defined by - * the parameter. The output of this method depends on the parameter. - * Can be called from inside a JavaScript function of the HTML page. - * - * @param infoName - * Is of type QString. Defines which method will be called. Possible values are: - * - mac - * - ip - * - mbserial - * - usb - * - * @return QString - * the output of the called method or "info_error" if an error occurred - * (e. g. invalid parameter). - * - * @see SysInfo::getInfo(const QString& infoName) - */ -const QString JavascriptInterface::getSysInfo(const QString& info) { - SysInfo si; - return si.getInfo(info); + foreach(fi, fiList) { + if (fi.suffix() == "js") { + QFile file; + file.setFileName(pathToJsDir + "/" + fi.fileName()); + file.open(QIODevice::ReadOnly); + js = file.readAll(); + file.close(); + + _targetFrame->evaluateJavaScript(js); + //LOG4CXX_DEBUG(jsiLogger, "evaluated " + fi.fileName()); + } + } } + //------------------------------------------------------------------------------------------------------- /** * This method quits the whole program. @@ -149,7 +89,7 @@ const QString JavascriptInterface::getSysInfo(const QString& info) { * Emits JavascriptInterface::quitFbgui() signal */ void JavascriptInterface::quit() { - emit quitFbgui(); + emit quitFbgui(); } //------------------------------------------------------------------------------------------------------- @@ -163,7 +103,7 @@ void JavascriptInterface::quit() { * @see fbgui::performShutDown() */ void JavascriptInterface::shutDown() { - emit shutDownClient(); + emit shutDownClient(); } //------------------------------------------------------------------------------------------------------- /** @@ -176,56 +116,20 @@ void JavascriptInterface::shutDown() { * @see fbgui::performReboot() */ void JavascriptInterface::reboot() { - emit rebootClient(); -} -//------------------------------------------------------------------------------------------------------- -// Download Manager information exchange -//------------------------------------------------------------------------------------------------------- -/** - * This method delivers some informations about the downloading file. - * - * This method delivers some informations about the downloading file. - * - * @todo add some more informations - */ -void JavascriptInterface::downloadInfo(const QString& filename, - const double& filesize) { - QString code = QString("downloadInfo('\%1', \%2)").arg(filename).arg( - filesize); - _parent->evaluateJavaScript(code); -} -//------------------------------------------------------------------------------------------------------- -/** - * This method updates the progress bar. - * - * This method calls a Javascript function to update the progress bar of the download. - * Javascript must have a function called "updateProgress" to receive this information. - * - * @todo add some more informations - */ -void JavascriptInterface::updateProgressBar(const int& percent, - const double& speed, const QString& unit) { - if (percent == 0) - return; - QString code = QString("updateProgress(\%1, \%2, '\%3')").arg(percent).arg( - speed).arg(unit); - _parent->evaluateJavaScript(code); + emit rebootClient(); } + //------------------------------------------------------------------------------------------------------- /** * This method sends out messages to Javascript. A corresponding function must be implemented * on the webpage to receive these. */ void JavascriptInterface::notify(const QString& msg) { - LOG4CXX_DEBUG(jsiLogger, "Notifying: " << msg); - QString code = QString("notify('\%1')").arg(msg); - _parent->evaluateJavaScript(code); +LOG4CXX_DEBUG(jsiLogger, "Notifying: " << msg); +QString code = QString("notify('\%1')").arg(msg); +_targetFrame->evaluateJavaScript(code); } + +//------------------------------------------------------------------------------------------------------- +// Network Discovery Communication //------------------------------------------------------------------------------------------------------- -/** - * Sets a callback function for when downloads are finished (will be called when the queue is empty). - */ -void JavascriptInterface::callbackOnFinished() { - QString code = QString("\%1").arg(_callbackOnDownloadsFinished); - _parent->evaluateJavaScript(code); -} diff --git a/src/fbgui/javascriptinterface.h b/src/fbgui/javascriptinterface.h index b15c134..2b3c83f 100644 --- a/src/fbgui/javascriptinterface.h +++ b/src/fbgui/javascriptinterface.h @@ -11,7 +11,7 @@ * General information about OpenSLX can be found under http://openslx.org * * - * Interface for javascript. + * Abstract interface for javascript. * */ @@ -27,17 +27,14 @@ public: JavascriptInterface(QWebFrame* parent); ~JavascriptInterface(); -private: +protected: // pointer to parent - QWebFrame* _parent; - // function to be called withint javascript when downloads are done. - QString _callbackOnDownloadsFinished; + QWebFrame* _targetFrame; + // loads jQuery code void loadJQuery(); signals: - // request the file from download manager - void requestFile(const QString& filename); // quit the application void quitFbgui(); // shut off the system. connected to fbgui::performShutDown() @@ -49,21 +46,10 @@ public slots: // make sure the interface stays attached on webpage reload void attachToDOM(); - // slots for calling from the webpage - void startDownload(const QString& filename); - void setCallbackOnFinished(const QString& function); - const QString getSysInfo(const QString& info); void quit(); void shutDown(); void reboot(); - // callback when downloads are done. - void callbackOnFinished(); - - // slots for information exchange with the download manager. - void updateProgressBar(const int& percent, const double& speed, - const QString& unit); - void downloadInfo(const QString& filename, const double& filesize); void notify(const QString& msg); }; diff --git a/src/fbgui/javascriptinterfacefbgui.cpp b/src/fbgui/javascriptinterfacefbgui.cpp new file mode 100644 index 0000000..d9ff225 --- /dev/null +++ b/src/fbgui/javascriptinterfacefbgui.cpp @@ -0,0 +1,115 @@ +/* + * javascriptinterfacefbgui.cpp + * + * Created on: Feb 21, 2012 + * Author: joe + */ + +#include "javascriptinterfacefbgui.h" +#include "sysinfo.h" + +JavascriptInterfaceFBGUI::JavascriptInterfaceFBGUI(QWebFrame* parent) + : JavascriptInterface(parent){ +} + +JavascriptInterfaceFBGUI::~JavascriptInterfaceFBGUI() { +} + +//------------------------------------------------------------------------------------------------------- +// Javascript functions for webpage +//------------------------------------------------------------------------------------------------------- +/** + * This method start a download. + * + * This method start a download. + * Can be called from inside a JavaScript function of the HTML page. + * Emits the JavascriptInterface::requestFile(const QString) signal. + */ +void JavascriptInterfaceFBGUI::startDownload(const QString& filename) { + // ignore if empty filename + if (filename.isEmpty()) { + _targetFrame->evaluateJavaScript("alert(\"No filename!\")"); + return; + } + emit requestFile(filename); +} +//------------------------------------------------------------------------------------------------------- +/** + * This method start a download. + * + * This method start a download. + * Can be called from inside a JavaScript function of the HTML page. + * + * @todo add some more informations + */ +void JavascriptInterfaceFBGUI::setCallbackOnFinished(const QString& function) { + //LOG4CXX_DEBUG(jsiLogger, "Callback set: " << function); + _callbackOnDownloadsFinished = QString(function); +} +//------------------------------------------------------------------------------------------------------- +/** + * This method delivers system informations. + * + * This method delivers system informations. Type of informations, are defined by + * the parameter. The output of this method depends on the parameter. + * Can be called from inside a JavaScript function of the HTML page. + * + * @param infoName + * Is of type QString. Defines which method will be called. Possible values are: + * - mac + * - ip + * - mbserial + * - usb + * + * @return QString + * the output of the called method or "info_error" if an error occurred + * (e. g. invalid parameter). + * + * @see SysInfo::getInfo(const QString& infoName) + */ +const QString JavascriptInterfaceFBGUI::getSysInfo(const QString& info) { + SysInfo si; + return si.getInfo(info); +} + +//------------------------------------------------------------------------------------------------------- +// Download Manager information exchange +//------------------------------------------------------------------------------------------------------- +/** + * This method delivers some informations about the downloading file. + * + * This method delivers some informations about the downloading file. + * + * @todo add some more informations + */ +void JavascriptInterfaceFBGUI::downloadInfo(const QString& filename, + const double& filesize) { + QString code = QString("downloadInfo('\%1', \%2)").arg(filename).arg( + filesize); + _targetFrame->evaluateJavaScript(code); +} +//------------------------------------------------------------------------------------------------------- +/** + * This method updates the progress bar. + * + * This method calls a Javascript function to update the progress bar of the download. + * Javascript must have a function called "updateProgress" to receive this information. + * + * @todo add some more informations + */ +void JavascriptInterfaceFBGUI::updateProgressBar(const int& percent, + const double& speed, const QString& unit) { + if (percent == 0) + return; + QString code = QString("updateProgress(\%1, \%2, '\%3')").arg(percent).arg( + speed).arg(unit); + _targetFrame->evaluateJavaScript(code); +} +//------------------------------------------------------------------------------------------------------- +/** + * Sets a callback function for when downloads are finished (will be called when the queue is empty). + */ +void JavascriptInterfaceFBGUI::callbackOnFinished() { + QString code = QString("\%1").arg(_callbackOnDownloadsFinished); + _targetFrame->evaluateJavaScript(code); +} diff --git a/src/fbgui/javascriptinterfacefbgui.h b/src/fbgui/javascriptinterfacefbgui.h new file mode 100644 index 0000000..627bdb4 --- /dev/null +++ b/src/fbgui/javascriptinterfacefbgui.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2010,2011 - RZ Uni Freiburg + * Copyright (c) 2010,2011 - OpenSLX Project + * + * This program/file is free software distributed under the GPL version 2. + * See http://openslx.org/COPYING + * + * If you have any feedback please consult http://openslx.org/feedback and + * send your feedback to feedback@openslx.org + * + * General information about OpenSLX can be found under http://openslx.org + * + * + * Custom fbgui interface for javascript. + * + */ + +#ifndef JAVASCRIPTINTERFACEFBGUI_H_ +#define JAVASCRIPTINTERFACEFBGUI_H_ + +#include "javascriptinterface.h" + +class JavascriptInterfaceFBGUI : public JavascriptInterface +{ + Q_OBJECT +public: + JavascriptInterfaceFBGUI(QWebFrame* parent); + virtual ~JavascriptInterfaceFBGUI(); + +public slots: + + // slots for calling from the webpage + void startDownload(const QString& filename); + void setCallbackOnFinished(const QString& function); + const QString getSysInfo(const QString& info); + + // callback when downloads are done. + void callbackOnFinished(); + + // slots for information exchange with the download manager. + void updateProgressBar(const int& percent, const double& speed, + const QString& unit); + void downloadInfo(const QString& filename, const double& filesize); + +private: + // function to be called withint javascript when downloads are done. + QString _callbackOnDownloadsFinished; +signals: + // request the file from download manager + void requestFile(const QString& filename); +}; + +#endif /* JAVASCRIPTINTERFACEFBGUI_H_ */ diff --git a/src/fbgui/javascriptinterfacendgui.cpp b/src/fbgui/javascriptinterfacendgui.cpp new file mode 100644 index 0000000..f300866 --- /dev/null +++ b/src/fbgui/javascriptinterfacendgui.cpp @@ -0,0 +1,194 @@ +/* + * javascriptinterfacendgui.cpp + * + * Created on: Feb 21, 2012 + * Author: joe + */ + +#include "javascriptinterfacendgui.h" + +#include +#include "qlog4cxx.h" + +using namespace log4cxx; +using namespace log4cxx::helpers; +LoggerPtr ndjsiLogger(Logger::getLogger("ndgui.jsi")); + +JavascriptInterfaceNDGUI::JavascriptInterfaceNDGUI(QWebFrame* parent, NetworkDiscovery* nd) + : JavascriptInterface(parent){ + _nd = nd; +} + +JavascriptInterfaceNDGUI::~JavascriptInterfaceNDGUI() { + +} +//------------------------------------------------------------------------------------ +// SLOTS +//------------------------------------------------------------------------------------ +/** + * @brief show abortBoot dialog + * + * @param msg + * the message, displayed in the dialog. + */ +void JavascriptInterfaceNDGUI::abortBoot(const QString msg) { + QString code = QString("abortBootDialog('\%1')").arg(msg); + _targetFrame->evaluateJavaScript(code); +} + +/** + * @brief opens ths chooseInterfaceDialog + * + * @param msg + * the interfaces as json formated string. will be displayed in a select box. + */ +void JavascriptInterfaceNDGUI::chooseInterfaceDialog(const QList ifNameList) { + + QString jsonArr = "["; + for (int i = 0; i < ifNameList.size() - 1; i++) { + jsonArr += "\"" + ifNameList.value(i) + "\","; + } + jsonArr += "\"" + ifNameList.last() + "\"]"; + + QString code = QString("chooseInterfaceDialog(\%1)").arg(jsonArr); + _targetFrame->evaluateJavaScript(code); +} + +/** + * @brief updates the over all status + * + * @param status + * the new status message + */ +void JavascriptInterfaceNDGUI::updateStatus(const QString &status) { + if (status == "") + return; + QString code = QString("updateStatus('\%1')").arg(status); + _targetFrame->evaluateJavaScript(code); +} + +/** + * @brief updates the progress bar for each interface. + * + * @param ifname + * the name ot the interface to update + * + * @param percent + * the progress in percent + */ +void JavascriptInterfaceNDGUI::updateIfProgressBar(const QString &ifName, const int& percent) { + if (percent == 0) + return; + QString code = QString("updateIfProgressBar('\%1',\%2)").arg(ifName).arg(percent); + _targetFrame->evaluateJavaScript(code); +} + +/** + * @brief update the status for each interface + * + * @param ifName + * the name ot the interface to update + * + * @param status + * the new status of the interface. + */ +void JavascriptInterfaceNDGUI::updateIfStatus(const QString &ifName, const QString &status) { + if (ifName == "") + return; + QString code = QString("updateIfStatus('\%1','\%2')").arg(ifName).arg(status); + _targetFrame->evaluateJavaScript(code); +} + +void JavascriptInterfaceNDGUI::addInterface(const QString &ifName) { + if (ifName == "") + return; + QString code = QString("addInterface('\%1')").arg(ifName); + _targetFrame->evaluateJavaScript(code); +} + +/** + * @brief just for debugging. + */ +void JavascriptInterfaceNDGUI::notifyCall(QString msg){ + LOG4CXX_DEBUG(ndjsiLogger, "Javascript notified: " << msg); +} + +//------------------------------------------------------------------------------------ +// INVOKABLES +//------------------------------------------------------------------------------------ + +/** + * @brief read the log file. Log File will be presented inside of a dialog. + */ +QString JavascriptInterfaceNDGUI::readLogFile() { + QString retval("Contents of log file:\n"); + QFile logFile(logFilePath); + if (logFile.exists()) { + if (logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + while (!logFile.atEnd()) { + retval.append(logFile.readLine()); + } + } else { + LOG4CXX_DEBUG(ndjsiLogger, "could not open log file"); + retval = "could not open log file"; + } + } else { + LOG4CXX_DEBUG(ndjsiLogger, + "log file does not exist at: " << logFilePath); + retval = " log file does not exist at: " + logFilePath; + } + return retval; +} + +/** + * @brief fills the drop down box of the manual interface configuration + * dialog. + */ +QVariantList JavascriptInterfaceNDGUI::getManualConfInterfaces() { + LOG4CXX_DEBUG(ndjsiLogger, "call getManualConfInterfaces"); + QVariantList jsonArr; + QString debugOut; + foreach (QString s, _nd->getIfUpList()) { + QVariant e(s); + jsonArr << e; + debugOut += s + "; "; + } + LOG4CXX_DEBUG(ndjsiLogger, "value of jsonArr:" << debugOut); + return jsonArr; +} + +/** + * @brief return a json formated interface configuration + * + * @param ifName + * the name of the interface + */ +QVariantMap JavascriptInterfaceNDGUI::getInterfaceConf(QString ifName) { + InterfaceConfiguration* ifc = _nd->getInterfaceConfig(ifName); + QVariantMap jsonObj; + QList dns; + if (ifc != NULL) { + jsonObj.insert("ipaddr", ifc->getIpAddress()); + jsonObj.insert("netmask", ifc->getNetmask()); + jsonObj.insert("broadcast", ifc->getBroadcast()); + jsonObj.insert("gateway", ifc->getGateway()); + + dns.clear(); + dns = ifc->getDnsservers().trimmed().split(" "); + jsonObj.insert("dns", dns.first()); + } + return jsonObj; +} + +/** + * @brief takes the entered manual configuration dates and delivers it + * to the networkDiscovery for further actions. + * + * @param jsonArr + * a jsonArr which contains the manual entered interface configuration + */ +int JavascriptInterfaceNDGUI::ip4_setManualConfiguration(QVariantMap jsonArr) { + return _nd->ip4_setManualConfiguration(jsonArr); + +} + diff --git a/src/fbgui/javascriptinterfacendgui.h b/src/fbgui/javascriptinterfacendgui.h new file mode 100644 index 0000000..d286d79 --- /dev/null +++ b/src/fbgui/javascriptinterfacendgui.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2010,2011 - RZ Uni Freiburg + * Copyright (c) 2010,2011 - OpenSLX Project + * + * This program/file is free software distributed under the GPL version 2. + * See http://openslx.org/COPYING + * + * If you have any feedback please consult http://openslx.org/feedback and + * send your feedback to feedback@openslx.org + * + * General information about OpenSLX can be found under http://openslx.org + * + * + * Custom ndgui interface for javascript. + * + */ + +#ifndef JAVASCRIPTINTERFACENDGUI_H_ +#define JAVASCRIPTINTERFACENDGUI_H_ + +#include "javascriptinterface.h" +#include "networkdiscovery.h" + +class JavascriptInterfaceNDGUI: public JavascriptInterface { +Q_OBJECT +public: + JavascriptInterfaceNDGUI(QWebFrame* parent, NetworkDiscovery* nd = 0); + virtual ~JavascriptInterfaceNDGUI(); + + Q_INVOKABLE QVariantList getManualConfInterfaces(); + Q_INVOKABLE int ip4_setManualConfiguration(QVariantMap result); + Q_INVOKABLE QString readLogFile(); + Q_INVOKABLE QVariantMap getInterfaceConf(QString ifName); + +public slots: + void abortBoot(QString msg); + void updateIfStatus(const QString &ifName, const QString &status); + void updateStatus(const QString &status); + void updateIfProgressBar(const QString &ifName, const int& percent); + void addInterface(const QString &ifName); + void chooseInterfaceDialog(const QList); + void notifyCall(QString msg); + +private: + NetworkDiscovery* _nd; +}; + +#endif /* JAVASCRIPTINTERFACENDGUI_H_ */ diff --git a/src/fbgui/main.cpp b/src/fbgui/main.cpp index 197ba68..09a1b45 100644 --- a/src/fbgui/main.cpp +++ b/src/fbgui/main.cpp @@ -10,6 +10,7 @@ #include #include "qlog4cxx.h" +#include "globals.h" #include "fbgui.h" #include "ndgui.h" diff --git a/src/fbgui/ndgui.cpp b/src/fbgui/ndgui.cpp index a95d884..40c7cea 100644 --- a/src/fbgui/ndgui.cpp +++ b/src/fbgui/ndgui.cpp @@ -10,6 +10,7 @@ #include "ndgui.h" +#include "javascriptinterfacendgui.h" #include #include "qlog4cxx.h" @@ -18,63 +19,51 @@ using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr ndLogger(Logger::getLogger("fbgui.nd")); - -QString gServerIp(""); -bool gAutoUp = true; -QString gSocketServerPath(""); -QString gPathToDhcpExe(""); -QString interfaceName(""); - - /** * constructor */ ndgui::ndgui() : agui() { -} - +} /** * destructor */ ndgui::~ndgui() { - delete _allowUserChoice; delete _tryAgain; delete _networkDiscovery; - } - - /** * @brief initialize all variables and prepare everything for a successful run */ void ndgui::init() { - LOG4CXX_DEBUG(ndLogger, "Initializing ndgui..."); + setWindowTitle(tr("NetD")); _started = false; _userChoice = false; - _ifNameList.clear(); - _manConfList.clear(); addActions(); _networkDiscovery = new NetworkDiscovery(); - connect(_networkDiscovery, SIGNAL(addInterface(const QString &)), this, + _jsi = new JavascriptInterfaceNDGUI(_webView->page()->mainFrame(), _networkDiscovery); + + + connect(_networkDiscovery, SIGNAL(addInterface(const QString &)), _jsi, SLOT(addInterface( const QString &))); connect(_networkDiscovery, SIGNAL(changeProgressBarValue(const QString & , const int& )), - this, SLOT(updateIfProgressBar(const QString & , const int&))); + _jsi, SLOT(updateIfProgressBar(const QString & , const int&))); connect(_networkDiscovery, SIGNAL(connectionEstablished(QString)), this, SLOT(handleConnectionEstablished(QString))); - connect(_networkDiscovery, SIGNAL(abortBoot(QString)), this, + connect(_networkDiscovery, SIGNAL(abortBoot(QString)), _jsi, SLOT(abortBoot(const QString))); - connect(_networkDiscovery, SIGNAL(updateIfStatus(QString,QString)), this, + connect(_networkDiscovery, SIGNAL(updateIfStatus(QString,QString)), _jsi, SLOT(updateIfStatus(const QString &, const QString &))); - connect(_networkDiscovery, SIGNAL(updateStatus(QString)), this, + connect(_networkDiscovery, SIGNAL(updateStatus(QString)), _jsi, SLOT(updateStatus(const QString&))); connect(_networkDiscovery, SIGNAL(allProcessesFinished()), this, SLOT(handleAllProcessesFinished())); @@ -84,8 +73,8 @@ void ndgui::init() { this, SLOT(continueBootWithoutCheck(QString))); connect(_webView->page()->mainFrame(), SIGNAL( - javaScriptWindowObjectCleared()), this, SLOT(attachToDOM())); - connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(startSingleShot())); + javaScriptWindowObjectCleared()), _jsi, SLOT(attachToDOM())); + connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(startNetworkDiscovery())); if (debugMode > -1) { @@ -93,11 +82,9 @@ void ndgui::init() { } else { _webView->load(QUrl("qrc:html/networkdiscovery.html")); } - - setWindowTitle(tr("NetD")); showFullScreen(); -} +} /** * @brief Add actions @@ -125,25 +112,6 @@ void ndgui::setUserChoiceTrue() { _userChoice = true; } - - -/** - * @brief starts a singleshot event. - * - * is connected to the singleShot event. Triggering this method means - * that we go on with the main NetworkDiscovery screen. - * connects the loadFinished signal of the _webView with the - * startNetworkDiscovery slot and removes the - * action. - */ -void ndgui::startSingleShot() { - - LOG4CXX_DEBUG(ndLogger, "start single shot"); - QTimer::singleShot(3000, this, SLOT(startNetworkDiscovery())); -} - - - /** * @brief start the network discovery * @@ -152,19 +120,15 @@ void ndgui::startSingleShot() { * and starts the networkDiscovery. */ void ndgui::startNetworkDiscovery() { - disconnect(_webView, SIGNAL(loadFinished(bool)), this, - SLOT(startSingleShot())); + //disconnect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(startSingleShot())); if (!_started) { _started = true; - _networkDiscovery->initAndRun(gServerIp, _userChoice, gAutoUp, - logFilePath, gSocketServerPath, gPathToDhcpExe); + _networkDiscovery->initAndRun(_userChoice); } else { LOG4CXX_DEBUG(ndLogger, "NetworkDiscovery already started"); } } - - /** * @brief handle if a interface is able to connect * @@ -192,12 +156,7 @@ void ndgui::handleAllProcessesFinished() { _allowUserChoice->setEnabled(false); if (_ifNameList.size() > 0) { if (_userChoice) { - QString jsonArr = "["; - for (int i = 0; i < _ifNameList.size() - 1; i++) { - jsonArr += "\"" + _ifNameList.value(i) + "\","; - } - jsonArr += "\"" + _ifNameList.last() + "\"]"; - chooseInterfaceDialog(jsonArr); + _jsi->chooseInterfaceDialog(_ifNameList); } else { foreach(QString i, _ifNameList) { @@ -210,12 +169,11 @@ void ndgui::handleAllProcessesFinished() { } else { LOG4CXX_DEBUG(ndLogger, " No usable interfaces found!: " << _networkDiscovery->GetErrorStr()); LOG4CXX_DEBUG(ndLogger, " list is empty"); - abortBoot("No usable interfaces found!" + _jsi->abortBoot("No usable interfaces found!" + _networkDiscovery->GetErrorStr()); } } - /** * @brief continue the boot sequence * @@ -223,43 +181,44 @@ void ndgui::handleAllProcessesFinished() { * will start the fbgui screen. All networkDiscovery signals * will be ignored after this point. */ -//void ndgui::continueBoot(QString ifName, int userChoice) { void ndgui::continueBoot(QString ifName) { if (_networkDiscovery->checkConnectivity(ifName)) { LOG4CXX_DEBUG(ndLogger, " continue with interface: " << ifName); - interfaceName = ifName; + gInterfaceName = ifName; emit initFbgui(); this->close(); } else { - abortBoot( - "Interface was suddenly made unusable. Please check the log and try again."); + _jsi->abortBoot("Interface was suddenly made unusable. Please check the log and try again."); } - } - /** * @brief continue the boot sequence without further checking if the connection is still possible. */ void ndgui::continueBootWithoutCheck(QString ifName) { LOG4CXX_DEBUG(ndLogger, " continue with interface: " << ifName); - interfaceName = ifName; + gInterfaceName = ifName; emit initFbgui(); this->close(); } - +/* slots */ /** - * @brief read the log file. Log File will be presented inside of a dialog. + * @brief adds an interface to the DOM tree. Creates its progress bar and it's status label. + * + * @param ifName + * name of the new interface. */ -QString ndgui::readLogFile() { - LOG4CXX_DEBUG(ndLogger, "show log"); - return _networkDiscovery->readLogFile(); -} - +//void ndgui::addInterface(const QString &ifName) { +// if (ifName == "") +// return; +// _manConfList.append(ifName); +// QString code = QString("addInterface('\%1')").arg(ifName); +// _webView->page()->mainFrame()->evaluateJavaScript(code); +//} /** - * @brief starts the whole application again. + * @brief crashes everything :) */ void ndgui::tryAgain() { LOG4CXX_DEBUG(ndLogger, " try again "); @@ -269,202 +228,8 @@ void ndgui::tryAgain() { //delete _webView; delete _networkDiscovery; - init(); - -} - - -/*test html gui version*/ - -/** - * @brief fills the drop down box of the manual interface configuration - * dialog. - */ -QVariantList ndgui::getManualConfInterfaces() { - LOG4CXX_DEBUG(ndLogger, "call getManualConfInterfaces"); - QVariantList jsonArr; - QString debugOut; - foreach (QString s, _manConfList) { - QVariant e(s); - jsonArr << e; - debugOut += s + "; "; - } - LOG4CXX_DEBUG(ndLogger, "value of jsonArr:" << debugOut); - return jsonArr; -} - - -/** - * @brief return a json formated interface configuration - * - * @param ifName - * the name of the interface - */ -QVariantMap ndgui::getInterfaceConf(QString ifName) { - - return _networkDiscovery->getInterfaceConfig(ifName); -} - - - -/** - * @brief takes the entered manual configuration dates and delivers it - * to the networkDiscovery for further actions. - * - * @param jsonArr - * a jsonArr which contains the manual entered interface configuration - */ -int ndgui::ip4_setManualConfiguration(QVariantMap jsonArr) { - return _networkDiscovery->ip4_setManualConfiguration(jsonArr); - -} - - - -/* slots */ -/************************************************/ -////////////////////////////////////////////////// -/************************************************/ - -/** - * @brief stellt ein ndgui/fbgui Objekt zur verwendung durch die html bereit. - */ -void ndgui::attachToDOM(){ - _webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("fbgui"), this); - loadJQuery(); -} - - - -/** - * @brief load jQuery and js scripts into the page so that all javascript functions will work. - */ -void ndgui::loadJQuery() { - QString js; - QString pathToJsDir(":/html"); - pathToJsDir.append("/js"); - - QDir qrcJSDir(pathToJsDir); - QFileInfoList fiList = qrcJSDir.entryInfoList(); - QFileInfo fi; - foreach(fi, fiList) - { - if (fi.suffix() == "js") { - //LOG4CXX_DEBUG(ndLogger, fi.fileName()); - //LOG4CXX_DEBUG(ndLogger, fi.fileName()); - //if (fi.fileName() != "test.js" && fi.fileName() != "nd-functions.js") { - QFile file; - file.setFileName(pathToJsDir + "/" + fi.fileName()); - file.open(QIODevice::ReadOnly); - js = file.readAll(); - file.close(); - - _webView->page()->mainFrame()->evaluateJavaScript(js); - //LOG4CXX_DEBUG(ndLogger, "evaluated " + fi.fileName()); - //} - } - } -} - - - - -/** - * @brief show abortBoot dialog - * - * @param msg - * the message, displayed in the dialog. - */ -void ndgui::abortBoot(const QString msg) { - QString code = QString("abortBootDialog('\%1')").arg(msg); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - - -/** - * @brief opens ths chooseInterfaceDialog - * - * @param msg - * the interfaces as json formated string. will be displayed in a select box. - */ -void ndgui::chooseInterfaceDialog(const QString msg) { - QString code = QString("chooseInterfaceDialog(\%1)").arg(msg); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - - -/** - * @brief updates the over all status - * - * @param status - * the new status message - */ -void ndgui::updateStatus(const QString &status) { - if (status == "") - return; - QString code = QString("updateStatus('\%1')").arg(status); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - - -/** - * @brief updates the progress bar for each interface. - * - * @param ifname - * the name ot the interface to update - * - * @param percent - * the progress in percent - */ -void ndgui::updateIfProgressBar(const QString &ifName, const int& percent) { - if (percent == 0) - return; - QString code = QString("updateIfProgressBar('\%1',\%2)").arg(ifName).arg(percent); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - - -/** - * @brief update the status for each interface - * - * @param ifName - * the name ot the interface to update - * - * @param status - * the new status of the interface. - */ -void ndgui::updateIfStatus(const QString &ifName, const QString &status) { - if (ifName == "") - return; - QString code = QString("updateIfStatus('\%1','\%2')").arg(ifName).arg(status); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - - -/** - * @brief adds an interface to the DOM tree. Creates its progress bar and it's status label. - * - * @param ifName - * name of the new interface. - */ -void ndgui::addInterface(const QString &ifName) { - if (ifName == "") - return; - _manConfList.append(ifName); - QString code = QString("addInterface('\%1')").arg(ifName); - _webView->page()->mainFrame()->evaluateJavaScript(code); -} - - + _ifNameList.clear(); + _manConfList.clear(); -/** - * @brief just for debugging. - */ -void ndgui::notifyCall(QString msg){ - LOG4CXX_DEBUG(ndLogger, "------ called:" << msg); + init(); } diff --git a/src/fbgui/ndgui.h b/src/fbgui/ndgui.h index 2e214df..379479d 100644 --- a/src/fbgui/ndgui.h +++ b/src/fbgui/ndgui.h @@ -11,8 +11,6 @@ * General information about OpenSLX can be found under http://openslx.org */ - - #ifndef NDGUI_H #define NDGUI_H @@ -20,80 +18,52 @@ #include #include -#include "fbgui.h" #include "agui.h" +#include "javascriptinterfacendgui.h" #include "networkdiscovery.h" - -extern QString gServerIp; -extern bool gAutoUp; -extern QString gSocketServerPath; -extern QString gPathToDhcpExe; - -class ndgui: public agui -{ - Q_OBJECT +class ndgui: public agui { +Q_OBJECT public: - ndgui(); - ~ndgui(); - Q_INVOKABLE QVariantList getManualConfInterfaces(); - Q_INVOKABLE int ip4_setManualConfiguration(QVariantMap result); - Q_INVOKABLE QString readLogFile(); - Q_INVOKABLE QVariantMap getInterfaceConf(QString ifName); + ndgui(); + ~ndgui(); - void init(); + void init(); public slots: - void handleConnectionEstablished(QString ifName); - void abortBoot(QString msg); - void chooseInterfaceDialog(QString msg); - void handleAllProcessesFinished(); - - void continueBoot(QString ifName); - void continueBootWithoutCheck(QString ifName); - void tryAgain(); + void startNetworkDiscovery(); + void handleConnectionEstablished(QString ifName); + void handleAllProcessesFinished(); + void continueBootWithoutCheck(QString ifName); + void tryAgain(); - void startSingleShot(); - void startNetworkDiscovery(); + /* to delete once the new jsi is tested ... */ +// void addInterface(const QString &ifName); + void continueBoot(QString ifName); - /*test for html gui version*/ - void attachToDOM(); - void loadJQuery(); - void addInterface(const QString &ifName); - void updateIfStatus(const QString &ifName, const QString &status); - void updateStatus(const QString &status); - void updateIfProgressBar(const QString &ifName, const int& percent); - void notifyCall(QString msg); signals: - void initFbgui(); + void initFbgui(); private slots: - void setUserChoiceTrue(); + void setUserChoiceTrue(); private: + void addActions(); - void addActions(); - - QString _tag; - - bool _userChoice; - - bool _started; - - QAction* _allowUserChoice; - - QAction* _tryAgain; - - NetworkDiscovery* _networkDiscovery; + NetworkDiscovery* _networkDiscovery; + JavascriptInterfaceNDGUI* _jsi; - QList _ifNameList; // maps interfaceName to its gateway + QAction* _allowUserChoice; + QAction* _tryAgain; - QList _manConfList; + bool _userChoice;bool _started; - QString _manualConfInterfaces; + QList _ifNameList; // maps interfaceName to its gateway + QList _manConfList; + QString _manualConfInterfaces; }; #endif // NDGUI_H diff --git a/src/fbgui/networkdiscovery.cpp b/src/fbgui/networkdiscovery.cpp index ccefb8a..ab14923 100644 --- a/src/fbgui/networkdiscovery.cpp +++ b/src/fbgui/networkdiscovery.cpp @@ -23,18 +23,12 @@ using namespace log4cxx; using namespace log4cxx::helpers; LoggerPtr ndcLogger(Logger::getLogger("fbgui.nd.core")); - - - /** * constructor */ NetworkDiscovery::NetworkDiscovery(QObject *parent) { - _server = new QLocalServer(this); } - - /** * destructor */ @@ -44,13 +38,11 @@ NetworkDiscovery::~NetworkDiscovery() { foreach(QProcess* p, _clientProcessToIfNameMap.keys()) { delete p; } - foreach(interfaceconfiguration* i, _ifcMap.values()) { + foreach(InterfaceConfiguration* i, _ifcMap.values()) { delete i; } } - - /** * initialize all important class members and start the main work. * @@ -75,16 +67,10 @@ NetworkDiscovery::~NetworkDiscovery() { * @param args * additional arguments for the customdhcpcd client. (default value: NULL) */ -void NetworkDiscovery::initAndRun(QString serverIp, bool userChoice, bool autoUp, QString pathToLogFile, QString serverPath, QString pathToExe, - QStringList* args) { +void NetworkDiscovery::initAndRun(bool userChoice, QStringList* args) { - _serverIp = serverIp; _userChoice = userChoice; - _autoUp = autoUp; - _pathToLogFile = pathToLogFile; - _serverPath = serverPath; - _pathToDhcpcdExe = pathToExe; _blocked = false; _numberOfProcesses = 0; _ifUpCountdown = 10; @@ -100,22 +86,24 @@ void NetworkDiscovery::initAndRun(QString serverIp, bool userChoice, bool autoUp _ifcMap.clear(); _server = new QLocalServer(); - if (serverPath != DEFAULT_QTSOCKETADDRESS) { + if (gSocketServerPath != DEFAULT_QTSOCKETADDRESS) { _dhcpcdArguments.append("-q"); - _dhcpcdArguments.append(serverPath); + _dhcpcdArguments.append(gSocketServerPath); } /* delete the file at serverPath. this is necessary since in case the application crashes, the file still - * exists which leads to an error. - */ + * exists which leads to an error. + */ - if(QFile::exists(serverPath)) { - QFile::remove(serverPath); + if (QFile::exists(gSocketServerPath)) { + QFile::remove(gSocketServerPath); } - emit updateStatus("try to create server socket"); - if (!_server->listen(serverPath)) { + emit + updateStatus("try to create server socket"); + if (!_server->listen(gSocketServerPath)) { // emit signal to the gui that a critial error occoured - LOG4CXX_DEBUG(ndcLogger, "Unable to start server: " << _server->errorString()); + LOG4CXX_DEBUG(ndcLogger, + "Unable to start server: " << _server->errorString()); emit abortBoot("Unable to start server: " + _server->errorString()); return; @@ -124,28 +112,29 @@ void NetworkDiscovery::initAndRun(QString serverIp, bool userChoice, bool autoUp killDHCPCD(); // check if the path to the customdhcpcd file is correct - emit updateStatus("check if cdhcpcd is available"); - QFileInfo fInfo(_pathToDhcpcdExe); - if (!fInfo.exists()) { - LOG4CXX_DEBUG(ndcLogger, "could not find customdhcpcd exe. Please check the path to this file."); - emit abortBoot( - "could not find customdhcpcd exe. Please check the path to this file."); - return; - } + emit + updateStatus("check if cdhcpcd is available"); + QFileInfo fInfo(gPathToDhcpExe); + if (!fInfo.exists()) { + LOG4CXX_DEBUG( + ndcLogger, + "could not find customdhcpcd exe. Please check the path to this file."); + emit + abortBoot( + "could not find customdhcpcd exe. Please check the path to this file."); + return; + } connect(_server, SIGNAL(newConnection()), this, SLOT(handleNewConnection())); - connect(this, SIGNAL(readyForRun()), this, SLOT(slotReadyForRun())); if (args != NULL && !args->isEmpty()) { LOG4CXX_DEBUG(ndcLogger, "added additional args"); _dhcpcdArguments.append(*args); - } - emit updateStatus("start mainwork"); - mainWork(); + } emit + updateStatus("start mainwork"); + mainWork(); } - - /** * @brief the main work. Here we start with searching for usable interfaces and check the IsRunning state. * @@ -153,78 +142,20 @@ void NetworkDiscovery::initAndRun(QString serverIp, bool userChoice, bool autoUp * check every second the IsRunning state. Do this as long the counter (@see _ifUpCountdown) is greater than 0. * Default: _ifUpCountdown = 10. */ -void NetworkDiscovery::mainWork() -{ - if (_autoUp) { - emit updateStatus("search for usable interfaces (with auto Up)"); - getListOfNetworkInterfacesWithAutoUp(); - } else { - emit updateStatus("search for usable interfaces"); - getListOfNetworkInterfaces(); - } - emit updateStatus("check if interfaces are in running state"); +void NetworkDiscovery::mainWork() { + gAutoUp ? + emit updateStatus("search for usable interfaces (with auto Up)") : + emit updateStatus("search for usable interfaces"); + + getListOfNetworkInterfaces(); + + emit + updateStatus("check if interfaces are in running state"); _timer = new QTimer(this); connect(_timer, SIGNAL(timeout()), this, SLOT(checkForIsRunning())); _timer->start(1000); } - - -/** - * searches for usable interfaces and puts them into a list. - * if the interface is down, put it in the _ifDownList, try to bring it up. - * else put it in the _ifUpList. - * usable interfaces are: can Broadcast, no loopback, no point to point, name is not in the BlackList, - */ -void NetworkDiscovery::getListOfNetworkInterfacesWithAutoUp() { - QList nIList = QNetworkInterface::allInterfaces(); - _ifUpList.clear(); - _ifDownList.clear(); - if (nIList.size() > 0) { - foreach(QNetworkInterface nI, nIList) - { - LOG4CXX_DEBUG(ndcLogger, "found Interface:" << nI.humanReadableName()); - if ((nI.flags() & QNetworkInterface::CanBroadcast)) { - LOG4CXX_DEBUG(ndcLogger, "flags: can broadcast "); - } - if ((nI.flags() & QNetworkInterface::IsLoopBack)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is LoopBack "); - } - if ((nI.flags() & QNetworkInterface::IsPointToPoint)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Point to Point "); - } - if ((nI.flags() & QNetworkInterface::IsRunning)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Running "); - } - if ((nI.flags() & QNetworkInterface::IsUp)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Up "); - } - - if (((!(nI.flags() & QNetworkInterface::CanBroadcast) - || nI.flags() & QNetworkInterface::IsLoopBack) - || nI.flags() & QNetworkInterface::IsPointToPoint) - || checkBlackList(nI.humanReadableName())) { - continue; - } - if ((nI.flags() & QNetworkInterface::IsRunning)) { - _ifUpList.append(nI.humanReadableName()); - } - else if (!(nI.flags() & QNetworkInterface::IsUp)) { - _networkManager->bringInterfaceUP(nI.humanReadableName()); - LOG4CXX_DEBUG(ndcLogger, "interface is down, try to bring up: " << nI.humanReadableName() ); - _ifDownList.append(nI.humanReadableName()); - } - else if (!(nI.flags() & QNetworkInterface::IsRunning)) { - _ifDownList.append(nI.humanReadableName()); - } - } - } else { - LOG4CXX_DEBUG(ndcLogger, "no interfaces found! "); - } -} - - - /** * searches for usable interfaces which are up and running and put them into a list. * usable interfaces are: can Broadcast, no loopback, no point to point, name is not in the BlackList, @@ -235,43 +166,48 @@ void NetworkDiscovery::getListOfNetworkInterfaces() { _ifDownList.clear(); if (nIList.size() > 0) { foreach(QNetworkInterface nI, nIList) - { - LOG4CXX_DEBUG(ndcLogger, "found Interface:" << nI.humanReadableName()); - if ((nI.flags() & QNetworkInterface::CanBroadcast)) { - LOG4CXX_DEBUG(ndcLogger, "flags: can broadcast "); - } - if ((nI.flags() & QNetworkInterface::IsLoopBack)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is LoopBack "); - } - if ((nI.flags() & QNetworkInterface::IsPointToPoint)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Point to Point "); - } - if ((nI.flags() & QNetworkInterface::IsRunning)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Running "); - } - if ((nI.flags() & QNetworkInterface::IsUp)) { - LOG4CXX_DEBUG(ndcLogger, "flags: is Up "); - } - if (((!(nI.flags() & QNetworkInterface::CanBroadcast) - || nI.flags() & QNetworkInterface::IsLoopBack) - || nI.flags() & QNetworkInterface::IsPointToPoint) - || !(nI.flags() & QNetworkInterface::IsUp) - || checkBlackList(nI.humanReadableName())) { - continue; - } - if (!(nI.flags() & QNetworkInterface::IsRunning)) { - _ifDownList.append(nI.humanReadableName()); - } else { - _ifUpList.append(nI.humanReadableName()); - } + { + LOG4CXX_DEBUG(ndcLogger, "found Interface:" << nI.humanReadableName()); + if ((nI.flags() & QNetworkInterface::CanBroadcast)) { + LOG4CXX_DEBUG(ndcLogger, "flags: can broadcast "); + } + if ((nI.flags() & QNetworkInterface::IsLoopBack)) { + LOG4CXX_DEBUG(ndcLogger, "flags: is LoopBack "); + } + if ((nI.flags() & QNetworkInterface::IsPointToPoint)) { + LOG4CXX_DEBUG(ndcLogger, "flags: is Point to Point "); + } + if ((nI.flags() & QNetworkInterface::IsRunning)) { + LOG4CXX_DEBUG(ndcLogger, "flags: is Running "); + } + if ((nI.flags() & QNetworkInterface::IsUp)) { + LOG4CXX_DEBUG(ndcLogger, "flags: is Up "); + } + if (((!(nI.flags() & QNetworkInterface::CanBroadcast) + || nI.flags() & QNetworkInterface::IsLoopBack) + || nI.flags() & QNetworkInterface::IsPointToPoint) + || (gAutoUp && !(nI.flags() & QNetworkInterface::IsUp)) + || checkBlackList(nI.humanReadableName())) { + continue; } + + if ((nI.flags() & QNetworkInterface::IsRunning)) { + _ifUpList.append(nI.humanReadableName()); + } else if (gAutoUp && !(nI.flags() & QNetworkInterface::IsUp)) { + _networkManager->bringInterfaceUP(nI.humanReadableName()); + LOG4CXX_DEBUG( + ndcLogger, + "interface is down, try to bring up: " << nI.humanReadableName()); + _ifDownList.append(nI.humanReadableName()); + } else if (!(nI.flags() & QNetworkInterface::IsRunning)) { + _ifDownList.append(nI.humanReadableName()); + } + } } else { LOG4CXX_DEBUG(ndcLogger, "no interfaces found! "); } } - - /** * only called if autoUp == true. * check the IsRunning flag of each interface in the _ifDownList. @@ -280,7 +216,8 @@ void NetworkDiscovery::getListOfNetworkInterfaces() { void NetworkDiscovery::checkForIsRunning() { bool isRunning = false; foreach(QString i, _ifDownList) { - QNetworkInterface networkInterface = QNetworkInterface::interfaceFromName(i); + QNetworkInterface networkInterface = QNetworkInterface::interfaceFromName( + i); isRunning = (networkInterface.flags() & QNetworkInterface::IsRunning); if (isRunning) { _ifUpList.append(i); @@ -288,16 +225,15 @@ void NetworkDiscovery::checkForIsRunning() { } } _ifUpCountdown--; - if ((_ifUpCountdown <= 0 ) || _ifDownList.isEmpty()) { + if ((_ifUpCountdown <= 0) || _ifDownList.isEmpty()) { // shut down timer _timer->stop(); delete _timer; - emit readyForRun(); + //emit readyForRun(); + slotReadyForRun(); } } - - /** * emits the addInterface signal for each interface name in _ifUpList * and calls the runDHCPCD method. @@ -312,20 +248,20 @@ void NetworkDiscovery::slotReadyForRun() { } _numberOfProcesses = _ifUpList.size(); emit updateStatus("start dhcp client for each interface"); - runDHCPCD( _ifUpList); + runDHCPCD(_ifUpList); } else { - LOG4CXX_DEBUG(ndcLogger, "list is empty. Have not found usable interface. "); + LOG4CXX_DEBUG(ndcLogger, + "list is empty. Have not found usable interface. "); emit foreach(QString i, _ifDownList) { LOG4CXX_DEBUG(ndcLogger, "" << i << " is not in running state. (check cable)"); } - abortBoot("All interfaces are not usable. (e.g. please check if all network cables are plugged in. Read the log for more informations.)"); + abortBoot( + "All interfaces are not usable. (e.g. please check if all network cables are plugged in. Read the log for more informations.)"); return; } } - - /** * call for every interface in the list the runDHCPCD method. * @@ -333,14 +269,11 @@ void NetworkDiscovery::slotReadyForRun() { * list of interface names. */ void NetworkDiscovery::runDHCPCD(QList &interfaces) { - foreach(QString nI, interfaces) - { - runDHCPCD(nI); - } + foreach(QString nI, interfaces) { + runDHCPCD(nI); + } } - - /** * start a cdhcpcd process with the interface name as last argument. * @@ -352,18 +285,17 @@ void NetworkDiscovery::runDHCPCD(QString interface) { _dhcpcdArguments.append(interface); QProcess * p = new QProcess(this); - LOG4CXX_DEBUG(ndcLogger, "start cdhcpcd with arguments: " << _dhcpcdArguments.join(", ")); + LOG4CXX_DEBUG(ndcLogger, + "start cdhcpcd with arguments: " << _dhcpcdArguments.join(", ")); _clientProcessToIfNameMap.insert(p, interface); - p->start(_pathToDhcpcdExe, _dhcpcdArguments); + p->start(gPathToDhcpExe, _dhcpcdArguments); connect(p, SIGNAL(started()), this, SLOT(handleProcessStarted())); connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(handleProcessFinished(int, QProcess::ExitStatus))); _dhcpcdArguments.removeLast(); } - - /** * This Method is called when a process is started. * @@ -371,13 +303,11 @@ void NetworkDiscovery::runDHCPCD(QString interface) { * It prints the message: "process started for interface: ". */ void NetworkDiscovery::handleProcessStarted() { - QProcess* p = qobject_cast (QObject::sender()); + QProcess* p = qobject_cast(QObject::sender()); QString ifName = _clientProcessToIfNameMap.value(p, "ifName"); LOG4CXX_DEBUG(ndcLogger, "process started for interface: " << ifName); } - - /** * This Method is called when a process is finished. * @@ -408,18 +338,21 @@ void NetworkDiscovery::handleProcessStarted() { void NetworkDiscovery::handleProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { - QProcess* p = qobject_cast (QObject::sender()); + QProcess* p = qobject_cast(QObject::sender()); QString ifName = _clientProcessToIfNameMap.value(p, "ifName"); _numberOfProcesses = _numberOfProcesses - 1; if (!_blocked) { //_blocked becomes true, if _userChoice is false and we already found a usable interface if (ifName.compare("ifName") == 0) { LOG4CXX_DEBUG(ndcLogger, "haven't found process!"); } else { - LOG4CXX_DEBUG(ndcLogger, "process for interface " << ifName << " finished " << " exit code: " << exitCode << " exit status " << exitStatus); + LOG4CXX_DEBUG( + ndcLogger, + "process for interface " << ifName << " finished " << " exit code: " << exitCode << " exit status " << exitStatus); if (exitCode > 0) { - LOG4CXX_DEBUG(ndcLogger, "process exited unexpected: " << p->errorString()); - emit updateIfStatus(ifName, "process exited unexpected" - + p->errorString()); + LOG4CXX_DEBUG(ndcLogger, + "process exited unexpected: " << p->errorString()); + emit updateIfStatus(ifName, + "process exited unexpected" + p->errorString()); } else { LOG4CXX_DEBUG(ndcLogger, "process normal exit "); emit @@ -452,8 +385,6 @@ void NetworkDiscovery::handleProcessFinished(int exitCode, } } - - /** * checks the connectivity. tries to open a TCP connection to the * server (see _serverIp). For this it adjusts the routing table. @@ -467,50 +398,44 @@ void NetworkDiscovery::handleProcessFinished(int exitCode, * @return * true: connection is possible * false: connection not possible - */ -bool NetworkDiscovery::checkConnectivity(QString ifName) { + */bool NetworkDiscovery::checkConnectivity(QString ifName) { int mss = 0; // get gateway address QString pathToGatewayFile(DEFAULT_INTERFACE_CONF_LOCATION); pathToGatewayFile += ifName; - interfaceconfiguration* ifConf; + InterfaceConfiguration* ifConf; if (!_ifcMap.contains(ifName)) { - ifConf = new interfaceconfiguration(); + ifConf = new InterfaceConfiguration(); _ifcMap.insert(ifName, ifConf); - } - else { + } else { ifConf = _ifcMap.value(ifName); } ifConf->readConfigOutOfFile(pathToGatewayFile); // replace default route LOG4CXX_DEBUG(ndcLogger, "replace default route"); - _networkManager->replaceDefaultRoute(ifName, - ifConf->getGateway(), mss, AF_INET); + _networkManager->replaceDefaultRoute(ifName, ifConf->getGateway(), mss, + AF_INET); - if (checkConnectivityViaTcp(_serverIp)) { - LOG4CXX_DEBUG(ndcLogger, "passed connectivity check! for interface " << ifName); + if (checkConnectivityViaTcp(gServerIp)) { + LOG4CXX_DEBUG(ndcLogger, + "passed connectivity check! for interface " << ifName); emit updateIfStatus(ifName, "connection possible"); return true; } else { - LOG4CXX_DEBUG(ndcLogger, "failed connectivity check! for interface " << ifName); + LOG4CXX_DEBUG(ndcLogger, + "failed connectivity check! for interface " << ifName); emit updateIfStatus(ifName, "connection not possible"); return false; } } - - -/**/ -bool NetworkDiscovery::checkConnectivityViaTcp() { - return checkConnectivityViaTcp(_serverIp); +/**/bool NetworkDiscovery::checkConnectivityViaTcp() { + return checkConnectivityViaTcp(gServerIp); } - - - /** * try to open a tcp connection to the server * @@ -520,12 +445,10 @@ bool NetworkDiscovery::checkConnectivityViaTcp() { * @return * true: connection is possible * false: connection not possible - */ -bool NetworkDiscovery::checkConnectivityViaTcp(QString server) { + */bool NetworkDiscovery::checkConnectivityViaTcp(QString server) { // check connectivity via tcp connection LOG4CXX_DEBUG(ndcLogger, "check connectivity to server: " << server); // do host lookup - //QHostInfo hostInfo = QHostInfo::fromName(server); QTcpSocket *tcpSocket = new QTcpSocket(this); //LOG4CXX_DEBUG(ndcLogger, "hostInfo first address: " << hostInfo.addresses().first().toString()); //hostInfo.addresses().first() tcpSocket->connectToHost(server, 80); @@ -539,8 +462,6 @@ bool NetworkDiscovery::checkConnectivityViaTcp(QString server) { delete tcpSocket; } - - /** * same function as handleNewInput() but with a client as parameter. * @@ -553,7 +474,8 @@ void NetworkDiscovery::handleNewInput(QLocalSocket * client) { QString data(client->readLine()); data = data.trimmed(); - if (!data.isEmpty()) LOG4CXX_DEBUG(ndcLogger, data); + if (!data.isEmpty()) + LOG4CXX_DEBUG(ndcLogger, data); QStringList lines = data.split("\n"); for (int i = 0; i < lines.length(); i++) { @@ -562,15 +484,13 @@ void NetworkDiscovery::handleNewInput(QLocalSocket * client) { } } - - /** * This method is connected to the readyRead Signal of the QLocalSocket * client. * send an ACK to the client with every received message. */ void NetworkDiscovery::handleNewInput() { - QLocalSocket* socket = qobject_cast (QObject::sender()); + QLocalSocket* socket = qobject_cast(QObject::sender()); QLocalSocket * client = _clients.value(socket); QString data(client->read(DHCP_MESSAGE_SIZE)); @@ -581,8 +501,6 @@ void NetworkDiscovery::handleNewInput() { } } - - /** * This Method processes the send messages. * @@ -603,118 +521,114 @@ void NetworkDiscovery::handleNewInput() { * @param data * the message. (format ;;; ) */ -void NetworkDiscovery::handleNewInputLine(QLocalSocket * client, QString logMsg) { - - if (logMsg.trimmed().size() < 1) return; - - QString interface = logMsg.section(";", 0, 0); - QString s_state = logMsg.section(";", 1, 1); - QString s_subState = logMsg.section(";", 2, 2); - QString msg = logMsg.section(";", 3, 3); - int st = s_state.trimmed().toInt(); - int sst = s_subState.trimmed().toInt(); - //LOG4CXX_DEBUG(ndcLogger, logMsg); - - if (_ifNameToClient.size() < _numberOfProcesses - && !_ifNameToClient.contains(interface)) - { - _ifNameToClient.insert(interface, client); - } - - - // st states - - // #define LOG_EMERG 0 /* system is unusable */ - // #define LOG_ALERT 1 /* action must be taken immediately */ - // #define LOG_CRIT 2 /* critical conditions */ - // #define LOG_ERR 3 /* error conditions */ - // #define LOG_WARNING 4 /* warning conditions */ - // #define LOG_NOTICE 5 /* normal but significant condition */ - // #define LOG_INFO 6 /* informational */ - // #define LOG_DEBUG 7 /* debug-level messages */ - - QString out; - QTextStream outStream(&out); - - switch (sst) - { - case DHCP_DISCOVER: - emit changeProgressBarValue(interface, 10); - outStream << interface << " send discover"; - break; - case DHCP_OFFER: - emit changeProgressBarValue(interface, 20); - outStream << interface << " got offer"; - break; - case DHCP_REQUEST: - emit changeProgressBarValue(interface, 30); - outStream << interface << " send request"; - break; - case DHCP_ACK: - emit changeProgressBarValue(interface, 40); - outStream << interface << " ack"; - break; - case DHCP_NAK: - emit changeProgressBarValue(interface, 40); - outStream << interface << " nak"; - break; - case DHCP_RELEASE: - outStream << interface << " release"; - break; - case DHCP_INFORM: - break; - case DHCPCD_ARP_TEST: - emit changeProgressBarValue(interface, 50); - outStream << interface << " do arp test"; - break; - case DHCP_DECLINE: - emit changeProgressBarValue(interface, 60); - break; - case DHCPCD_CONFIGURE: - emit changeProgressBarValue(interface, 70); - outStream << interface << " do configure interface"; - break; - case DHCPCD_WRITE: - emit changeProgressBarValue(interface, 80); - outStream << interface << " write conf file"; - break; - case DHCPCD_EXIT: - emit changeProgressBarValue(interface, 100); - outStream << interface << " exiting"; - break; - case DHCPCD_LOG: - outStream << "received dhcpcd log: " << msg; - break; - default: - outStream << "received unknown substatus: " << msg; - break; - } - - switch (st) - { - - case LOG_INFO: - LOG4CXX_INFO(ndcLogger, out); - break; - case LOG_NOTICE: - LOG4CXX_WARN(ndcLogger, out); - break; - case LOG_WARNING: - LOG4CXX_WARN(ndcLogger, out); - break; - case LOG_DEBUG: - LOG4CXX_DEBUG(ndcLogger, out); - break; - case LOG_ERR: - LOG4CXX_ERROR(ndcLogger, out); - break; - default: - LOG4CXX_DEBUG(ndcLogger, out); - break; - } -} +void NetworkDiscovery::handleNewInputLine(QLocalSocket * client, + QString logMsg) { + if (logMsg.trimmed().size() < 1) + return; + QString interface = logMsg.section(";", 0, 0); + QString s_state = logMsg.section(";", 1, 1); + QString s_subState = logMsg.section(";", 2, 2); + QString msg = logMsg.section(";", 3, 3); + int st = s_state.trimmed().toInt(); + int sst = s_subState.trimmed().toInt(); + //LOG4CXX_DEBUG(ndcLogger, logMsg); + + if (_ifNameToClient.size() < _numberOfProcesses + && !_ifNameToClient.contains(interface)) { + _ifNameToClient.insert(interface, client); + } + + // st states + + // #define LOG_EMERG 0 /* system is unusable */ + // #define LOG_ALERT 1 /* action must be taken immediately */ + // #define LOG_CRIT 2 /* critical conditions */ + // #define LOG_ERR 3 /* error conditions */ + // #define LOG_WARNING 4 /* warning conditions */ + // #define LOG_NOTICE 5 /* normal but significant condition */ + // #define LOG_INFO 6 /* informational */ + // #define LOG_DEBUG 7 /* debug-level messages */ + + QString out; + QTextStream outStream(&out); + + switch (sst) { + case DHCP_DISCOVER: + emit changeProgressBarValue(interface, 10); + outStream << interface << " send discover"; + break; + case DHCP_OFFER: + emit changeProgressBarValue(interface, 20); + outStream << interface << " got offer"; + break; + case DHCP_REQUEST: + emit changeProgressBarValue(interface, 30); + outStream << interface << " send request"; + break; + case DHCP_ACK: + emit changeProgressBarValue(interface, 40); + outStream << interface << " ack"; + break; + case DHCP_NAK: + emit changeProgressBarValue(interface, 40); + outStream << interface << " nak"; + break; + case DHCP_RELEASE: + outStream << interface << " release"; + break; + case DHCP_INFORM: + break; + case DHCPCD_ARP_TEST: + emit changeProgressBarValue(interface, 50); + outStream << interface << " do arp test"; + break; + case DHCP_DECLINE: + emit changeProgressBarValue(interface, 60); + break; + case DHCPCD_CONFIGURE: + emit changeProgressBarValue(interface, 70); + outStream << interface << " do configure interface"; + break; + case DHCPCD_WRITE: + emit changeProgressBarValue(interface, 80); + outStream << interface << " write conf file"; + break; + case DHCPCD_EXIT: + emit changeProgressBarValue(interface, 100); + outStream << interface << " exiting"; + break; + case DHCPCD_LOG: + outStream << "received dhcpcd log: " << msg; + break; + default: + outStream << "received unknown substatus: " << msg; + break; + } + + switch (st) { + + case LOG_INFO: + LOG4CXX_INFO(ndcLogger, out); + break; + case LOG_NOTICE: + LOG4CXX_WARN(ndcLogger, out); + break; + case LOG_WARNING: + LOG4CXX_WARN(ndcLogger, out); + break; + case LOG_DEBUG: + LOG4CXX_DEBUG(ndcLogger, out); + break; + case LOG_ERR: + LOG4CXX_ERROR(ndcLogger, out); + break; + default: + LOG4CXX_DEBUG(ndcLogger, out); + break; + } +} /** * replace the default route. sets af automatically to AF_INET @@ -728,12 +642,11 @@ void NetworkDiscovery::handleNewInputLine(QLocalSocket * client, QString logMsg) * @param mss * mss value (i think this is the metric. in most cases this value is 0) */ -int NetworkDiscovery::ip4_replaceDefaultRoute(QString ifName, QString gateway, int mss) { +int NetworkDiscovery::ip4_replaceDefaultRoute(QString ifName, QString gateway, + int mss) { return _networkManager->replaceDefaultRoute(ifName, gateway, mss, AF_INET); } - - /** * replace the dhcp configuration with the manual config, entered by the user. * if we can not establish a connection with the entered values, reset to the old @@ -755,29 +668,28 @@ int NetworkDiscovery::ip4_setManualConfiguration(QVariantMap result) { LOG4CXX_DEBUG(ndcLogger, "set man conf. and check connectivity"); - if (!checkConnectivityViaTcp(_serverIp)) { + if (!checkConnectivityViaTcp(gServerIp)) { LOG4CXX_DEBUG(ndcLogger, "no connectivity. reset conf."); - interfaceconfiguration * ifc = _ifcMap.value( - result["ifname"].toString(), NULL); + InterfaceConfiguration * ifc = _ifcMap.value(result["ifname"].toString(), + NULL); if (ifc != NULL) { dns.clear(); dns = ifc->getDnsservers().trimmed().split(" "); _networkManager->ip4_setManualConfiguration( result["ifname"].toString(), ifc->getIpAddress(), - ifc->getNetmask(), ifc->getBroadcast(), ifc->getGateway(), - 0, AF_INET, "/etc/", dns); + ifc->getNetmask(), ifc->getBroadcast(), ifc->getGateway(), 0, + AF_INET, "/etc/", dns); } return 0; - } - LOG4CXX_DEBUG(ndcLogger, "emit signal continueBootWithoutCheck(" << result["ifname"].toString() << ")"); + }LOG4CXX_DEBUG( + ndcLogger, + "emit signal continueBootWithoutCheck(" << result["ifname"].toString() << ")"); emit continueBootWithoutCheck(result["ifname"].toString()); return 0; } - - /** * returns the gateway address, written into the dhcp config file. * @@ -788,20 +700,16 @@ int NetworkDiscovery::ip4_setManualConfiguration(QVariantMap result) { * gateway address as string. or empty string if no interface config was found. */ QString NetworkDiscovery::getGatewayForInterface(QString ifName) { - interfaceconfiguration * ifConf = _ifcMap.value(ifName, NULL); - if (ifConf != NULL) - { + InterfaceConfiguration * ifConf = _ifcMap.value(ifName, NULL); + if (ifConf != NULL) { return ifConf->getGateway(); - } - else { + } else { LOG4CXX_DEBUG(ndcLogger, "could not find interface configuration"); return ""; } } - - /** * reads the log file. * @@ -809,28 +717,25 @@ QString NetworkDiscovery::getGatewayForInterface(QString ifName) { */ QString NetworkDiscovery::readLogFile() { // path to log file is in _pathToLogFile. initialized in initAndRun(). - QString retval("the log file\n"); - QFile logFile(_pathToLogFile); + QString retval("the log file:\n"); + QFile logFile(logFilePath); if (logFile.exists()) { if (logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!logFile.atEnd()) { retval.append(logFile.readLine()); } - } - else { + } else { LOG4CXX_DEBUG(ndcLogger, "could not open log file"); retval = "could not open log file"; } - } - else { - LOG4CXX_DEBUG(ndcLogger, "log file does not exist at: " << _pathToLogFile); - retval = " log file does not exist at: " + _pathToLogFile; + } else { + LOG4CXX_DEBUG(ndcLogger, "log file does not exist at: " << logFilePath); + retval = " log file does not exist at: " + logFilePath; } return retval; } - /**/ void NetworkDiscovery::killDHCPCD() { LOG4CXX_DEBUG(ndcLogger, "kill cdhcpcd processes"); @@ -843,8 +748,6 @@ void NetworkDiscovery::killDHCPCD() { delete p; } - - /**/ void NetworkDiscovery::prepareTryAgain() { // kill all cdhcpcd processes @@ -863,45 +766,26 @@ void NetworkDiscovery::prepareTryAgain() { { delete p; } - foreach(interfaceconfiguration* i, _ifcMap.values()) + foreach(InterfaceConfiguration* i, _ifcMap.values()) { delete i; } } - - /* *TODO: to be bug fixed *TODO: do it with kill and not QProcess("killall cdhcpcd") */ void NetworkDiscovery::tryAgain() { prepareTryAgain(); - initAndRun(_serverIp, _userChoice, _autoUp, _pathToLogFile, _serverPath, DEFAULT_PATHTODHCPCDEXE); + initAndRun(_userChoice); } - - /**/ -QVariantMap NetworkDiscovery::getInterfaceConfig(QString ifName) { - QVariantMap jsonObj; - QList dns; - interfaceconfiguration * ifc = _ifcMap.value(ifName, NULL); - if (ifc != NULL) { - jsonObj.insert("ipaddr",ifc->getIpAddress()); - jsonObj.insert("netmask",ifc->getNetmask()); - jsonObj.insert("broadcast",ifc->getBroadcast()); - jsonObj.insert("gateway",ifc->getGateway()); - - dns.clear(); - dns = ifc->getDnsservers().trimmed().split(" "); - jsonObj.insert("dns",dns.first()); - } - return jsonObj; +InterfaceConfiguration* NetworkDiscovery::getInterfaceConfig(QString ifName) { + return _ifcMap.value(ifName, NULL); } - - /** * connected to the new client arrived signal. * connects the client readyRead signal with the handleNewInput slot. @@ -917,13 +801,11 @@ void NetworkDiscovery::handleNewConnection() { connect(_client, SIGNAL(readyRead()), this, SLOT(handleNewInput())); } - - /** * called when a client disconnects. */ void NetworkDiscovery::handleClientDisconnect() { - QLocalSocket* socket = qobject_cast (QObject::sender()); + QLocalSocket* socket = qobject_cast(QObject::sender()); QLocalSocket * client = _clients.value(socket); @@ -932,8 +814,6 @@ void NetworkDiscovery::handleClientDisconnect() { client->deleteLater(); } - - /** * This Method implements a blacklist. * @@ -951,8 +831,7 @@ void NetworkDiscovery::handleClientDisconnect() { * returns false: else * * @see NetworkDiscovery::getListOfNetworkInterfaces() - */ -bool NetworkDiscovery::checkBlackList(QString i) { + */bool NetworkDiscovery::checkBlackList(QString i) { if (i.startsWith("v", Qt::CaseInsensitive)) { return true; } else if (i.startsWith("d", Qt::CaseInsensitive)) { @@ -962,15 +841,11 @@ bool NetworkDiscovery::checkBlackList(QString i) { } } - - /**/ QString NetworkDiscovery::GetErrorStr() { return _errorStr; } - - ////////////////////////////////////////////////////////////////////////////////////// /** @@ -980,8 +855,7 @@ QString NetworkDiscovery::GetErrorStr() { * * @param interface * name of the interface - */ -bool NetworkDiscovery::checkCarrierState(QString interface) { + */bool NetworkDiscovery::checkCarrierState(QString interface) { LOG4CXX_DEBUG(ndcLogger, "check carrier state for interface " << interface); QByteArray ba = interface.toAscii(); @@ -1000,10 +874,12 @@ bool NetworkDiscovery::checkCarrierState(QString interface) { int v = value.toInt(pok); if (*pok) { if (v == 1) { - LOG4CXX_DEBUG(ndcLogger, "carrier is 1. Cable is plugged. return true"); + LOG4CXX_DEBUG(ndcLogger, + "carrier is 1. Cable is plugged. return true"); return true; } else { - LOG4CXX_DEBUG(ndcLogger, "carrier is 0. Cable is unplugged. return false"); + LOG4CXX_DEBUG( ndcLogger, + "carrier is 0. Cable is unplugged. return false"); return false; } } else { @@ -1018,3 +894,7 @@ bool NetworkDiscovery::checkCarrierState(QString interface) { return true; } + +QList NetworkDiscovery::getIfUpList() { + return _ifUpList; +} diff --git a/src/fbgui/networkdiscovery.h b/src/fbgui/networkdiscovery.h index d63ad0b..4f057e0 100644 --- a/src/fbgui/networkdiscovery.h +++ b/src/fbgui/networkdiscovery.h @@ -32,13 +32,9 @@ #include "dhcp.h" - +#include "globals.h" #include "../common/fbgui.h" - - -#define DEFAULT_PATHTODHCPCDEXE "/bin/cdhcpcd" - class NetworkDiscovery: public QObject { Q_OBJECT @@ -47,12 +43,7 @@ public: NetworkDiscovery(QObject *parent = 0); ~NetworkDiscovery(); - void initAndRun(QString serverIp, bool userChoice, - bool autoUp, - QString pathToLogFile, - QString serverPath = DEFAULT_QTSOCKETADDRESS, - QString pathToExe = DEFAULT_PATHTODHCPCDEXE, - QStringList* args = NULL); + void initAndRun(bool userChoice, QStringList* args = NULL); int ip4_replaceDefaultRoute(QString ifName, QString gateway, int mss); QString getGatewayForInterface(QString ifName); @@ -62,8 +53,9 @@ public: void prepareTryAgain(); bool checkConnectivity(QString ifName); bool checkConnectivityViaTcp(); - QVariantMap getInterfaceConfig(QString ifName); + InterfaceConfiguration* getInterfaceConfig(QString ifName); QString GetErrorStr(); + QList getIfUpList(); public slots: void handleNewConnection(); @@ -93,29 +85,23 @@ signals: void readyForRun(); private: - QString _tag; QLocalServer *_server; QMap _clients; QLocalSocket *_client; QMap _ifNameToClient; QMap _clientProcessToIfNameMap; - QString _serverPath; - QString _pathToDhcpcdExe; QStringList _dhcpcdArguments; int _numberOfProcesses; NetworkManager* _networkManager; bool _userChoice; bool _blocked; - bool _autoUp; - QString _serverIp; - QString _pathToLogFile; QList _ifUpList; QList _ifDownList; int _ifUpCountdown; QTimer*_timer; QList _pidsList; QString _errorStr; - QMap _ifcMap; + QMap _ifcMap; void mainWork(); void killDHCPCD(); @@ -132,8 +118,6 @@ private: void getListOfNetworkInterfaces(); void getListOfNetworkInterfacesWithAutoUp(); - - }; #endif // NetworkDiscovery_H diff --git a/src/fbgui/sysinfo.cpp b/src/fbgui/sysinfo.cpp index 807413b..fb0e53f 100644 --- a/src/fbgui/sysinfo.cpp +++ b/src/fbgui/sysinfo.cpp @@ -54,11 +54,11 @@ const QString SysInfo::getInfo(const QString& infoName) { } const QString SysInfo::getMACAddress() { // Returns MAC address of eth0 for now - LOG4CXX_DEBUG(siLogger, "Requesting MAC of: " << interfaceName << " ..."); - QNetworkInterface qni = QNetworkInterface::interfaceFromName(interfaceName); + LOG4CXX_DEBUG(siLogger, "Requesting MAC of: " << gInterfaceName << " ..."); + QNetworkInterface qni = QNetworkInterface::interfaceFromName(gInterfaceName); if (!qni.isValid()) { - LOG4CXX_DEBUG(siLogger, "No valid interface with name: " << interfaceName); - return "no_interface"; + LOG4CXX_DEBUG(siLogger, "No valid interface with name: " << gInterfaceName); + return ""; } return qni.hardwareAddress(); } diff --git a/testApp.sh b/testApp.sh index 4fcfe25..ad505d8 100755 --- a/testApp.sh +++ b/testApp.sh @@ -13,7 +13,8 @@ # Note: all path are expected to be absolute. # Adapt these to your own system. QT_VERSION=Qt-4.8.0 -PATH_TO_FBGUI_BUILD=~/fbgui/build +#PATH_TO_FBGUI_BUILD=~/fbgui/build +PATH_TO_FBGUI_BUILD=~/workspace/fbgui # check if network discovery is activated and if running as root for ARG in $* -- cgit v1.2.3-55-g7522