diff options
author | sangwan.kwon <sangwan.kwon@samsung.com> | 2016-05-30 14:27:13 +0900 |
---|---|---|
committer | sangwan.kwon <sangwan.kwon@samsung.com> | 2016-05-30 14:35:25 +0900 |
commit | b8ffd7662428b4baff92a0c8271e84c2b55ce47b (patch) | |
tree | cdeecf4ba84a2fb7c852fa6c538a304f2a458196 | |
parent | 30177b747ab42a7cedc5228803e057d05583b1a6 (diff) | |
download | cert-checker-b8ffd7662428b4baff92a0c8271e84c2b55ce47b.tar.gz cert-checker-b8ffd7662428b4baff92a0c8271e84c2b55ce47b.tar.bz2 cert-checker-b8ffd7662428b4baff92a0c8271e84c2b55ce47b.zip |
Apply tizen coding rule
* It depends on cpp rule checker(version 160520)
Change-Id: Ica308e1296be4f3567725fdb004f3bae8a456a0c
70 files changed, 5093 insertions, 5333 deletions
diff --git a/src/client/ocsp-client.cpp b/src/client/ocsp-client.cpp index 63e6d26..e40f890 100644 --- a/src/client/ocsp-client.cpp +++ b/src/client/ocsp-client.cpp @@ -41,9 +41,9 @@ CCerr OcspClient::request() { LogDebug("Request to oscp service."); auto ret = m_dispatcher->methodCall<CommandId>(CommandId::CC_OCSP_SYN); - LogDebug("Response ret : " << static_cast<int>(ret)); - if(ret == CommandId::CC_OCSP_ACK) + + if (ret == CommandId::CC_OCSP_ACK) return E_CC_NONE; else return E_CC_INTERNAL; diff --git a/src/client/ocsp.cpp b/src/client/ocsp.cpp index 0302687..eb6744a 100644 --- a/src/client/ocsp.cpp +++ b/src/client/ocsp.cpp @@ -26,7 +26,8 @@ #include "client/error.h" __attribute__((visibility("default"))) -int cchecker_ocsp_request() { +int cchecker_ocsp_request() +{ CCHECKER::OcspClient oc; return oc.request() == CCHECKER::E_CC_NONE ? 0 : -1; }; diff --git a/src/common/binary-queue.cpp b/src/common/binary-queue.cpp index 776f65e..34cc9f9 100644 --- a/src/common/binary-queue.cpp +++ b/src/common/binary-queue.cpp @@ -39,9 +39,7 @@ BinaryQueue::~BinaryQueue() RawBuffer BinaryQueue::pop() { RawBuffer buf(m_size); - read(m_size, buf.data()); - return buf; } @@ -78,7 +76,6 @@ void BinaryQueue::read(size_t size, void *bytes) size_t count = std::min(size, m_buckets.front()->left); cur = m_buckets.front()->extractTo(cur, count); - size -= count; m_size -= count; @@ -107,10 +104,8 @@ void *BinaryQueue::Bucket::extractTo(void *dest, size_t size) throw std::logic_error("logic error. invalid input to Bucket::extractTo."); memcpy(dest, cur, size); - cur += size; left -= size; - return static_cast<unsigned char *>(dest) + size; } diff --git a/src/common/dispatcher.h b/src/common/dispatcher.h index def73ed..9e29580 100644 --- a/src/common/dispatcher.h +++ b/src/common/dispatcher.h @@ -57,13 +57,10 @@ Type Dispatcher::methodCall(Args &&...args) connect(); m_connection->send(BinaryQueue::Serialize(std::forward<Args>(args)...).pop()); - BinaryQueue q; q.push(m_connection->receive()); - Type response; q.Deserialize(response); - return response; } diff --git a/src/common/eventfd.cpp b/src/common/eventfd.cpp index 1828b1f..a3dba42 100644 --- a/src/common/eventfd.cpp +++ b/src/common/eventfd.cpp @@ -33,6 +33,7 @@ namespace CCHECKER { EventFD::EventFD(unsigned int initval, int flags) { fd = ::eventfd(initval, flags); + if (fd == -1) { throw std::logic_error("EventFd from constructor is failed!!"); } @@ -48,6 +49,7 @@ EventFD::~EventFD() void EventFD::send() { const std::uint64_t val = 1; + if (::write(fd, &val, sizeof(val)) == -1) { throw std::logic_error("EventFd send to fd is failed!!"); } @@ -56,6 +58,7 @@ void EventFD::send() void EventFD::receive() { std::uint64_t val; + if (::read(fd, &val, sizeof(val)) == -1) { throw std::logic_error("EventFd read to fd is failed!!"); } diff --git a/src/common/eventfd.h b/src/common/eventfd.h index f10945f..64681ab 100644 --- a/src/common/eventfd.h +++ b/src/common/eventfd.h @@ -31,8 +31,8 @@ public: EventFD(unsigned int initval = 0, int flags = EFD_SEMAPHORE | EFD_CLOEXEC); ~EventFD(); - EventFD(const EventFD&) = delete; - EventFD& operator=(const EventFD&) = delete; + EventFD(const EventFD &) = delete; + EventFD &operator=(const EventFD &) = delete; void send(); void receive(); diff --git a/src/common/log.cpp b/src/common/log.cpp index c5528a2..9d83458 100644 --- a/src/common/log.cpp +++ b/src/common/log.cpp @@ -24,27 +24,27 @@ #include <systemd/sd-journal.h> void JournalLog(int logLevel, - const char *message, - const char *fileName, - int line, - const char *function) + const char *message, + const char *fileName, + int line, + const char *function) { - try { - sd_journal_send("PRIORITY=%d", logLevel, - "CODE_FILE=%s", fileName, - "CODE_FUNC=%s", function, - "CODE_LINE=%d", line, - // add file, line & function info to log message - "MESSAGE=[%s:%d] %s(): %s", fileName, line, function, message, - NULL); - } catch (const std::out_of_range&) { - sd_journal_send( - "PRIORITY=%d", LOG_ERR, - "CODE_FILE=%s", fileName, - "CODE_FUNC=%s", function, - "CODE_LINE=%d", line, - // add file, line & function info to log message - "MESSAGE=[%s:%d] %s(): Unsupported log level %d", fileName, line, function, logLevel, - NULL); - } + try { + sd_journal_send("PRIORITY=%d", logLevel, + "CODE_FILE=%s", fileName, + "CODE_FUNC=%s", function, + "CODE_LINE=%d", line, + // add file, line & function info to log message + "MESSAGE=[%s:%d] %s(): %s", fileName, line, function, message, + NULL); + } catch (const std::out_of_range &) { + sd_journal_send( + "PRIORITY=%d", LOG_ERR, + "CODE_FILE=%s", fileName, + "CODE_FUNC=%s", function, + "CODE_LINE=%d", line, + // add file, line & function info to log message + "MESSAGE=[%s:%d] %s(): Unsupported log level %d", fileName, line, function, logLevel, + NULL); + } } diff --git a/src/common/log.h b/src/common/log.h index 99d494b..b0c802d 100644 --- a/src/common/log.h +++ b/src/common/log.h @@ -26,57 +26,56 @@ #define CERT_CHECKER_LOG_H void JournalLog(int logLevel, const char *message, const char *fileName, - int line, const char *function); + int line, const char *function); /* * Replacement low overhead null logging class */ -class NullStream -{ - public: - NullStream() {} +class NullStream { +public: + NullStream() {} - template <typename T> - NullStream& operator<<(const T&) - { - return *this; - } + template <typename T> + NullStream &operator<<(const T &) + { + return *this; + } }; /* avoid warnings about unused variables */ #define DPL_MACRO_DUMMY_LOGGING(message, level) \ - do { \ - NullStream ns; \ - ns << message; \ - } while (0) + do { \ + NullStream ns; \ + ns << message; \ + } while (0) #define CERT_CHECKER_LOG(message, level) \ -do \ -{ \ - std::ostringstream platformLog; \ - platformLog << message; \ - JournalLog(level, \ - platformLog.str().c_str(), \ - __FILE__, \ - __LINE__, \ - __FUNCTION__); \ -} while (0) + do \ + { \ + std::ostringstream platformLog; \ + platformLog << message; \ + JournalLog(level, \ + platformLog.str().c_str(), \ + __FILE__, \ + __LINE__, \ + __FUNCTION__); \ + } while (0) /* always logged. */ #define LogError(message) \ - CERT_CHECKER_LOG(message, LOG_ERR) + CERT_CHECKER_LOG(message, LOG_ERR) #define LogInfo(message) \ - CERT_CHECKER_LOG(message, LOG_INFO) + CERT_CHECKER_LOG(message, LOG_INFO) #define LogWarning(message) \ - CERT_CHECKER_LOG(message, LOG_WARNING) + CERT_CHECKER_LOG(message, LOG_WARNING) /* only debug logged. */ #ifdef BUILD_TYPE_DEBUG - #define LogDebug(message) \ - CERT_CHECKER_LOG(message, LOG_DEBUG) +#define LogDebug(message) \ + CERT_CHECKER_LOG(message, LOG_DEBUG) #else - #define LogDebug(message) \ - DPL_MACRO_DUMMY_LOGGING(message, LOG_DEBUG) +#define LogDebug(message) \ + DPL_MACRO_DUMMY_LOGGING(message, LOG_DEBUG) #endif // BUILD_TYPE_DEBUG #endif //CERT_CHECKER_LOG_H diff --git a/src/common/mainloop.cpp b/src/common/mainloop.cpp index 8ce7326..0c0d19f 100644 --- a/src/common/mainloop.cpp +++ b/src/common/mainloop.cpp @@ -47,7 +47,7 @@ Mainloop::~Mainloop() { if (!m_stopped && !m_isTimedOut && !m_callbacks.empty()) throw std::logic_error("mainloop registered callbacks should be empty " - "except timed out case"); + "except timed out case"); ::close(m_pollfd); } @@ -64,7 +64,6 @@ void Mainloop::prepare() wakeupSignal.receive(); removeEventSource(wakeupSignal.getFd()); }; - addEventSource(wakeupSignal.getFd(), EPOLLIN, std::move(wakeupMainloop)); } @@ -87,9 +86,7 @@ void Mainloop::addEventSource(int fd, uint32_t event, Callback &&callback) throw std::logic_error("event source already added!"); LogDebug("Add event[" << event << "] source on fd[" << fd << "]"); - epoll_event e; - e.events = event; e.data.fd = fd; @@ -127,7 +124,6 @@ void Mainloop::dispatch(int timeout) { int nfds = -1; epoll_event event[MAX_EPOLL_EVENTS]; - LogDebug("Mainloop dispatched with timeout: " << timeout); do { @@ -158,7 +154,6 @@ void Mainloop::dispatch(int timeout) } LogDebug("event[" << event[i].events << "] polled on fd[" << fd << "]"); - m_callbacks[fd](event[i].events); } } diff --git a/src/common/service.cpp b/src/common/service.cpp index 0c14dc2..3547efa 100644 --- a/src/common/service.cpp +++ b/src/common/service.cpp @@ -32,7 +32,6 @@ namespace CCHECKER { Service::Service(const std::string &address) : m_address(address) { LogDebug("Service constructed with address[" << address << "]"); - m_timeout = -1; setNewConnectionCallback(nullptr); setCloseConnectionCallback(nullptr); @@ -45,12 +44,9 @@ Service::~Service() void Service::start() { LogInfo("Service start!"); - Socket socket(m_address); - LogDebug("Get systemd socket[" << socket.getFd() - << "] with address[" << m_address << "]"); - + << "] with address[" << m_address << "]"); m_loop.addEventSource(socket.getFd(), EPOLLIN | EPOLLHUP | EPOLLRDHUP, [&](uint32_t event) { if (event != EPOLLIN) @@ -58,7 +54,6 @@ void Service::start() m_onNewConnection(std::make_shared<Connection>(socket.accept())); }); - m_loop.run(m_timeout); } @@ -76,17 +71,14 @@ void Service::setNewConnectionCallback(const ConnCallback &/*callback*/) throw std::logic_error("onNewConnection called but ConnShPtr is nullptr."); int fd = connection->getFd(); - LogInfo("welcome! accepted client socket fd[" << fd << "]"); - /* // TODO: disable temporarily if (callback) callback(connection); */ - m_loop.addEventSource(fd, EPOLLIN | EPOLLHUP | EPOLLRDHUP, - [&, fd](uint32_t event) { + [ &, fd](uint32_t event) { LogDebug("read event comes in to fd[" << fd << "]"); if (m_connectionRegistry.count(fd) == 0) @@ -101,10 +93,8 @@ void Service::setNewConnectionCallback(const ConnCallback &/*callback*/) } LogDebug("Start message process on fd[" << fd << "]"); - onMessageProcess(conn); }); - m_connectionRegistry[fd] = connection; }; } @@ -122,10 +112,8 @@ void Service::setCloseConnectionCallback(const ConnCallback &/*callback*/) throw std::logic_error("no connection in registry to remove."); LogInfo("good-bye! close socket fd[" << fd << "]"); - m_loop.removeEventSource(fd); m_connectionRegistry.erase(fd); /* scoped-lock needed? */ - /* // TODO: disable temporarily if (callback) diff --git a/src/common/socket.cpp b/src/common/socket.cpp index 05ed75f..a30d605 100644 --- a/src/common/socket.cpp +++ b/src/common/socket.cpp @@ -85,7 +85,6 @@ Socket &Socket::operator=(Socket &&other) m_fd = other.m_fd; other.m_fd = 0; - return *this; } @@ -108,7 +107,6 @@ Socket Socket::accept() const "socket accept failed!"); LogInfo("Accept client success with fd: " << fd); - return Socket(fd); } @@ -126,7 +124,6 @@ Socket Socket::connect(const std::string &path) sockaddr_un addr; addr.sun_family = AF_UNIX; - strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path)); if (::connect(fd, reinterpret_cast<sockaddr *>(&addr), @@ -136,7 +133,6 @@ Socket Socket::connect(const std::string &path) "socket connect failed!"); LogInfo("Connect to OCSP service success with fd:" << fd); - return Socket(fd); } @@ -148,11 +144,9 @@ int Socket::getFd() const RawBuffer Socket::read(void) const { size_t total = 0; - RawBuffer data(1024, 0); auto buf = reinterpret_cast<char *>(data.data()); auto size = data.size(); - LogDebug("Read data from stream on socket fd[" << m_fd << "]"); while (total < size) { @@ -173,20 +167,16 @@ RawBuffer Socket::read(void) const } data.resize(total); - LogDebug("Read data of size[" << total - << "] from stream on socket fd[" << m_fd << "] done."); - + << "] from stream on socket fd[" << m_fd << "] done."); return data; } void Socket::write(const RawBuffer &data) const { size_t total = 0; - auto buf = reinterpret_cast<const char *>(data.data()); auto size = data.size(); - LogDebug("Write data to stream on socket fd[" << m_fd << "]"); while (total < size) { @@ -205,7 +195,7 @@ void Socket::write(const RawBuffer &data) const } LogDebug("Write data of size[" << total << - "] to stream on socket fd[" << m_fd << "] done."); + "] to stream on socket fd[" << m_fd << "] done."); } } // namespace CCHECKER diff --git a/src/common/timer.cpp b/src/common/timer.cpp index 63267d5..395375e 100644 --- a/src/common/timer.cpp +++ b/src/common/timer.cpp @@ -38,7 +38,7 @@ void Timer::timerStart(int interval) { LogDebug("Timer start!!"); - if(m_isRunning) + if (m_isRunning) return; m_isRunning = true; @@ -63,7 +63,7 @@ void Timer::timerStop() void Timer::run() { - while(1) { + while (1) { LogDebug("[timer] running interval : " << m_interval); if (m_isStop) @@ -73,10 +73,9 @@ void Timer::run() m_cv.wait_for( lock, std::chrono::seconds(m_interval), - [this] { - return m_isStop == true; - } - ); + [this] { + return m_isStop == true; + }); job(); } diff --git a/src/common/timer.h b/src/common/timer.h index e24ac35..9029ba7 100644 --- a/src/common/timer.h +++ b/src/common/timer.h @@ -29,8 +29,7 @@ namespace CCHECKER { -class Timer -{ +class Timer { public: Timer(void); virtual ~Timer(void); @@ -45,7 +44,7 @@ public: protected: // This is for derived class member function. - virtual void job(void){} + virtual void job(void) {} void run(); diff --git a/src/db/sql_query.cpp b/src/db/sql_query.cpp index bafbf56..2485b0b 100644 --- a/src/db/sql_query.cpp +++ b/src/db/sql_query.cpp @@ -26,278 +26,292 @@ namespace { - #define DB_ISSUER 101 - #define DB_DATE 102 - #define DB_APP_ID 103 - #define DB_PKG_ID 104 - #define DB_UID 105 - #define DB_CHECK_ID 106 - #define DB_CERTIFICATE 107 - #define DB_VERIFIED 108 - #define DB_CHAIN_ID 109 - #define DB_CERT_ORDER 110 - - // This changes define into question mark and a number in quotes - // e.g. _(DB_ISSUER) -> "?" "101" - #define _(db) __(db) - #define __(db) "?" #db - - // setup - const char *DB_CMD_SETUP = "VACUUM; PRAGMA foregin_keys=ON;"; - - const char *DB_CMD_GET_LAST_INSERTED_ROW = "SELECT last_insert_rowid();"; - - // apps - const char *DB_CMD_ADD_APP = - "INSERT INTO to_check(app_id, pkg_id, uid, verified) VALUES(" _(DB_APP_ID) ", " _(DB_PKG_ID) ", " _(DB_UID) ", " _(DB_VERIFIED) ");"; - - const char *DB_CMD_GET_CHECK_ID = - "SELECT check_id FROM to_check WHERE app_id=" _(DB_APP_ID) " AND pkg_id=" _(DB_PKG_ID) " AND uid=" _(DB_UID) ";"; - - const char *DB_CMD_ADD_CHAIN = - "INSERT INTO chains_to_check(check_id) VALUES(" _(DB_CHECK_ID) ");"; - - const char *DB_CMD_ADD_CERT = - "INSERT INTO certs_to_check(chain_id, certificate, cert_order) VALUES(" _(DB_CHAIN_ID) ", " _(DB_CERTIFICATE) ", " _(DB_CERT_ORDER) ");"; - - const char *DB_CMD_GET_CHAINS = - "SELECT chain_id FROM chains_to_check INNER JOIN to_check ON chains_to_check.check_id=to_check.check_id WHERE to_check.app_id=" - _(DB_APP_ID) " AND to_check.pkg_id=" _(DB_PKG_ID) " AND to_check.uid=" _(DB_UID) ";"; - - const char *DB_CMD_REMOVE_APP = - "DELETE FROM to_check WHERE app_id=" _(DB_APP_ID) " AND pkg_id=" _(DB_PKG_ID) " AND uid=" _(DB_UID) ";"; - - const char *DB_CMD_GET_APPS = - "SELECT app_id, pkg_id, uid, verified FROM to_check"; - - const char *DB_CMD_GET_CERTS = - "SELECT certificate FROM certs_to_check WHERE chain_id=" _(DB_CHAIN_ID) " ORDER BY cert_order ASC;"; - - const char *DB_CMD_SET_APP_AS_VERIFIED = - "UPDATE to_check SET verified=" _(DB_VERIFIED) " WHERE check_id=" _(DB_CHECK_ID) ";"; +#define DB_ISSUER 101 +#define DB_DATE 102 +#define DB_APP_ID 103 +#define DB_PKG_ID 104 +#define DB_UID 105 +#define DB_CHECK_ID 106 +#define DB_CERTIFICATE 107 +#define DB_VERIFIED 108 +#define DB_CHAIN_ID 109 +#define DB_CERT_ORDER 110 + +// This changes define into question mark and a number in quotes +// e.g. _(DB_ISSUER) -> "?" "101" +#define _(db) __(db) +#define __(db) "?" #db + +// setup +const char *DB_CMD_SETUP = "VACUUM; PRAGMA foregin_keys=ON;"; + +const char *DB_CMD_GET_LAST_INSERTED_ROW = "SELECT last_insert_rowid();"; + +// apps +const char *DB_CMD_ADD_APP = + "INSERT INTO to_check(app_id, pkg_id, uid, verified) VALUES(" _(DB_APP_ID) ", " _(DB_PKG_ID) ", " _ + (DB_UID) ", " _(DB_VERIFIED) ");"; + +const char *DB_CMD_GET_CHECK_ID = + "SELECT check_id FROM to_check WHERE app_id=" _(DB_APP_ID) " AND pkg_id=" _ + (DB_PKG_ID) " AND uid=" _(DB_UID) ";"; + +const char *DB_CMD_ADD_CHAIN = + "INSERT INTO chains_to_check(check_id) VALUES(" _(DB_CHECK_ID) ");"; + +const char *DB_CMD_ADD_CERT = + "INSERT INTO certs_to_check(chain_id, certificate, cert_order) VALUES(" _(DB_CHAIN_ID) ", " _ + (DB_CERTIFICATE) ", " _(DB_CERT_ORDER) ");"; + +const char *DB_CMD_GET_CHAINS = + "SELECT chain_id FROM chains_to_check INNER JOIN to_check ON chains_to_check.check_id=to_check.check_id WHERE to_check.app_id=" + _(DB_APP_ID) " AND to_check.pkg_id=" _(DB_PKG_ID) " AND to_check.uid=" _(DB_UID) ";"; + +const char *DB_CMD_REMOVE_APP = + "DELETE FROM to_check WHERE app_id=" _(DB_APP_ID) " AND pkg_id=" _(DB_PKG_ID) " AND uid=" _ + (DB_UID) ";"; + +const char *DB_CMD_GET_APPS = + "SELECT app_id, pkg_id, uid, verified FROM to_check"; + +const char *DB_CMD_GET_CERTS = + "SELECT certificate FROM certs_to_check WHERE chain_id=" _(DB_CHAIN_ID) " ORDER BY cert_order ASC;"; + +const char *DB_CMD_SET_APP_AS_VERIFIED = + "UPDATE to_check SET verified=" _(DB_VERIFIED) " WHERE check_id=" _(DB_CHECK_ID) ";"; } namespace CCHECKER { namespace DB { -SqlQuery::SqlQuery(const std::string& path) +SqlQuery::SqlQuery(const std::string &path) { - m_connection = NULL; - m_inUserTransaction = false; + m_connection = NULL; + m_inUserTransaction = false; - if (!connect(path)) - throw std::runtime_error("Database error"); + if (!connect(path)) + throw std::runtime_error("Database error"); } -bool SqlQuery::connect(const std::string& path) +bool SqlQuery::connect(const std::string &path) { - if (m_connection != NULL) { - LogError("Already connected!"); - return true; - } - - Try { - m_connection = new SqlConnection(path, SqlConnection::Flag::None, SqlConnection::Flag::Option::CRW); - m_connection->ExecCommand(DB_CMD_SETUP); - return true; - } Catch(std::bad_alloc) { - LogError("Couldn't allocate SqlConnection"); - } Catch(SqlConnection::Exception::ConnectionBroken) { - LogError("Couldn't connect to database: " << path); - } Catch(SqlConnection::Exception::InvalidColumn) { - LogError("Couldn't set the key for database"); - } Catch(SqlConnection::Exception::SyntaxError) { - LogError("Couldn't initiate the database"); - } Catch(SqlConnection::Exception::InternalError) { - LogError("Couldn't create the database"); - } - return false; + if (m_connection != NULL) { + LogError("Already connected!"); + return true; + } + + Try { + m_connection = new SqlConnection(path, SqlConnection::Flag::None, SqlConnection::Flag::Option::CRW); + m_connection->ExecCommand(DB_CMD_SETUP); + return true; + } Catch(std::bad_alloc) { + LogError("Couldn't allocate SqlConnection"); + } + Catch(SqlConnection::Exception::ConnectionBroken) { + LogError("Couldn't connect to database: " << path); + } + Catch(SqlConnection::Exception::InvalidColumn) { + LogError("Couldn't set the key for database"); + } + Catch(SqlConnection::Exception::SyntaxError) { + LogError("Couldn't initiate the database"); + } + Catch(SqlConnection::Exception::InternalError) { + LogError("Couldn't create the database"); + } + return false; } SqlQuery::~SqlQuery() { - delete m_connection; + delete m_connection; } bool SqlQuery::check_if_app_exists(const app_t &app) { - int32_t check_id; - return get_check_id(app, check_id); + int32_t check_id; + return get_check_id(app, check_id); } bool SqlQuery::get_check_id(const app_t &app, int32_t &check_id) { - SqlConnection::DataCommandAutoPtr getCheckIDCommand = - m_connection->PrepareDataCommand(DB_CMD_GET_CHECK_ID); - getCheckIDCommand->BindString(DB_APP_ID, app.app_id.c_str()); - getCheckIDCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); - getCheckIDCommand->BindInt64(DB_UID, app.uid); - if (getCheckIDCommand->Step()) { - check_id = getCheckIDCommand->GetColumnInt32(0); - LogDebug("Found check id: " << check_id << ", for app: " << app.app_id); - return true; - } - LogDebug("No check_id for app: " << app.app_id << " in database"); - return false; + SqlConnection::DataCommandAutoPtr getCheckIDCommand = + m_connection->PrepareDataCommand(DB_CMD_GET_CHECK_ID); + getCheckIDCommand->BindString(DB_APP_ID, app.app_id.c_str()); + getCheckIDCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); + getCheckIDCommand->BindInt64(DB_UID, app.uid); + + if (getCheckIDCommand->Step()) { + check_id = getCheckIDCommand->GetColumnInt32(0); + LogDebug("Found check id: " << check_id << ", for app: " << app.app_id); + return true; + } + + LogDebug("No check_id for app: " << app.app_id << " in database"); + return false; } bool SqlQuery::add_chain_id(const int32_t check_id, int32_t &chain_id) { - // Add new chain for an app - SqlConnection::DataCommandAutoPtr addChainCommand = - m_connection->PrepareDataCommand(DB_CMD_ADD_CHAIN); - addChainCommand->BindInt32(DB_CHECK_ID, check_id); - addChainCommand->Step(); - - // get chain_id - SqlConnection::DataCommandAutoPtr getLastInserted = - m_connection->PrepareDataCommand(DB_CMD_GET_LAST_INSERTED_ROW); - if(getLastInserted->Step()) { - chain_id = getLastInserted->GetColumnInt32(0); - LogDebug("Found chain_id: " << chain_id << ", for check_id " << check_id); - return true; - } - return false; + // Add new chain for an app + SqlConnection::DataCommandAutoPtr addChainCommand = + m_connection->PrepareDataCommand(DB_CMD_ADD_CHAIN); + addChainCommand->BindInt32(DB_CHECK_ID, check_id); + addChainCommand->Step(); + // get chain_id + SqlConnection::DataCommandAutoPtr getLastInserted = + m_connection->PrepareDataCommand(DB_CMD_GET_LAST_INSERTED_ROW); + + if (getLastInserted->Step()) { + chain_id = getLastInserted->GetColumnInt32(0); + LogDebug("Found chain_id: " << chain_id << ", for check_id " << check_id); + return true; + } + + return false; } bool SqlQuery::add_app_to_check_list(const app_t &app) { - //Check if app exists in DB - if (check_if_app_exists(app)) { - LogDebug(app.str() << " already exists in database"); - return true; - } - - m_connection->BeginTransaction(); - //Add app to to_check table - SqlConnection::DataCommandAutoPtr addAppCommand = - m_connection->PrepareDataCommand(DB_CMD_ADD_APP); - addAppCommand->BindString(DB_APP_ID, app.app_id.c_str()); - addAppCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); - addAppCommand->BindInt64(DB_UID, app.uid); - addAppCommand->BindInt32(DB_VERIFIED, static_cast<int32_t>(app_t::verified_t::UNKNOWN)); // Set app as not-verified - addAppCommand->Step(); - LogDebug("App " << app.app_id << " added to to_check table, adding certificates."); - - // Get check_id - int32_t check_id; - if (!get_check_id(app, check_id)) { // If get check_id failed return false; - LogDebug("Failed while addind app "<< app.app_id << " to to_check table."); - m_connection->RollbackTransaction(); - return false; - } - - // If get check_id succeed we can add chain to database - int32_t chain_id; - for (const auto &iter : app.signatures) { - // Add chain - if (add_chain_id(check_id, chain_id)) { - // add certificates from chain in right order (start with 1) - end entity go first - int32_t cert_order = 1; - for (const auto &iter_cert : iter) { - SqlConnection::DataCommandAutoPtr addCertCommand = - m_connection->PrepareDataCommand(DB_CMD_ADD_CERT); - addCertCommand->BindInt32(DB_CHAIN_ID, chain_id); - addCertCommand->BindString(DB_CERTIFICATE, iter_cert.c_str()); - addCertCommand->BindInt32(DB_CERT_ORDER, cert_order); - addCertCommand->Step(); - cert_order++; - LogDebug("Certificate for app " << app.app_id << "added"); - } - } else { - LogDebug("Failed to add certificates chain"); - m_connection->RollbackTransaction(); - return false; - } - - } - m_connection->CommitTransaction(); - return true; + //Check if app exists in DB + if (check_if_app_exists(app)) { + LogDebug(app.str() << " already exists in database"); + return true; + } + + m_connection->BeginTransaction(); + //Add app to to_check table + SqlConnection::DataCommandAutoPtr addAppCommand = + m_connection->PrepareDataCommand(DB_CMD_ADD_APP); + addAppCommand->BindString(DB_APP_ID, app.app_id.c_str()); + addAppCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); + addAppCommand->BindInt64(DB_UID, app.uid); + addAppCommand->BindInt32(DB_VERIFIED, + static_cast<int32_t>(app_t::verified_t::UNKNOWN)); // Set app as not-verified + addAppCommand->Step(); + LogDebug("App " << app.app_id << " added to to_check table, adding certificates."); + // Get check_id + int32_t check_id; + + if (!get_check_id(app, check_id)) { // If get check_id failed return false; + LogDebug("Failed while addind app " << app.app_id << " to to_check table."); + m_connection->RollbackTransaction(); + return false; + } + + // If get check_id succeed we can add chain to database + int32_t chain_id; + + for (const auto &iter : app.signatures) { + // Add chain + if (add_chain_id(check_id, chain_id)) { + // add certificates from chain in right order (start with 1) - end entity go first + int32_t cert_order = 1; + + for (const auto &iter_cert : iter) { + SqlConnection::DataCommandAutoPtr addCertCommand = + m_connection->PrepareDataCommand(DB_CMD_ADD_CERT); + addCertCommand->BindInt32(DB_CHAIN_ID, chain_id); + addCertCommand->BindString(DB_CERTIFICATE, iter_cert.c_str()); + addCertCommand->BindInt32(DB_CERT_ORDER, cert_order); + addCertCommand->Step(); + cert_order++; + LogDebug("Certificate for app " << app.app_id << "added"); + } + } else { + LogDebug("Failed to add certificates chain"); + m_connection->RollbackTransaction(); + return false; + } + } + + m_connection->CommitTransaction(); + return true; } void SqlQuery::remove_app_from_check_list(const app_t &app) { - LogDebug("Removing app: " << app.str()); - - //Remove app from to_check table - SqlConnection::DataCommandAutoPtr removeAppCommand = - m_connection->PrepareDataCommand(DB_CMD_REMOVE_APP); - removeAppCommand->BindString(DB_APP_ID, app.app_id.c_str()); - removeAppCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); - removeAppCommand->BindInt32(DB_UID, app.uid); - removeAppCommand->Step(); - LogDebug("Removed app: " << app.str()); - - // Removing certificates should be done automatically by DB because of - // ON DELETE CASCADE for check_id + LogDebug("Removing app: " << app.str()); + //Remove app from to_check table + SqlConnection::DataCommandAutoPtr removeAppCommand = + m_connection->PrepareDataCommand(DB_CMD_REMOVE_APP); + removeAppCommand->BindString(DB_APP_ID, app.app_id.c_str()); + removeAppCommand->BindString(DB_PKG_ID, app.pkg_id.c_str()); + removeAppCommand->BindInt32(DB_UID, app.uid); + removeAppCommand->Step(); + LogDebug("Removed app: " << app.str()); + // Removing certificates should be done automatically by DB because of + // ON DELETE CASCADE for check_id } void SqlQuery::mark_as_verified(const app_t &app, const app_t::verified_t &verified) { - int32_t check_id; - - if (get_check_id(app, check_id)) { - SqlConnection::DataCommandAutoPtr setVerifiedCommand = - m_connection->PrepareDataCommand(DB_CMD_SET_APP_AS_VERIFIED); - setVerifiedCommand->BindInt32(DB_CHECK_ID, check_id); - setVerifiedCommand->BindInt32(DB_VERIFIED, static_cast<int32_t>(verified)); - setVerifiedCommand->Step(); - LogDebug("App: " << app.str() << " marked as verified: " << static_cast<int32_t>(verified)); - } + int32_t check_id; + + if (get_check_id(app, check_id)) { + SqlConnection::DataCommandAutoPtr setVerifiedCommand = + m_connection->PrepareDataCommand(DB_CMD_SET_APP_AS_VERIFIED); + setVerifiedCommand->BindInt32(DB_CHECK_ID, check_id); + setVerifiedCommand->BindInt32(DB_VERIFIED, static_cast<int32_t>(verified)); + setVerifiedCommand->Step(); + LogDebug("App: " << app.str() << " marked as verified: " << static_cast<int32_t>(verified)); + } } void SqlQuery::get_apps(std::list<app_t> &apps_buffer) { - // This function will fill buffer with check_id, app_id, pkg_id, uid and verified fields - - // it leaves certificates' list empty. - SqlConnection::DataCommandAutoPtr getAppsCommand = - m_connection->PrepareDataCommand(DB_CMD_GET_APPS); - - while (getAppsCommand->Step()) { - app_t app; - app.app_id = getAppsCommand->GetColumnString(0); - app.pkg_id = getAppsCommand->GetColumnString(1); - app.uid = getAppsCommand->GetColumnInt64(2); - app.verified = static_cast<app_t::verified_t>(getAppsCommand->GetColumnInt32(3)); - app.signatures = {}; - LogDebug("App read from DB: app_id: " << app.str() << ", verified: " << static_cast<int32_t>(app.verified)); - apps_buffer.push_back(app); - } + // This function will fill buffer with check_id, app_id, pkg_id, uid and verified fields - + // it leaves certificates' list empty. + SqlConnection::DataCommandAutoPtr getAppsCommand = + m_connection->PrepareDataCommand(DB_CMD_GET_APPS); + + while (getAppsCommand->Step()) { + app_t app; + app.app_id = getAppsCommand->GetColumnString(0); + app.pkg_id = getAppsCommand->GetColumnString(1); + app.uid = getAppsCommand->GetColumnInt64(2); + app.verified = static_cast<app_t::verified_t>(getAppsCommand->GetColumnInt32(3)); + app.signatures = {}; + LogDebug("App read from DB: app_id: " << app.str() << ", verified: " << static_cast<int32_t> + (app.verified)); + apps_buffer.push_back(app); + } } void SqlQuery::get_app_list(std::list<app_t> &apps_buffer) { - m_connection->BeginTransaction(); - get_apps(apps_buffer); - - // Get chain for every application - for (auto &iter_app : apps_buffer) { - SqlConnection::DataCommandAutoPtr getChainsCommand = - m_connection->PrepareDataCommand(DB_CMD_GET_CHAINS); - getChainsCommand->BindString(DB_APP_ID, iter_app.app_id.c_str()); - getChainsCommand->BindString(DB_PKG_ID, iter_app.pkg_id.c_str()); - getChainsCommand->BindInt32(DB_UID, iter_app.uid); - - // Get all certs from chain - certs will be sorted - end entity go first - while (getChainsCommand->Step()) { - chain_t chain; - int32_t chain_id; - chain_id = getChainsCommand->GetColumnInt32(0); - LogDebug("Found chain (" << chain_id << ") for " << iter_app.str()); - - SqlConnection::DataCommandAutoPtr getCertsCommand = - m_connection->PrepareDataCommand(DB_CMD_GET_CERTS); - getCertsCommand->BindInt32(DB_CHAIN_ID, chain_id); - - // Add found certs to chain - while (getCertsCommand->Step()) { - chain.push_back(getCertsCommand->GetColumnString(0)); - LogDebug("Found certificate (" << chain.size() << ") in chain no. " << chain_id); - } - iter_app.signatures.push_back(chain); - } - } - m_connection->CommitTransaction(); + m_connection->BeginTransaction(); + get_apps(apps_buffer); + + // Get chain for every application + for (auto &iter_app : apps_buffer) { + SqlConnection::DataCommandAutoPtr getChainsCommand = + m_connection->PrepareDataCommand(DB_CMD_GET_CHAINS); + getChainsCommand->BindString(DB_APP_ID, iter_app.app_id.c_str()); + getChainsCommand->BindString(DB_PKG_ID, iter_app.pkg_id.c_str()); + getChainsCommand->BindInt32(DB_UID, iter_app.uid); + + // Get all certs from chain - certs will be sorted - end entity go first + while (getChainsCommand->Step()) { + chain_t chain; + int32_t chain_id; + chain_id = getChainsCommand->GetColumnInt32(0); + LogDebug("Found chain (" << chain_id << ") for " << iter_app.str()); + SqlConnection::DataCommandAutoPtr getCertsCommand = + m_connection->PrepareDataCommand(DB_CMD_GET_CERTS); + getCertsCommand->BindInt32(DB_CHAIN_ID, chain_id); + + // Add found certs to chain + while (getCertsCommand->Step()) { + chain.push_back(getCertsCommand->GetColumnString(0)); + LogDebug("Found certificate (" << chain.size() << ") in chain no. " << chain_id); + } + + iter_app.signatures.push_back(chain); + } + } + + m_connection->CommitTransaction(); } } // DB diff --git a/src/dpl/core/include/cchecker/dpl/assert.h b/src/dpl/core/include/cchecker/dpl/assert.h index 03dd7d0..1bb918e 100644 --- a/src/dpl/core/include/cchecker/dpl/assert.h +++ b/src/dpl/core/include/cchecker/dpl/assert.h @@ -29,15 +29,15 @@ namespace CCHECKER { // Do not call directly // Always use Assert macro CCHECKER_NORETURN void AssertProc(const char *condition, - const char *file, - int line, - const char *function); + const char *file, + int line, + const char *function); } // namespace CCHECKER #define Assert(Condition) do { if (!(Condition)) { CCHECKER::AssertProc(#Condition, \ - __FILE__, \ - __LINE__, \ - __FUNCTION__); \ - } } while (0) + __FILE__, \ + __LINE__, \ + __FUNCTION__); \ + } } while (0) #endif // CCHECKER_ASSERT_H diff --git a/src/dpl/core/include/cchecker/dpl/colors.h b/src/dpl/core/include/cchecker/dpl/colors.h index d652f5b..b1cf04a 100644 --- a/src/dpl/core/include/cchecker/dpl/colors.h +++ b/src/dpl/core/include/cchecker/dpl/colors.h @@ -27,46 +27,46 @@ namespace CCHECKER { namespace Colors { namespace Text { -extern const char* BOLD_GREEN_BEGIN; -extern const char* BOLD_GREEN_END; -extern const char* PURPLE_BEGIN; -extern const char* PURPLE_END; -extern const char* RED_BEGIN; -extern const char* RED_END; -extern const char* GREEN_BEGIN; -extern const char* GREEN_END; -extern const char* CYAN_BEGIN; -extern const char* CYAN_END; -extern const char* BOLD_RED_BEGIN; -extern const char* BOLD_RED_END; -extern const char* BOLD_YELLOW_BEGIN; -extern const char* BOLD_YELLOW_END; -extern const char* BOLD_GOLD_BEGIN; -extern const char* BOLD_GOLD_END; -extern const char* BOLD_WHITE_BEGIN; -extern const char* BOLD_WHITE_END; -extern const char* COLOR_END; +extern const char *BOLD_GREEN_BEGIN; +extern const char *BOLD_GREEN_END; +extern const char *PURPLE_BEGIN; +extern const char *PURPLE_END; +extern const char *RED_BEGIN; +extern const char *RED_END; +extern const char *GREEN_BEGIN; +extern const char *GREEN_END; +extern const char *CYAN_BEGIN; +extern const char *CYAN_END; +extern const char *BOLD_RED_BEGIN; +extern const char *BOLD_RED_END; +extern const char *BOLD_YELLOW_BEGIN; +extern const char *BOLD_YELLOW_END; +extern const char *BOLD_GOLD_BEGIN; +extern const char *BOLD_GOLD_END; +extern const char *BOLD_WHITE_BEGIN; +extern const char *BOLD_WHITE_END; +extern const char *COLOR_END; } //namespace Text namespace Html { -extern const char* BOLD_GREEN_BEGIN; -extern const char* BOLD_GREEN_END; -extern const char* PURPLE_BEGIN; -extern const char* PURPLE_END; -extern const char* RED_BEGIN; -extern const char* RED_END; -extern const char* GREEN_BEGIN; -extern const char* GREEN_END; -extern const char* CYAN_BEGIN; -extern const char* CYAN_END; -extern const char* BOLD_RED_BEGIN; -extern const char* BOLD_RED_END; -extern const char* BOLD_YELLOW_BEGIN; -extern const char* BOLD_YELLOW_END; -extern const char* BOLD_GOLD_BEGIN; -extern const char* BOLD_GOLD_END; -extern const char* BOLD_WHITE_BEGIN; -extern const char* BOLD_WHITE_END; +extern const char *BOLD_GREEN_BEGIN; +extern const char *BOLD_GREEN_END; +extern const char *PURPLE_BEGIN; +extern const char *PURPLE_END; +extern const char *RED_BEGIN; +extern const char *RED_END; +extern const char *GREEN_BEGIN; +extern const char *GREEN_END; +extern const char *CYAN_BEGIN; +extern const char *CYAN_END; +extern const char *BOLD_RED_BEGIN; +extern const char *BOLD_RED_END; +extern const char *BOLD_YELLOW_BEGIN; +extern const char *BOLD_YELLOW_END; +extern const char *BOLD_GOLD_BEGIN; +extern const char *BOLD_GOLD_END; +extern const char *BOLD_WHITE_BEGIN; +extern const char *BOLD_WHITE_END; } //namespace Html } //namespace Colors } //namespace CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/exception.h b/src/dpl/core/include/cchecker/dpl/exception.h index f7b9afc..a23e4ef 100644 --- a/src/dpl/core/include/cchecker/dpl/exception.h +++ b/src/dpl/core/include/cchecker/dpl/exception.h @@ -32,340 +32,331 @@ namespace CCHECKER { void LogUnhandledException(const std::string &str); void LogUnhandledException(const std::string &str, - const char *filename, - int line, - const char *function); + const char *filename, + int line, + const char *function); } namespace CCHECKER { -class Exception -{ - private: - static unsigned int m_exceptionCount; - static Exception* m_lastException; - static void (*m_terminateHandler)(); - - static void AddRef(Exception* exception) - { - if (!m_exceptionCount) { - m_terminateHandler = std::set_terminate(&TerminateHandler); - } - - ++m_exceptionCount; - m_lastException = exception; - } - - static void UnRef(Exception* e) - { - if (m_lastException == e) { - m_lastException = NULL; - } - - --m_exceptionCount; - - if (!m_exceptionCount) { - std::set_terminate(m_terminateHandler); - m_terminateHandler = NULL; - } - } - - static void TerminateHandler() - { - if (m_lastException != NULL) { - DisplayKnownException(*m_lastException); - abort(); - } else { - DisplayUnknownException(); - abort(); - } - } - - Exception *m_reason; - std::string m_path; - std::string m_function; - int m_line; - - protected: - std::string m_message; - std::string m_className; - - public: - static std::string KnownExceptionToString(const Exception &e) - { - std::ostringstream message; - message << - "\033[1;5;31m\n=== Unhandled CCHECKER exception occurred ===\033[m\n\n"; - message << "\033[1;33mException trace:\033[m\n\n"; - message << e.DumpToString(); - message << "\033[1;31m\n=== Will now abort ===\033[m\n"; - - return message.str(); - } - - static std::string UnknownExceptionToString() - { - std::ostringstream message; - message << - "\033[1;5;31m\n=== Unhandled non-CCHECKER exception occurred ===\033[m\n\n"; - message << "\033[1;31m\n=== Will now abort ===\033[m\n"; - - return message.str(); - } - - static void DisplayKnownException(const Exception& e) - { - LogUnhandledException(KnownExceptionToString(e).c_str()); - } - - static void DisplayUnknownException() - { - LogUnhandledException(UnknownExceptionToString().c_str()); - } - - Exception(const Exception &other) - { - // Deep copy - if (other.m_reason != NULL) { - m_reason = new Exception(*other.m_reason); - } else { - m_reason = NULL; - } - - m_message = other.m_message; - m_path = other.m_path; - m_function = other.m_function; - m_line = other.m_line; - - m_className = other.m_className; - - AddRef(this); - } - - const Exception &operator =(const Exception &other) - { - if (this == &other) { - return *this; - } - - // Deep copy - if (other.m_reason != NULL) { - m_reason = new Exception(*other.m_reason); - } else { - m_reason = NULL; - } - - m_message = other.m_message; - m_path = other.m_path; - m_function = other.m_function; - m_line = other.m_line; - - m_className = other.m_className; - - AddRef(this); - - return *this; - } - - Exception(const char *path, - const char *function, - int line, - const std::string &message) : - m_reason(NULL), - m_path(path), - m_function(function), - m_line(line), - m_message(message) - { - AddRef(this); - } - - Exception(const char *path, - const char *function, - int line, - const Exception &reason, - const std::string &message) : - m_reason(new Exception(reason)), - m_path(path), - m_function(function), - m_line(line), - m_message(message) - { - AddRef(this); - } - - virtual ~Exception() throw() - { - if (m_reason != NULL) { - delete m_reason; - m_reason = NULL; - } - - UnRef(this); - } - - void Dump() const - { - // Show reason first - if (m_reason != NULL) { - m_reason->Dump(); - } - - // Afterward, dump exception - const char *file = strchr(m_path.c_str(), '/'); - - if (file == NULL) { - file = m_path.c_str(); - } else { - ++file; - } - - printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", - file, m_line, - m_function.c_str(), - m_className.c_str(), - m_message.empty() ? "<EMPTY>" : m_message.c_str()); - } - - std::string DumpToString() const - { - std::string ret; - if (m_reason != NULL) { - ret = m_reason->DumpToString(); - } - - const char *file = strchr(m_path.c_str(), '/'); - - if (file == NULL) { - file = m_path.c_str(); - } else { - ++file; - } - - char buf[1024]; - snprintf(buf, - sizeof(buf), - "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", - file, - m_line, - m_function.c_str(), - m_className.c_str(), - m_message.empty() ? "<EMPTY>" : m_message.c_str()); - - buf[sizeof(buf) - 1] = '\n'; - ret += buf; - - return ret; - } - - Exception *GetReason() const - { - return m_reason; - } - - std::string GetPath() const - { - return m_path; - } - - std::string GetFunction() const - { - return m_function; - } - - int GetLine() const - { - return m_line; - } - - std::string GetMessage() const - { - return m_message; - } - - std::string GetClassName() const - { - return m_className; - } +class Exception { +private: + static unsigned int m_exceptionCount; + static Exception *m_lastException; + static void (*m_terminateHandler)(); + + static void AddRef(Exception *exception) + { + if (!m_exceptionCount) { + m_terminateHandler = std::set_terminate(&TerminateHandler); + } + + ++m_exceptionCount; + m_lastException = exception; + } + + static void UnRef(Exception *e) + { + if (m_lastException == e) { + m_lastException = NULL; + } + + --m_exceptionCount; + + if (!m_exceptionCount) { + std::set_terminate(m_terminateHandler); + m_terminateHandler = NULL; + } + } + + static void TerminateHandler() + { + if (m_lastException != NULL) { + DisplayKnownException(*m_lastException); + abort(); + } else { + DisplayUnknownException(); + abort(); + } + } + + Exception *m_reason; + std::string m_path; + std::string m_function; + int m_line; + +protected: + std::string m_message; + std::string m_className; + +public: + static std::string KnownExceptionToString(const Exception &e) + { + std::ostringstream message; + message << + "\033[1;5;31m\n=== Unhandled CCHECKER exception occurred ===\033[m\n\n"; + message << "\033[1;33mException trace:\033[m\n\n"; + message << e.DumpToString(); + message << "\033[1;31m\n=== Will now abort ===\033[m\n"; + return message.str(); + } + + static std::string UnknownExceptionToString() + { + std::ostringstream message; + message << + "\033[1;5;31m\n=== Unhandled non-CCHECKER exception occurred ===\033[m\n\n"; + message << "\033[1;31m\n=== Will now abort ===\033[m\n"; + return message.str(); + } + + static void DisplayKnownException(const Exception &e) + { + LogUnhandledException(KnownExceptionToString(e).c_str()); + } + + static void DisplayUnknownException() + { + LogUnhandledException(UnknownExceptionToString().c_str()); + } + + Exception(const Exception &other) + { + // Deep copy + if (other.m_reason != NULL) { + m_reason = new Exception(*other.m_reason); + } else { + m_reason = NULL; + } + + m_message = other.m_message; + m_path = other.m_path; + m_function = other.m_function; + m_line = other.m_line; + m_className = other.m_className; + AddRef(this); + } + + const Exception &operator =(const Exception &other) + { + if (this == &other) { + return *this; + } + + // Deep copy + if (other.m_reason != NULL) { + m_reason = new Exception(*other.m_reason); + } else { + m_reason = NULL; + } + + m_message = other.m_message; + m_path = other.m_path; + m_function = other.m_function; + m_line = other.m_line; + m_className = other.m_className; + AddRef(this); + return *this; + } + + Exception(const char *path, + const char *function, + int line, + const std::string &message) : + m_reason(NULL), + m_path(path), + m_function(function), + m_line(line), + m_message(message) + { + AddRef(this); + } + + Exception(const char *path, + const char *function, + int line, + const Exception &reason, + const std::string &message) : + m_reason(new Exception(reason)), + m_path(path), + m_function(function), + m_line(line), + m_message(message) + { + AddRef(this); + } + + virtual ~Exception() throw() + { + if (m_reason != NULL) { + delete m_reason; + m_reason = NULL; + } + + UnRef(this); + } + + void Dump() const + { + // Show reason first + if (m_reason != NULL) { + m_reason->Dump(); + } + + // Afterward, dump exception + const char *file = strchr(m_path.c_str(), '/'); + + if (file == NULL) { + file = m_path.c_str(); + } else { + ++file; + } + + printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", + file, m_line, + m_function.c_str(), + m_className.c_str(), + m_message.empty() ? "<EMPTY>" : m_message.c_str()); + } + + std::string DumpToString() const + { + std::string ret; + + if (m_reason != NULL) { + ret = m_reason->DumpToString(); + } + + const char *file = strchr(m_path.c_str(), '/'); + + if (file == NULL) { + file = m_path.c_str(); + } else { + ++file; + } + + char buf[1024]; + snprintf(buf, + sizeof(buf), + "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", + file, + m_line, + m_function.c_str(), + m_className.c_str(), + m_message.empty() ? "<EMPTY>" : m_message.c_str()); + buf[sizeof(buf) - 1] = '\n'; + ret += buf; + return ret; + } + + Exception *GetReason() const + { + return m_reason; + } + + std::string GetPath() const + { + return m_path; + } + + std::string GetFunction() const + { + return m_function; + } + + int GetLine() const + { + return m_line; + } + + std::string GetMessage() const + { + return m_message; + } + + std::string GetClassName() const + { + return m_className; + } }; } // namespace CCHECKER #define Try try #define Throw(ClassName) \ - throw ClassName(__FILE__, __FUNCTION__, __LINE__) + throw ClassName(__FILE__, __FUNCTION__, __LINE__) #define ThrowMsg(ClassName, Message) \ - do \ - { \ - std::ostringstream dplLoggingStream; \ - dplLoggingStream << Message; \ - throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \ - } while (0) + do \ + { \ + std::ostringstream dplLoggingStream; \ + dplLoggingStream << Message; \ + throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \ + } while (0) #define ReThrow(ClassName) \ - throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception) + throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception) #define ReThrowMsg(ClassName, Message) \ - throw ClassName(__FILE__, \ - __FUNCTION__, \ - __LINE__, \ - _rethrown_exception, \ - Message) + throw ClassName(__FILE__, \ + __FUNCTION__, \ + __LINE__, \ + _rethrown_exception, \ + Message) #define Catch(ClassName) \ - catch (const ClassName &_rethrown_exception) + catch (const ClassName &_rethrown_exception) #define DECLARE_EXCEPTION_TYPE(BaseClass, Class) \ - class Class : \ - public BaseClass \ - { \ - public: \ - Class(const char *path, \ - const char *function, \ - int line, \ - const std::string & message = std::string()) : \ - BaseClass(path, function, line, message) \ - { \ - BaseClass::m_className = #Class; \ - } \ - \ - Class(const char *path, \ - const char *function, \ - int line, \ - const CCHECKER::Exception & reason, \ - const std::string & message = std::string()) : \ - BaseClass(path, function, line, reason, message) \ - { \ - BaseClass::m_className = #Class; \ - } \ - }; + class Class : \ + public BaseClass \ + { \ + public: \ + Class(const char *path, \ + const char *function, \ + int line, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, message) \ + { \ + BaseClass::m_className = #Class; \ + } \ + \ + Class(const char *path, \ + const char *function, \ + int line, \ + const CCHECKER::Exception & reason, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, reason, message) \ + { \ + BaseClass::m_className = #Class; \ + } \ + }; #define UNHANDLED_EXCEPTION_HANDLER_BEGIN try #define UNHANDLED_EXCEPTION_HANDLER_END \ - catch (const CCHECKER::Exception &exception) \ - { \ - std::ostringstream msg; \ - msg << CCHECKER::Exception::KnownExceptionToString(exception); \ - CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ - abort(); \ - } \ - catch (std::exception& e) \ - { \ - std::ostringstream msg; \ - msg << e.what(); \ - msg << "\n"; \ - msg << CCHECKER::Exception::UnknownExceptionToString(); \ - CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ - abort(); \ - } \ - catch (...) \ - { \ - std::ostringstream msg; \ - msg << CCHECKER::Exception::UnknownExceptionToString(); \ - CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ - abort(); \ - } + catch (const CCHECKER::Exception &exception) \ + { \ + std::ostringstream msg; \ + msg << CCHECKER::Exception::KnownExceptionToString(exception); \ + CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ + abort(); \ + } \ + catch (std::exception& e) \ + { \ + std::ostringstream msg; \ + msg << e.what(); \ + msg << "\n"; \ + msg << CCHECKER::Exception::UnknownExceptionToString(); \ + CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ + abort(); \ + } \ + catch (...) \ + { \ + std::ostringstream msg; \ + msg << CCHECKER::Exception::UnknownExceptionToString(); \ + CCHECKER::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__); \ + abort(); \ + } namespace CCHECKER { namespace CommonException { @@ -377,8 +368,8 @@ namespace CommonException { * important messages. */ DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from - // underlying libraries or - // kernel +// underlying libraries or +// kernel } } diff --git a/src/dpl/core/include/cchecker/dpl/noncopyable.h b/src/dpl/core/include/cchecker/dpl/noncopyable.h index 747299c..47fc8b3 100644 --- a/src/dpl/core/include/cchecker/dpl/noncopyable.h +++ b/src/dpl/core/include/cchecker/dpl/noncopyable.h @@ -23,15 +23,14 @@ #define CCHECKER_NONCOPYABLE_H namespace CCHECKER { -class Noncopyable -{ - private: - Noncopyable(const Noncopyable &); - const Noncopyable &operator=(const Noncopyable &); +class Noncopyable { +private: + Noncopyable(const Noncopyable &); + const Noncopyable &operator=(const Noncopyable &); - public: - Noncopyable(); - virtual ~Noncopyable(); +public: + Noncopyable(); + virtual ~Noncopyable(); }; } // namespace CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/optional.h b/src/dpl/core/include/cchecker/dpl/optional.h index 42d1bd4..0f19d86 100644 --- a/src/dpl/core/include/cchecker/dpl/optional.h +++ b/src/dpl/core/include/cchecker/dpl/optional.h @@ -26,135 +26,137 @@ namespace CCHECKER { template <typename Type> -class Optional -{ - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, NullReference) - }; - - public: - Optional() : - m_null(true), - m_value() - {} - - Optional(const Type& t) : - m_null(false), - m_value(t) - {} - - bool IsNull() const - { - return m_null; - } - - Type& operator*() - { - if (m_null) { - Throw(typename Exception::NullReference); - } - return m_value; - } - - const Type& operator*() const - { - if (m_null) { - Throw(typename Exception::NullReference); - } - return m_value; - } - - const Type* operator->() const - { - if (m_null) { - Throw(typename Exception::NullReference); - } - return &m_value; - } - - Type* operator->() - { - if (m_null) { - Throw(typename Exception::NullReference); - } - return &m_value; - } - - bool operator!() const - { - return m_null; - } - - Optional<Type>& operator=(const Type& other) - { - m_null = false; - m_value = other; - return *this; - } - - bool operator==(const Optional<Type>& aSecond) const - { - return LogicalOperator<true>(*this, aSecond, - std::equal_to<Type>(), std::equal_to<bool>()); - } - - bool operator==(const Type& aSecond) const - { - return Optional<Type>(aSecond) == *this; - } - - bool operator!=(const Optional<Type>& aSecond) const - { - return !(*this == aSecond); - } - - bool operator<(const Optional<Type>& aSecond) const - { - return LogicalOperator<false>(*this, aSecond, - std::less<Type>(), std::less<bool>()); - } - - bool operator>(const Optional<Type>& aSecond) const - { - return LogicalOperator<false>(*this, aSecond, - std::greater<Type>(), std::greater<bool>()); - } - - bool operator<=(const Optional<Type>& aSecond) const - { - return *this == aSecond || *this < aSecond; - } - - bool operator>=(const Optional<Type>& aSecond) const - { - return *this == aSecond || *this > aSecond; - } - - static Optional<Type> Null; - - private: - bool m_null; - Type m_value; - - template <bool taEquality, typename taComparator, typename taNullComparator> - static bool LogicalOperator(const Optional<Type>& aFirst, - const Optional<Type>& aSecond, - taComparator aComparator, - taNullComparator aNullComparator) - { - if (aFirst.m_null == aSecond.m_null) { - if (aFirst.m_null) { - return taEquality; - } else { - return aComparator(aFirst.m_value, aSecond.m_value); - } - } else { - return aNullComparator(aFirst.m_null, aSecond.m_null); - } - } +class Optional { + class Exception { + public: + DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, NullReference) + }; + +public: + Optional() : + m_null(true), + m_value() + {} + + Optional(const Type &t) : + m_null(false), + m_value(t) + {} + + bool IsNull() const + { + return m_null; + } + + Type &operator*() + { + if (m_null) { + Throw(typename Exception::NullReference); + } + + return m_value; + } + + const Type &operator*() const + { + if (m_null) { + Throw(typename Exception::NullReference); + } + + return m_value; + } + + const Type *operator->() const + { + if (m_null) { + Throw(typename Exception::NullReference); + } + + return &m_value; + } + + Type *operator->() + { + if (m_null) { + Throw(typename Exception::NullReference); + } + + return &m_value; + } + + bool operator!() const + { + return m_null; + } + + Optional<Type> &operator=(const Type &other) + { + m_null = false; + m_value = other; + return *this; + } + + bool operator==(const Optional<Type> &aSecond) const + { + return LogicalOperator<true>(*this, aSecond, + std::equal_to<Type>(), std::equal_to<bool>()); + } + + bool operator==(const Type &aSecond) const + { + return Optional<Type>(aSecond) == *this; + } + + bool operator!=(const Optional<Type> &aSecond) const + { + return !(*this == aSecond); + } + + bool operator<(const Optional<Type> &aSecond) const + { + return LogicalOperator<false>(*this, aSecond, + std::less<Type>(), std::less<bool>()); + } + + bool operator>(const Optional<Type> &aSecond) const + { + return LogicalOperator<false>(*this, aSecond, + std::greater<Type>(), std::greater<bool>()); + } + + bool operator<=(const Optional<Type> &aSecond) const + { + return *this == aSecond || *this < aSecond; + } + + bool operator>=(const Optional<Type> &aSecond) const + { + return *this == aSecond || *this > aSecond; + } + + static Optional<Type> Null; + +private: + bool m_null; + Type m_value; + + template <bool taEquality, typename taComparator, typename taNullComparator> + static bool LogicalOperator(const Optional<Type> &aFirst, + const Optional<Type> &aSecond, + taComparator aComparator, + taNullComparator aNullComparator) + { + if (aFirst.m_null == aSecond.m_null) { + if (aFirst.m_null) { + return taEquality; + } else { + return aComparator(aFirst.m_value, aSecond.m_value); + } + } else { + return aNullComparator(aFirst.m_null, aSecond.m_null); + } + } }; template<typename Type> @@ -162,14 +164,14 @@ Optional<Type> Optional<Type>::Null = Optional<Type>(); } //namespace CCHECKER template<typename Type> -std::ostream& operator<<(std::ostream& aStream, - const CCHECKER::Optional<Type>& aOptional) +std::ostream &operator<<(std::ostream &aStream, + const CCHECKER::Optional<Type> &aOptional) { - if (aOptional.IsNull()) { - return aStream << "null optional"; - } else { - return aStream << *aOptional; - } + if (aOptional.IsNull()) { + return aStream << "null optional"; + } else { + return aStream << *aOptional; + } } #endif // CCHECKER_OPTIONAL_VALUE_H diff --git a/src/dpl/core/include/cchecker/dpl/scoped_array.h b/src/dpl/core/include/cchecker/dpl/scoped_array.h index 54c0c80..f38ae83 100644 --- a/src/dpl/core/include/cchecker/dpl/scoped_array.h +++ b/src/dpl/core/include/cchecker/dpl/scoped_array.h @@ -29,36 +29,33 @@ namespace CCHECKER { template<typename Class> -struct ScopedArrayPolicy -{ - typedef Class* Type; - static Type NullValue() - { - return NULL; - } - static void Destroy(Type ptr) - { - delete[] ptr; - } +struct ScopedArrayPolicy { + typedef Class *Type; + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + delete[] ptr; + } }; template<typename Class> -class ScopedArray : public ScopedResource<ScopedArrayPolicy<Class> > -{ - typedef ScopedArrayPolicy<Class> Policy; - typedef ScopedResource<Policy> BaseType; - - public: - explicit ScopedArray(Class *ptr = Policy::NullValue()) : BaseType(ptr) { } - - Class &operator [](std::ptrdiff_t k) const - { - Assert(this->m_value != Policy::NullValue() && - "Dereference of scoped NULL array!"); - Assert(k >= 0 && "Negative array index"); - - return this->m_value[k]; - } +class ScopedArray : public ScopedResource<ScopedArrayPolicy<Class>> { + typedef ScopedArrayPolicy<Class> Policy; + typedef ScopedResource<Policy> BaseType; + +public: + explicit ScopedArray(Class *ptr = Policy::NullValue()) : BaseType(ptr) { } + + Class &operator[](std::ptrdiff_t k) const + { + Assert(this->m_value != Policy::NullValue() && + "Dereference of scoped NULL array!"); + Assert(k >= 0 && "Negative array index"); + return this->m_value[k]; + } }; } // namespace CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/scoped_free.h b/src/dpl/core/include/cchecker/dpl/scoped_free.h index d8fee50..72b0ae0 100644 --- a/src/dpl/core/include/cchecker/dpl/scoped_free.h +++ b/src/dpl/core/include/cchecker/dpl/scoped_free.h @@ -30,27 +30,25 @@ namespace CCHECKER { template<typename Class> -struct ScopedFreePolicy -{ - typedef Class* Type; - static Type NullValue() - { - return NULL; - } - static void Destroy(Type ptr) - { - free(ptr); - } +struct ScopedFreePolicy { + typedef Class *Type; + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + free(ptr); + } }; template<typename Memory> -class ScopedFree : public ScopedResource<ScopedFreePolicy<Memory> > -{ - typedef ScopedFreePolicy<Memory> Policy; - typedef ScopedResource<Policy> BaseType; +class ScopedFree : public ScopedResource<ScopedFreePolicy<Memory>> { + typedef ScopedFreePolicy<Memory> Policy; + typedef ScopedResource<Policy> BaseType; - public: - explicit ScopedFree(Memory *ptr = Policy::NullValue()) : BaseType(ptr) { } +public: + explicit ScopedFree(Memory *ptr = Policy::NullValue()) : BaseType(ptr) { } }; } // namespace CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/scoped_resource.h b/src/dpl/core/include/cchecker/dpl/scoped_resource.h index 2b3c72d..42aef36 100644 --- a/src/dpl/core/include/cchecker/dpl/scoped_resource.h +++ b/src/dpl/core/include/cchecker/dpl/scoped_resource.h @@ -27,53 +27,52 @@ namespace CCHECKER { template<typename ClassPolicy> class ScopedResource : - private Noncopyable -{ - public: - typedef typename ClassPolicy::Type ValueType; - typedef ScopedResource<ClassPolicy> ThisType; + private Noncopyable { +public: + typedef typename ClassPolicy::Type ValueType; + typedef ScopedResource<ClassPolicy> ThisType; - protected: - ValueType m_value; +protected: + ValueType m_value; - public: - explicit ScopedResource(ValueType value) : m_value(value) { } +public: + explicit ScopedResource(ValueType value) : m_value(value) { } - ~ScopedResource() - { - ClassPolicy::Destroy(m_value); - } + ~ScopedResource() + { + ClassPolicy::Destroy(m_value); + } - ValueType Get() const - { - return m_value; - } + ValueType Get() const + { + return m_value; + } - void Reset(ValueType value = ClassPolicy::NullValue()) - { - ClassPolicy::Destroy(m_value); - m_value = value; - } + void Reset(ValueType value = ClassPolicy::NullValue()) + { + ClassPolicy::Destroy(m_value); + m_value = value; + } - ValueType Release() - { - ValueType value = m_value; - m_value = ClassPolicy::NullValue(); - return value; - } - typedef ValueType ThisType::*UnknownBoolType; + ValueType Release() + { + ValueType value = m_value; + m_value = ClassPolicy::NullValue(); + return value; + } + typedef ValueType ThisType::*UnknownBoolType; - operator UnknownBoolType() const - { - return m_value == ClassPolicy::NullValue() ? - 0 : //0 is valid here because it converts to false - &ThisType::m_value; //it converts to true - } + operator UnknownBoolType() const + { + return m_value == ClassPolicy::NullValue() ? + 0 : //0 is valid here because it converts to false + &ThisType::m_value; //it converts to true + } - bool operator !() const - { - return m_value == ClassPolicy::NullValue(); - } + bool operator !() const + { + return m_value == ClassPolicy::NullValue(); + } }; } // namespace CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/serialization.h b/src/dpl/core/include/cchecker/dpl/serialization.h index 5628350..c39ca09 100644 --- a/src/dpl/core/include/cchecker/dpl/serialization.h +++ b/src/dpl/core/include/cchecker/dpl/serialization.h @@ -32,423 +32,424 @@ namespace CCHECKER { // Abstract data stream buffer -class IStream -{ - public: - virtual void Read(size_t num, void * bytes) = 0; - virtual void Write(size_t num, const void * bytes) = 0; - virtual ~IStream(){} +class IStream { +public: + virtual void Read(size_t num, void *bytes) = 0; + virtual void Write(size_t num, const void *bytes) = 0; + virtual ~IStream() {} }; // Serializable interface -class ISerializable -{ - public: - /* ISerializable(){}; - * ISerializable(IStream&){}; */ - virtual void Serialize(IStream &) const = 0; - virtual ~ISerializable(){} +class ISerializable { +public: + /* ISerializable(){}; + * ISerializable(IStream&){}; */ + virtual void Serialize(IStream &) const = 0; + virtual ~ISerializable() {} }; struct Serialization { - // serialization - // normal functions - - // ISerializable objects - static void Serialize(IStream& stream, const ISerializable& object) - { - object.Serialize(stream); - } - - static void Serialize(IStream& stream, const ISerializable* const object) - { - object->Serialize(stream); - } - - // char - static void Serialize(IStream& stream, const char value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const char* const value) - { - stream.Write(sizeof(*value), value); - } - - // unsigned char - static void Serialize(IStream& stream, const unsigned char value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const unsigned char* const value) - { - stream.Write(sizeof(*value), value); - } - - // unsigned int32 - static void Serialize(IStream& stream, const uint32_t value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const uint32_t* const value) - { - stream.Write(sizeof(*value), value); - } - - // int32 - static void Serialize(IStream& stream, const int32_t value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const int32_t* const value) - { - stream.Write(sizeof(*value), value); - } - - // unsigned int64 - static void Serialize(IStream& stream, const uint64_t value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const uint64_t* const value) - { - stream.Write(sizeof(*value), value); - } - - // int64 - static void Serialize(IStream& stream, const int64_t value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const int64_t* const value) - { - stream.Write(sizeof(*value), value); - } - - // bool - static void Serialize(IStream& stream, const bool value) - { - stream.Write(sizeof(value), &value); - } - static void Serialize(IStream& stream, const bool* const value) - { - stream.Write(sizeof(*value), value); - } - - // std::string - template <typename T, typename R, typename A> - static void Serialize(IStream& stream, const std::basic_string<T,R,A>& str) - { - int length = str.size(); - stream.Write(sizeof(length), &length); - stream.Write(length*sizeof(T), str.data()); - } - - template<typename T, typename R, typename A> - static void Serialize(IStream& stream, const std::basic_string<T,R,A>* const str) - { - int length = str->size(); - stream.Write(sizeof(length), &length); - stream.Write(length*sizeof(T), str->data()); - } - - // STL templates - - // std::list - template <typename T> - static void Serialize(IStream& stream, const std::list<T>& list) - { - int length = list.size(); - stream.Write(sizeof(length), &length); - for (typename std::list<T>::const_iterator list_iter = list.begin(); - list_iter != list.end(); list_iter++) - { - Serialize(stream, *list_iter); - } - } - template <typename T> - static void Serialize(IStream& stream, const std::list<T>* const list) - { - Serialize(stream, *list); - } - - // RawBuffer - template <typename A> - static void Serialize(IStream& stream, const std::vector<unsigned char, A>& vec) - { - int length = vec.size(); - stream.Write(sizeof(length), &length); - stream.Write(length, vec.data()); - } - - template <typename A> - static void Serialize(IStream& stream, const std::vector<unsigned char, A>* const vec) - { - Serialize(stream, *vec); - } - - // std::vector - template <typename T, typename A> - static void Serialize(IStream& stream, const std::vector<T, A>& vec) - { - int length = vec.size(); - stream.Write(sizeof(length), &length); - for (const auto &i : vec) - { - Serialize(stream, i); - } - } - template <typename T, typename A> - static void Serialize(IStream& stream, const std::vector<T, A>* const vec) - { - Serialize(stream, *vec); - } - - // std::pair - template <typename A, typename B> - static void Serialize(IStream& stream, const std::pair<A, B>& p) - { - Serialize(stream, p.first); - Serialize(stream, p.second); - } - template <typename A, typename B> - static void Serialize(IStream& stream, const std::pair<A, B>* const p) - { - Serialize(stream, *p); - } - - // std::map - template <typename K, typename T> - static void Serialize(IStream& stream, const std::map<K, T>& map) - { - int length = map.size(); - stream.Write(sizeof(length), &length); - typename std::map<K, T>::const_iterator it; - for (it = map.begin(); it != map.end(); ++it) { - Serialize(stream, (*it).first); - Serialize(stream, (*it).second); - } - } - template <typename K, typename T> - static void Serialize(IStream& stream, const std::map<K, T>* const map) - { - Serialize(stream, *map); - } - - // std::unique_ptr - template <typename T> - static void Serialize(IStream& stream, const std::unique_ptr<T>& p) - { - Serialize(stream, *p); - } - + // serialization + // normal functions + + // ISerializable objects + static void Serialize(IStream &stream, const ISerializable &object) + { + object.Serialize(stream); + } + + static void Serialize(IStream &stream, const ISerializable *const object) + { + object->Serialize(stream); + } + + // char + static void Serialize(IStream &stream, const char value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const char *const value) + { + stream.Write(sizeof(*value), value); + } + + // unsigned char + static void Serialize(IStream &stream, const unsigned char value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const unsigned char *const value) + { + stream.Write(sizeof(*value), value); + } + + // unsigned int32 + static void Serialize(IStream &stream, const uint32_t value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const uint32_t *const value) + { + stream.Write(sizeof(*value), value); + } + + // int32 + static void Serialize(IStream &stream, const int32_t value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const int32_t *const value) + { + stream.Write(sizeof(*value), value); + } + + // unsigned int64 + static void Serialize(IStream &stream, const uint64_t value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const uint64_t *const value) + { + stream.Write(sizeof(*value), value); + } + + // int64 + static void Serialize(IStream &stream, const int64_t value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const int64_t *const value) + { + stream.Write(sizeof(*value), value); + } + + // bool + static void Serialize(IStream &stream, const bool value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream &stream, const bool *const value) + { + stream.Write(sizeof(*value), value); + } + + // std::string + template <typename T, typename R, typename A> + static void Serialize(IStream &stream, const std::basic_string<T, R, A> &str) + { + int length = str.size(); + stream.Write(sizeof(length), &length); + stream.Write(length * sizeof(T), str.data()); + } + + template<typename T, typename R, typename A> + static void Serialize(IStream &stream, const std::basic_string<T, R, A> *const str) + { + int length = str->size(); + stream.Write(sizeof(length), &length); + stream.Write(length * sizeof(T), str->data()); + } + + // STL templates + + // std::list + template <typename T> + static void Serialize(IStream &stream, const std::list<T> &list) + { + int length = list.size(); + stream.Write(sizeof(length), &length); + + for (typename std::list<T>::const_iterator list_iter = list.begin(); + list_iter != list.end(); list_iter++) { + Serialize(stream, *list_iter); + } + } + template <typename T> + static void Serialize(IStream &stream, const std::list<T> *const list) + { + Serialize(stream, *list); + } + + // RawBuffer + template <typename A> + static void Serialize(IStream &stream, const std::vector<unsigned char, A> &vec) + { + int length = vec.size(); + stream.Write(sizeof(length), &length); + stream.Write(length, vec.data()); + } + + template <typename A> + static void Serialize(IStream &stream, const std::vector<unsigned char, A> *const vec) + { + Serialize(stream, *vec); + } + + // std::vector + template <typename T, typename A> + static void Serialize(IStream &stream, const std::vector<T, A> &vec) + { + int length = vec.size(); + stream.Write(sizeof(length), &length); + + for (const auto &i : vec) { + Serialize(stream, i); + } + } + template <typename T, typename A> + static void Serialize(IStream &stream, const std::vector<T, A> *const vec) + { + Serialize(stream, *vec); + } + + // std::pair + template <typename A, typename B> + static void Serialize(IStream &stream, const std::pair<A, B> &p) + { + Serialize(stream, p.first); + Serialize(stream, p.second); + } + template <typename A, typename B> + static void Serialize(IStream &stream, const std::pair<A, B> *const p) + { + Serialize(stream, *p); + } + + // std::map + template <typename K, typename T> + static void Serialize(IStream &stream, const std::map<K, T> &map) + { + int length = map.size(); + stream.Write(sizeof(length), &length); + typename std::map<K, T>::const_iterator it; + + for (it = map.begin(); it != map.end(); ++it) { + Serialize(stream, (*it).first); + Serialize(stream, (*it).second); + } + } + template <typename K, typename T> + static void Serialize(IStream &stream, const std::map<K, T> *const map) + { + Serialize(stream, *map); + } + + // std::unique_ptr + template <typename T> + static void Serialize(IStream &stream, const std::unique_ptr<T> &p) + { + Serialize(stream, *p); + } }; // struct Serialization struct Deserialization { - // deserialization - // normal functions - - // ISerializable objects - // T instead of ISerializable is needed to call proper constructor - template <typename T> - static void Deserialize(IStream& stream, T& object) - { - object = T(stream); - } - template <typename T> - static void Deserialize(IStream& stream, T*& object) - { - object = new T(stream); - } - - // char - static void Deserialize(IStream& stream, char& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, char*& value) - { - value = new char; - stream.Read(sizeof(*value), value); - } - - // unsigned char - static void Deserialize(IStream& stream, unsigned char& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, unsigned char*& value) - { - value = new unsigned char; - stream.Read(sizeof(*value), value); - } - - // unsigned int32 - static void Deserialize(IStream& stream, uint32_t& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, uint32_t*& value) - { - value = new uint32_t; - stream.Read(sizeof(*value), value); - } - - // int32 - static void Deserialize(IStream& stream, int32_t& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, int32_t*& value) - { - value = new int32_t; - stream.Read(sizeof(*value), value); - } - - // unsigned int64 - static void Deserialize(IStream& stream, uint64_t& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, uint64_t*& value) - { - value = new uint64_t; - stream.Read(sizeof(*value), value); - } - - // int64 - static void Deserialize(IStream& stream, int64_t& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, int64_t*& value) - { - value = new int64_t; - stream.Read(sizeof(*value), value); - } - - // bool - static void Deserialize(IStream& stream, bool& value) - { - stream.Read(sizeof(value), &value); - } - static void Deserialize(IStream& stream, bool*& value) - { - value = new bool; - stream.Read(sizeof(*value), value); - } - - template <typename T, typename R, typename A> - static void Deserialize(IStream& stream, std::basic_string<T,R,A>& str) - { - int length; - stream.Read(sizeof(length), &length); - std::vector<T> buf(length); - stream.Read(length*sizeof(T), buf.data()); - str = std::basic_string<T,R,A>(buf.data(), buf.data()+length); - } - - template <typename T, typename R, typename A> - static void Deserialize(IStream& stream, std::basic_string<T,R,A>*& str) - { - int length; - stream.Read(sizeof(length), &length); - std::vector<T> buf(length); - stream.Read(length*sizeof(T), buf.data()); - str = new std::basic_string<T,R,A>(buf.data(), buf.data()+length); - } - - // STL templates - - // std::list - template <typename T> - static void Deserialize(IStream& stream, std::list<T>& list) - { - int length; - stream.Read(sizeof(length), &length); - for (int i = 0; i < length; ++i) { - T obj; - Deserialize(stream, obj); - list.push_back(std::move(obj)); - } - } - template <typename T> - static void Deserialize(IStream& stream, std::list<T>*& list) - { - list = new std::list<T>; - Deserialize(stream, *list); - } - - // RawBuffer - template <typename A> - static void Deserialize(IStream& stream, std::vector<unsigned char, A>& vec) - { - int length; - stream.Read(sizeof(length), &length); - vec.resize(length); - stream.Read(length, vec.data()); - } - - template <typename A> - static void Deserialize(IStream& stream, std::vector<unsigned char, A>*& vec) - { - vec = new std::vector<unsigned char,A>; - Deserialize(stream, *vec); - } - - // std::vector - template <typename T, typename A> - static void Deserialize(IStream& stream, std::vector<T,A>& vec) - { - int length; - stream.Read(sizeof(length), &length); - for (int i = 0; i < length; ++i) { - T obj; - Deserialize(stream, obj); - vec.push_back(std::move(obj)); - } - } - template <typename T, typename A> - static void Deserialize(IStream& stream, std::vector<T,A>*& vec) - { - vec = new std::vector<T,A>; - Deserialize(stream, *vec); - } - - // std::pair - template <typename A, typename B> - static void Deserialize(IStream& stream, std::pair<A, B>& p) - { - Deserialize(stream, p.first); - Deserialize(stream, p.second); - } - template <typename A, typename B> - static void Deserialize(IStream& stream, std::pair<A, B>*& p) - { - p = new std::pair<A, B>; - Deserialize(stream, *p); - } - - // std::map - template <typename K, typename T> - static void Deserialize(IStream& stream, std::map<K, T>& map) - { - int length; - stream.Read(sizeof(length), &length); - for (int i = 0; i < length; ++i) { - K key; - T obj; - Deserialize(stream, key); - Deserialize(stream, obj); - map[key] = std::move(obj); - } - } - template <typename K, typename T> - static void Deserialize(IStream& stream, std::map<K, T>*& map) - { - map = new std::map<K, T>; - Deserialize(stream, *map); - } + // deserialization + // normal functions + + // ISerializable objects + // T instead of ISerializable is needed to call proper constructor + template <typename T> + static void Deserialize(IStream &stream, T &object) + { + object = T(stream); + } + template <typename T> + static void Deserialize(IStream &stream, T *&object) + { + object = new T(stream); + } + + // char + static void Deserialize(IStream &stream, char &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, char *&value) + { + value = new char; + stream.Read(sizeof(*value), value); + } + + // unsigned char + static void Deserialize(IStream &stream, unsigned char &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, unsigned char *&value) + { + value = new unsigned char; + stream.Read(sizeof(*value), value); + } + + // unsigned int32 + static void Deserialize(IStream &stream, uint32_t &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, uint32_t *&value) + { + value = new uint32_t; + stream.Read(sizeof(*value), value); + } + + // int32 + static void Deserialize(IStream &stream, int32_t &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, int32_t *&value) + { + value = new int32_t; + stream.Read(sizeof(*value), value); + } + + // unsigned int64 + static void Deserialize(IStream &stream, uint64_t &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, uint64_t *&value) + { + value = new uint64_t; + stream.Read(sizeof(*value), value); + } + + // int64 + static void Deserialize(IStream &stream, int64_t &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, int64_t *&value) + { + value = new int64_t; + stream.Read(sizeof(*value), value); + } + + // bool + static void Deserialize(IStream &stream, bool &value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream &stream, bool *&value) + { + value = new bool; + stream.Read(sizeof(*value), value); + } + + template <typename T, typename R, typename A> + static void Deserialize(IStream &stream, std::basic_string<T, R, A> &str) + { + int length; + stream.Read(sizeof(length), &length); + std::vector<T> buf(length); + stream.Read(length * sizeof(T), buf.data()); + str = std::basic_string<T, R, A>(buf.data(), buf.data() + length); + } + + template <typename T, typename R, typename A> + static void Deserialize(IStream &stream, std::basic_string<T, R, A> *&str) + { + int length; + stream.Read(sizeof(length), &length); + std::vector<T> buf(length); + stream.Read(length * sizeof(T), buf.data()); + str = new std::basic_string<T, R, A>(buf.data(), buf.data() + length); + } + + // STL templates + + // std::list + template <typename T> + static void Deserialize(IStream &stream, std::list<T> &list) + { + int length; + stream.Read(sizeof(length), &length); + + for (int i = 0; i < length; ++i) { + T obj; + Deserialize(stream, obj); + list.push_back(std::move(obj)); + } + } + template <typename T> + static void Deserialize(IStream &stream, std::list<T> *&list) + { + list = new std::list<T>; + Deserialize(stream, *list); + } + + // RawBuffer + template <typename A> + static void Deserialize(IStream &stream, std::vector<unsigned char, A> &vec) + { + int length; + stream.Read(sizeof(length), &length); + vec.resize(length); + stream.Read(length, vec.data()); + } + + template <typename A> + static void Deserialize(IStream &stream, std::vector<unsigned char, A> *&vec) + { + vec = new std::vector<unsigned char, A>; + Deserialize(stream, *vec); + } + + // std::vector + template <typename T, typename A> + static void Deserialize(IStream &stream, std::vector<T, A> &vec) + { + int length; + stream.Read(sizeof(length), &length); + + for (int i = 0; i < length; ++i) { + T obj; + Deserialize(stream, obj); + vec.push_back(std::move(obj)); + } + } + template <typename T, typename A> + static void Deserialize(IStream &stream, std::vector<T, A> *&vec) + { + vec = new std::vector<T, A>; + Deserialize(stream, *vec); + } + + // std::pair + template <typename A, typename B> + static void Deserialize(IStream &stream, std::pair<A, B> &p) + { + Deserialize(stream, p.first); + Deserialize(stream, p.second); + } + template <typename A, typename B> + static void Deserialize(IStream &stream, std::pair<A, B> *&p) + { + p = new std::pair<A, B>; + Deserialize(stream, *p); + } + + // std::map + template <typename K, typename T> + static void Deserialize(IStream &stream, std::map<K, T> &map) + { + int length; + stream.Read(sizeof(length), &length); + + for (int i = 0; i < length; ++i) { + K key; + T obj; + Deserialize(stream, key); + Deserialize(stream, obj); + map[key] = std::move(obj); + } + } + template <typename K, typename T> + static void Deserialize(IStream &stream, std::map<K, T> *&map) + { + map = new std::map<K, T>; + Deserialize(stream, *map); + } }; // struct Deserialization // generic serialization @@ -457,18 +458,20 @@ struct Serializer; template <typename First, typename... Args> struct Serializer<First, Args...> : public Serializer<Args...> { - static void Serialize(IStream& stream, const First& f, const Args&... args) { - Serialization::Serialize(stream, f); - Serializer<Args...>::Serialize(stream, args...); - } + static void Serialize(IStream &stream, const First &f, const Args &... args) + { + Serialization::Serialize(stream, f); + Serializer<Args...>::Serialize(stream, args...); + } }; // end of recursion template <> struct Serializer<> { - static void Serialize(IStream&) { - return; - } + static void Serialize(IStream &) + { + return; + } }; // generic deserialization @@ -477,18 +480,20 @@ struct Deserializer; template <typename First, typename... Args> struct Deserializer<First, Args...> : public Deserializer<Args...> { - static void Deserialize(IStream& stream, First& f, Args&... args) { - Deserialization::Deserialize(stream, f); - Deserializer<Args...>::Deserialize(stream, args...); - } + static void Deserialize(IStream &stream, First &f, Args &... args) + { + Deserialization::Deserialize(stream, f); + Deserializer<Args...>::Deserialize(stream, args...); + } }; // end of recursion template <> struct Deserializer<> { - static void Deserialize(IStream&) { - return; - } + static void Deserialize(IStream &) + { + return; + } }; } // CCHECKER diff --git a/src/dpl/core/include/cchecker/dpl/string.h b/src/dpl/core/include/cchecker/dpl/string.h index d9c3bbd..5d12e17 100644 --- a/src/dpl/core/include/cchecker/dpl/string.h +++ b/src/dpl/core/include/cchecker/dpl/string.h @@ -33,47 +33,46 @@ namespace CCHECKER { typedef std::basic_string<wchar_t, CharTraits> String; // @brief String exception class -class StringException -{ - public: - DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) +class StringException { +public: + DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) - // @brief Invalid init for UTF8 to UTF32 converter - DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF8ToUTF32) + // @brief Invalid init for UTF8 to UTF32 converter + DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF8ToUTF32) - // @brief Invalid taStdContainerinit for UTF32 to UTF32 converter - DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF32ToUTF8) + // @brief Invalid taStdContainerinit for UTF32 to UTF32 converter + DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF32ToUTF8) - // @brief Invalid conversion for UTF8 to UTF32 converter - DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF8ToUTF32) + // @brief Invalid conversion for UTF8 to UTF32 converter + DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF8ToUTF32) - // @brief Invalid conversion for UTF8 to UTF32 converter - DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF32ToUTF8) + // @brief Invalid conversion for UTF8 to UTF32 converter + DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF32ToUTF8) - // @brief Invalid ASCII character detected in FromASCII - DECLARE_EXCEPTION_TYPE(Base, InvalidASCIICharacter) + // @brief Invalid ASCII character detected in FromASCII + DECLARE_EXCEPTION_TYPE(Base, InvalidASCIICharacter) - // @brief Invalid ASCII character detected in FromASCII - DECLARE_EXCEPTION_TYPE(Base, ICUInvalidCharacterFound) + // @brief Invalid ASCII character detected in FromASCII + DECLARE_EXCEPTION_TYPE(Base, ICUInvalidCharacterFound) }; //!\brief convert ASCII string to CCHECKER::String -String FromASCIIString(const std::string& aString); +String FromASCIIString(const std::string &aString); //!\brief convert UTF32 string to CCHECKER::String -String FromUTF32String(const std::wstring& aString); +String FromUTF32String(const std::wstring &aString); //@brief Returns String object created from UTF8 string //@param[in] aString input UTF-8 string -String FromUTF8String(const std::string& aString); +String FromUTF8String(const std::string &aString); //@brief Returns String content as std::string -std::string ToUTF8String(const String& aString); +std::string ToUTF8String(const String &aString); //@brief Compare two unicode strings int StringCompare(const String &left, - const String &right, - bool caseInsensitive = false); + const String &right, + bool caseInsensitive = false); //@brief Splits the string into substrings. //@param[in] str Input string @@ -81,61 +80,63 @@ int StringCompare(const String &left, // delimiters. Can be also a single delimiter character. //@param[in] it InserterIterator that is used to save the generated substrings. template<typename StringType, typename Delimiters, typename InserterIterator> -void Tokenize(const StringType& str, - const Delimiters& delimiters, - InserterIterator it, - bool ignoreEmpty = false) +void Tokenize(const StringType &str, + const Delimiters &delimiters, + InserterIterator it, + bool ignoreEmpty = false) { - typename StringType::size_type nextSearchStart = 0; - typename StringType::size_type pos; - typename StringType::size_type length; - - while (true) { - pos = str.find_first_of(delimiters, nextSearchStart); - length = - ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart; - - if (!ignoreEmpty || length > 0) { - *it = str.substr(nextSearchStart, length); - it++; - } - - if (pos == StringType::npos) { - return; - } - - nextSearchStart = pos + 1; - } + typename StringType::size_type nextSearchStart = 0; + typename StringType::size_type pos; + typename StringType::size_type length; + + while (true) { + pos = str.find_first_of(delimiters, nextSearchStart); + length = + ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart; + + if (!ignoreEmpty || length > 0) { + *it = str.substr(nextSearchStart, length); + it++; + } + + if (pos == StringType::npos) { + return; + } + + nextSearchStart = pos + 1; + } } namespace Utils { -template<typename T> class ConcatFunc : public std::binary_function<T, T, T> -{ +template<typename T> class ConcatFunc : public std::binary_function<T, T, T> { public: - explicit ConcatFunc(const T & val) : m_delim(val) {} - T operator()(const T & arg1, const T & arg2) const - { - return arg1 + m_delim + arg2; - } + explicit ConcatFunc(const T &val) : m_delim(val) {} + T operator()(const T &arg1, const T &arg2) const + { + return arg1 + m_delim + arg2; + } private: - T m_delim; + T m_delim; }; } template<typename ForwardIterator> -typename ForwardIterator::value_type Join(ForwardIterator begin, ForwardIterator end, typename ForwardIterator::value_type delim) +typename ForwardIterator::value_type Join(ForwardIterator begin, ForwardIterator end, + typename ForwardIterator::value_type delim) { - typedef typename ForwardIterator::value_type value; - if(begin == end) return value(); - Utils::ConcatFunc<value> func(delim); - ForwardIterator init = begin; - return std::accumulate(++begin, end, *init, func); + typedef typename ForwardIterator::value_type value; + + if (begin == end) return value(); + + Utils::ConcatFunc<value> func(delim); + ForwardIterator init = begin; + return std::accumulate(++begin, end, *init, func); } } //namespace CCHECKER -std::ostream& operator<<(std::ostream& aStream, const CCHECKER::String& aString); +std::ostream &operator<<(std::ostream &aStream, const CCHECKER::String &aString); #endif // CCHECKER_STRING diff --git a/src/dpl/core/src/assert.cpp b/src/dpl/core/src/assert.cpp index e367562..acaa958 100644 --- a/src/dpl/core/src/assert.cpp +++ b/src/dpl/core/src/assert.cpp @@ -28,41 +28,39 @@ namespace CCHECKER { void AssertProc(const char *condition, - const char *file, - int line, - const char *function) + const char *file, + int line, + const char *function) { #define INTERNAL_LOG(message) \ - do \ - { \ - std::ostringstream platformLog; \ - platformLog << message; \ - JournalLog(LOG_DEBUG, \ - platformLog.str().c_str(), \ - __FILE__, __LINE__, __FUNCTION__); \ - } \ - while (0) + do \ + { \ + std::ostringstream platformLog; \ + platformLog << message; \ + JournalLog(LOG_DEBUG, \ + platformLog.str().c_str(), \ + __FILE__, __LINE__, __FUNCTION__); \ + } \ + while (0) + // Try to log failed assertion to log system + Try { + INTERNAL_LOG( + "################################################################################"); + INTERNAL_LOG( + "### cert-checker assertion failed! ###"); + INTERNAL_LOG( + "################################################################################"); + INTERNAL_LOG("### Condition: " << condition); + INTERNAL_LOG("### File: " << file); + INTERNAL_LOG("### Line: " << line); + INTERNAL_LOG("### Function: " << function); + INTERNAL_LOG( + "################################################################################"); + } catch (Exception) { + // Just ignore possible double errors + } - // Try to log failed assertion to log system - Try - { - INTERNAL_LOG( - "################################################################################"); - INTERNAL_LOG( - "### cert-checker assertion failed! ###"); - INTERNAL_LOG( - "################################################################################"); - INTERNAL_LOG("### Condition: " << condition); - INTERNAL_LOG("### File: " << file); - INTERNAL_LOG("### Line: " << line); - INTERNAL_LOG("### Function: " << function); - INTERNAL_LOG( - "################################################################################"); - } catch (Exception) { - // Just ignore possible double errors - } - - // Fail with c-library abort - abort(); + // Fail with c-library abort + abort(); } } // namespace CCHECKER diff --git a/src/dpl/core/src/colors.cpp b/src/dpl/core/src/colors.cpp index 272c06b..1f380b9 100644 --- a/src/dpl/core/src/colors.cpp +++ b/src/dpl/core/src/colors.cpp @@ -27,46 +27,46 @@ namespace CCHECKER { namespace Colors { namespace Text { -const char* BOLD_GREEN_BEGIN = "\033[1;32m"; -const char* BOLD_GREEN_END = "\033[m"; -const char* RED_BEGIN = "\033[0;31m"; -const char* RED_END = "\033[m"; -const char* PURPLE_BEGIN = "\033[0;35m"; -const char* PURPLE_END = "\033[m"; -const char* GREEN_BEGIN = "\033[0;32m"; -const char* GREEN_END = "\033[m"; -const char* CYAN_BEGIN = "\033[0;36m"; -const char* CYAN_END = "\033[m"; -const char* BOLD_RED_BEGIN = "\033[1;31m"; -const char* BOLD_RED_END = "\033[m"; -const char* BOLD_YELLOW_BEGIN = "\033[1;33m"; -const char* BOLD_YELLOW_END = "\033[m"; -const char* BOLD_GOLD_BEGIN = "\033[0;33m"; -const char* BOLD_GOLD_END = "\033[m"; -const char* BOLD_WHITE_BEGIN = "\033[1;37m"; -const char* BOLD_WHITE_END = "\033[m"; -const char* COLOR_END = "\033[m"; +const char *BOLD_GREEN_BEGIN = "\033[1;32m"; +const char *BOLD_GREEN_END = "\033[m"; +const char *RED_BEGIN = "\033[0;31m"; +const char *RED_END = "\033[m"; +const char *PURPLE_BEGIN = "\033[0;35m"; +const char *PURPLE_END = "\033[m"; +const char *GREEN_BEGIN = "\033[0;32m"; +const char *GREEN_END = "\033[m"; +const char *CYAN_BEGIN = "\033[0;36m"; +const char *CYAN_END = "\033[m"; +const char *BOLD_RED_BEGIN = "\033[1;31m"; +const char *BOLD_RED_END = "\033[m"; +const char *BOLD_YELLOW_BEGIN = "\033[1;33m"; +const char *BOLD_YELLOW_END = "\033[m"; +const char *BOLD_GOLD_BEGIN = "\033[0;33m"; +const char *BOLD_GOLD_END = "\033[m"; +const char *BOLD_WHITE_BEGIN = "\033[1;37m"; +const char *BOLD_WHITE_END = "\033[m"; +const char *COLOR_END = "\033[m"; } //namespace Text namespace Html { -const char* BOLD_GREEN_BEGIN = "<font color=\"green\"><b>"; -const char* BOLD_GREEN_END = "</b></font>"; -const char* PURPLE_BEGIN = "<font color=\"purple\"><b>"; -const char* PURPLE_END = "</b></font>"; -const char* RED_BEGIN = "<font color=\"red\"><b>"; -const char* RED_END = "</b></font>"; -const char* GREEN_BEGIN = "<font color=\"green\">"; -const char* GREEN_END = "</font>"; -const char* CYAN_BEGIN = "<font color=\"cyan\">"; -const char* CYAN_END = "</font>"; -const char* BOLD_RED_BEGIN = "<font color=\"red\"><b>"; -const char* BOLD_RED_END = "</b></font>"; -const char* BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>"; -const char* BOLD_YELLOW_END = "</b></font>"; -const char* BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>"; -const char* BOLD_GOLD_END = "</b></font>"; -const char* BOLD_WHITE_BEGIN = "<font color=\"white\"><b>"; -const char* BOLD_WHITE_END = "</b></font>"; +const char *BOLD_GREEN_BEGIN = "<font color=\"green\"><b>"; +const char *BOLD_GREEN_END = "</b></font>"; +const char *PURPLE_BEGIN = "<font color=\"purple\"><b>"; +const char *PURPLE_END = "</b></font>"; +const char *RED_BEGIN = "<font color=\"red\"><b>"; +const char *RED_END = "</b></font>"; +const char *GREEN_BEGIN = "<font color=\"green\">"; +const char *GREEN_END = "</font>"; +const char *CYAN_BEGIN = "<font color=\"cyan\">"; +const char *CYAN_END = "</font>"; +const char *BOLD_RED_BEGIN = "<font color=\"red\"><b>"; +const char *BOLD_RED_END = "</b></font>"; +const char *BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>"; +const char *BOLD_YELLOW_END = "</b></font>"; +const char *BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>"; +const char *BOLD_GOLD_END = "</b></font>"; +const char *BOLD_WHITE_BEGIN = "<font color=\"white\"><b>"; +const char *BOLD_WHITE_END = "</b></font>"; } //namespace Html } //namespace Colors } //namespace CCHECKER diff --git a/src/dpl/core/src/errno_string.cpp b/src/dpl/core/src/errno_string.cpp index 5b1de37..fa04a45 100644 --- a/src/dpl/core/src/errno_string.cpp +++ b/src/dpl/core/src/errno_string.cpp @@ -34,66 +34,65 @@ #include <cchecker/dpl/scoped_free.h> namespace CCHECKER { -namespace // anonymous -{ +namespace { // anonymous const size_t DEFAULT_ERRNO_STRING_SIZE = 32; } // namespace anonymous std::string GetErrnoString(int error) { - size_t size = DEFAULT_ERRNO_STRING_SIZE; - char *buffer = NULL; - - for (;;) { - // Add one extra characted for end of string null value - char *newBuffer = static_cast<char *>(::realloc(buffer, size + 1)); + size_t size = DEFAULT_ERRNO_STRING_SIZE; + char *buffer = NULL; - if (!newBuffer) { - // Failed to realloc - ::free(buffer); - throw std::bad_alloc(); - } + for (;;) { + // Add one extra characted for end of string null value + char *newBuffer = static_cast<char *>(::realloc(buffer, size + 1)); - // Setup reallocated buffer - buffer = newBuffer; - ::memset(buffer, 0, size + 1); + if (!newBuffer) { + // Failed to realloc + ::free(buffer); + throw std::bad_alloc(); + } - // Try to retrieve error string + // Setup reallocated buffer + buffer = newBuffer; + ::memset(buffer, 0, size + 1); + // Try to retrieve error string #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE - // The XSI-compliant version of strerror_r() is provided if: - int result = ::strerror_r(error, buffer, size); + // The XSI-compliant version of strerror_r() is provided if: + int result = ::strerror_r(error, buffer, size); + + if (result == 0) { + ScopedFree<char> scopedBufferFree(buffer); + return std::string(buffer); + } - if (result == 0) { - ScopedFree<char> scopedBufferFree(buffer); - return std::string(buffer); - } #else - errno = 0; + errno = 0; + // Otherwise, the GNU-specific version is provided. + char *result = ::strerror_r(error, buffer, size); - // Otherwise, the GNU-specific version is provided. - char *result = ::strerror_r(error, buffer, size); + if (result != NULL) { + ScopedFree<char> scopedBufferFree(buffer); + return std::string(result); + } - if (result != NULL) { - ScopedFree<char> scopedBufferFree(buffer); - return std::string(result); - } #endif - // Interpret errors - switch (errno) { - case EINVAL: - // We got an invalid errno value - ::free(buffer); - ThrowMsg(InvalidErrnoValue, "Invalid errno value: " << error); + // Interpret errors + switch (errno) { + case EINVAL: + // We got an invalid errno value + ::free(buffer); + ThrowMsg(InvalidErrnoValue, "Invalid errno value: " << error); - case ERANGE: - // Incease buffer size and retry - size <<= 1; - continue; + case ERANGE: + // Incease buffer size and retry + size <<= 1; + continue; - default: - Assert(0 && "Invalid errno value after call to strerror_r!"); - } - } + default: + Assert(0 && "Invalid errno value after call to strerror_r!"); + } + } } } // namespace CCHECKER diff --git a/src/dpl/core/src/exception.cpp b/src/dpl/core/src/exception.cpp index bee161b..66024fc 100644 --- a/src/dpl/core/src/exception.cpp +++ b/src/dpl/core/src/exception.cpp @@ -26,32 +26,30 @@ #include "common/log.h" namespace CCHECKER { -Exception* Exception::m_lastException = NULL; +Exception *Exception::m_lastException = NULL; unsigned int Exception::m_exceptionCount = 0; void (*Exception::m_terminateHandler)() = NULL; void LogUnhandledException(const std::string &str) { - // Logging to console - printf("%s\n", str.c_str()); - - // Logging to dlog - LogDebug(str); + // Logging to console + printf("%s\n", str.c_str()); + // Logging to dlog + LogDebug(str); } void LogUnhandledException(const std::string &str, - const char *filename, - int line, - const char *function) + const char *filename, + int line, + const char *function) { - // Logging to console - std::ostringstream msg; - msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " << - function << " ===\033[m"; - msg << str; - printf("%s\n", msg.str().c_str()); - - // Logging to dlog - LogError(str.c_str() << filename << line << function); + // Logging to console + std::ostringstream msg; + msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " << + function << " ===\033[m"; + msg << str; + printf("%s\n", msg.str().c_str()); + // Logging to dlog + LogError(str.c_str() << filename << line << function); } } // namespace CCHECKER diff --git a/src/dpl/core/src/string.cpp b/src/dpl/core/src/string.cpp index 7c8223d..72ade02 100644 --- a/src/dpl/core/src/string.cpp +++ b/src/dpl/core/src/string.cpp @@ -37,215 +37,197 @@ // TODO: Completely move to ICU namespace CCHECKER { -namespace //anonymous -{ -class ASCIIValidator -{ - const std::string& m_TestedString; +namespace { //anonymous +class ASCIIValidator { + const std::string &m_TestedString; - public: - ASCIIValidator(const std::string& aTestedString); +public: + ASCIIValidator(const std::string &aTestedString); - void operator()(signed char aCharacter) const; + void operator()(signed char aCharacter) const; }; -ASCIIValidator::ASCIIValidator(const std::string& aTestedString) : - m_TestedString(aTestedString) +ASCIIValidator::ASCIIValidator(const std::string &aTestedString) : + m_TestedString(aTestedString) {} void ASCIIValidator::operator()(signed char aCharacter) const { - // Check for ASCII data range - if (aCharacter <= 0) { - ThrowMsg( - StringException::InvalidASCIICharacter, - "invalid character code " << static_cast<int>(aCharacter) - << " from string [" << - m_TestedString - << "] passed as ASCII"); - } + // Check for ASCII data range + if (aCharacter <= 0) { + ThrowMsg( + StringException::InvalidASCIICharacter, + "invalid character code " << static_cast<int>(aCharacter) + << " from string [" << + m_TestedString + << "] passed as ASCII"); + } } const iconv_t gc_IconvOperError = reinterpret_cast<iconv_t>(-1); const size_t gc_IconvConvertError = static_cast<size_t>(-1); } // namespace anonymous -String FromUTF8String(const std::string& aIn) +String FromUTF8String(const std::string &aIn) { - if (aIn.empty()) { - return String(); - } - - size_t inbytes = aIn.size(); - - // Default iconv UTF-32 module adds BOM (4 bytes) in from of string - // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32 - // newsize = oldsize * 4 + end + bom - // newsize - bytes for UTF-32 string - // oldsize - letters in UTF-8 string - // end - end character for UTF-32 (\0) - // bom - Unicode header in front of string (0xfeff) - size_t outbytes = sizeof(wchar_t) * (inbytes + 2); - std::vector<wchar_t> output(inbytes + 2, 0); - - size_t outbytesleft = outbytes; - char* inbuf = const_cast<char*>(aIn.c_str()); - - // vector is used to provide buffer for iconv which expects char* buffer - // but during conversion from UTF32 uses internaly wchar_t - char* outbuf = reinterpret_cast<char*>(&output[0]); - - iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8"); - - if (gc_IconvOperError == iconvHandle) { - int error = errno; - - ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32, - "iconv_open failed for " << "UTF-32 <- UTF-8" << - "error: " << GetErrnoString(error)); - } - - size_t iconvRet = iconv(iconvHandle, - &inbuf, - &inbytes, - &outbuf, - &outbytesleft); - - iconv_close(iconvHandle); - - if (gc_IconvConvertError == iconvRet) { - ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32, - "iconv failed for " << "UTF-32 <- UTF-8" << "error: " - << GetErrnoString()); - } - - // Ignore BOM in front of UTF-32 - return &output[1]; + if (aIn.empty()) { + return String(); + } + + size_t inbytes = aIn.size(); + // Default iconv UTF-32 module adds BOM (4 bytes) in from of string + // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32 + // newsize = oldsize * 4 + end + bom + // newsize - bytes for UTF-32 string + // oldsize - letters in UTF-8 string + // end - end character for UTF-32 (\0) + // bom - Unicode header in front of string (0xfeff) + size_t outbytes = sizeof(wchar_t) * (inbytes + 2); + std::vector<wchar_t> output(inbytes + 2, 0); + size_t outbytesleft = outbytes; + char *inbuf = const_cast<char *>(aIn.c_str()); + // vector is used to provide buffer for iconv which expects char* buffer + // but during conversion from UTF32 uses internaly wchar_t + char *outbuf = reinterpret_cast<char *>(&output[0]); + iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8"); + + if (gc_IconvOperError == iconvHandle) { + int error = errno; + ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32, + "iconv_open failed for " << "UTF-32 <- UTF-8" << + "error: " << GetErrnoString(error)); + } + + size_t iconvRet = iconv(iconvHandle, + &inbuf, + &inbytes, + &outbuf, + &outbytesleft); + iconv_close(iconvHandle); + + if (gc_IconvConvertError == iconvRet) { + ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32, + "iconv failed for " << "UTF-32 <- UTF-8" << "error: " + << GetErrnoString()); + } + + // Ignore BOM in front of UTF-32 + return &output[1]; } -std::string ToUTF8String(const CCHECKER::String& aIn) +std::string ToUTF8String(const CCHECKER::String &aIn) { - if (aIn.empty()) { - return std::string(); - } - - size_t inbytes = aIn.size() * sizeof(wchar_t); - size_t outbytes = inbytes + sizeof(char); - - // wstring returns wchar_t but iconv expects char* - // iconv internally is processing input as wchar_t - char* inbuf = reinterpret_cast<char*>(const_cast<wchar_t*>(aIn.c_str())); - std::vector<char> output(inbytes, 0); - char* outbuf = &output[0]; - - size_t outbytesleft = outbytes; - - iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32"); - - if (gc_IconvOperError == iconvHandle) { - ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8, - "iconv_open failed for " << "UTF-8 <- UTF-32" - << "error: " << GetErrnoString()); - } - - size_t iconvRet = iconv(iconvHandle, - &inbuf, - &inbytes, - &outbuf, - &outbytesleft); - - iconv_close(iconvHandle); - - if (gc_IconvConvertError == iconvRet) { - ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8, - "iconv failed for " << "UTF-8 <- UTF-32" - << "error: " << GetErrnoString()); - } - - return &output[0]; + if (aIn.empty()) { + return std::string(); + } + + size_t inbytes = aIn.size() * sizeof(wchar_t); + size_t outbytes = inbytes + sizeof(char); + // wstring returns wchar_t but iconv expects char* + // iconv internally is processing input as wchar_t + char *inbuf = reinterpret_cast<char *>(const_cast<wchar_t *>(aIn.c_str())); + std::vector<char> output(inbytes, 0); + char *outbuf = &output[0]; + size_t outbytesleft = outbytes; + iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32"); + + if (gc_IconvOperError == iconvHandle) { + ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8, + "iconv_open failed for " << "UTF-8 <- UTF-32" + << "error: " << GetErrnoString()); + } + + size_t iconvRet = iconv(iconvHandle, + &inbuf, + &inbytes, + &outbuf, + &outbytesleft); + iconv_close(iconvHandle); + + if (gc_IconvConvertError == iconvRet) { + ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8, + "iconv failed for " << "UTF-8 <- UTF-32" + << "error: " << GetErrnoString()); + } + + return &output[0]; } -String FromASCIIString(const std::string& aString) +String FromASCIIString(const std::string &aString) { - String output; - - std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString)); - std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output)); - - return output; + String output; + std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString)); + std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output)); + return output; } -String FromUTF32String(const std::wstring& aString) +String FromUTF32String(const std::wstring &aString) { - return String(&aString[0]); + return String(&aString[0]); } static UChar *ConvertToICU(const String &inputString) { - ScopedArray<UChar> outputString; - int32_t size = 0; - int32_t convertedSize = 0; - UErrorCode error = U_ZERO_ERROR; - - // Calculate size of output string - ::u_strFromWCS(NULL, - 0, - &size, - inputString.c_str(), - -1, - &error); - - if (error == U_ZERO_ERROR || - error == U_BUFFER_OVERFLOW_ERROR) - { - // What buffer size is ok ? - LogDebug("ICU: Output buffer size: " << size); - } else { - ThrowMsg(StringException::ICUInvalidCharacterFound, - "ICU: Failed to retrieve output string size. Error: " - << error); - } - - // Allocate proper buffer - outputString.Reset(new UChar[size + 1]); - ::memset(outputString.Get(), 0, sizeof(UChar) * (size + 1)); - - error = U_ZERO_ERROR; - - // Do conversion - ::u_strFromWCS(outputString.Get(), - size + 1, - &convertedSize, - inputString.c_str(), - -1, - &error); - - if (!U_SUCCESS(error)) { - ThrowMsg(StringException::ICUInvalidCharacterFound, - "ICU: Failed to convert string. Error: " << error); - } - - // Done - return outputString.Release(); + ScopedArray<UChar> outputString; + int32_t size = 0; + int32_t convertedSize = 0; + UErrorCode error = U_ZERO_ERROR; + // Calculate size of output string + ::u_strFromWCS(NULL, + 0, + &size, + inputString.c_str(), + -1, + &error); + + if (error == U_ZERO_ERROR || + error == U_BUFFER_OVERFLOW_ERROR) { + // What buffer size is ok ? + LogDebug("ICU: Output buffer size: " << size); + } else { + ThrowMsg(StringException::ICUInvalidCharacterFound, + "ICU: Failed to retrieve output string size. Error: " + << error); + } + + // Allocate proper buffer + outputString.Reset(new UChar[size + 1]); + ::memset(outputString.Get(), 0, sizeof(UChar) * (size + 1)); + error = U_ZERO_ERROR; + // Do conversion + ::u_strFromWCS(outputString.Get(), + size + 1, + &convertedSize, + inputString.c_str(), + -1, + &error); + + if (!U_SUCCESS(error)) { + ThrowMsg(StringException::ICUInvalidCharacterFound, + "ICU: Failed to convert string. Error: " << error); + } + + // Done + return outputString.Release(); } int StringCompare(const String &left, - const String &right, - bool caseInsensitive) + const String &right, + bool caseInsensitive) { - // Convert input strings - ScopedArray<UChar> leftICU(ConvertToICU(left)); - ScopedArray<UChar> rightICU(ConvertToICU(right)); - - if (caseInsensitive) { - return static_cast<int>(u_strcasecmp(leftICU.Get(), rightICU.Get(), 0)); - } else { - return static_cast<int>(u_strcmp(leftICU.Get(), rightICU.Get())); - } + // Convert input strings + ScopedArray<UChar> leftICU(ConvertToICU(left)); + ScopedArray<UChar> rightICU(ConvertToICU(right)); + + if (caseInsensitive) { + return static_cast<int>(u_strcasecmp(leftICU.Get(), rightICU.Get(), 0)); + } else { + return static_cast<int>(u_strcmp(leftICU.Get(), rightICU.Get())); + } } } //namespace CCHECKER -std::ostream& operator<<(std::ostream& aStream, const CCHECKER::String& aString) +std::ostream &operator<<(std::ostream &aStream, const CCHECKER::String &aString) { - return aStream << CCHECKER::ToUTF8String(aString); + return aStream << CCHECKER::ToUTF8String(aString); } diff --git a/src/dpl/db/include/cchecker/dpl/db/naive_synchronization_object.h b/src/dpl/db/include/cchecker/dpl/db/naive_synchronization_object.h index 8836635..393dc52 100644 --- a/src/dpl/db/include/cchecker/dpl/db/naive_synchronization_object.h +++ b/src/dpl/db/include/cchecker/dpl/db/naive_synchronization_object.h @@ -32,12 +32,11 @@ namespace DB { * to the same database across different threads and processes */ class NaiveSynchronizationObject : - public SqlConnection::SynchronizationObject -{ - public: - // [SqlConnection::SynchronizationObject] - virtual void Synchronize(); - virtual void NotifyAll(); + public SqlConnection::SynchronizationObject { +public: + // [SqlConnection::SynchronizationObject] + virtual void Synchronize(); + virtual void NotifyAll(); }; } // namespace DB } // namespace CCHECKER diff --git a/src/dpl/db/include/cchecker/dpl/db/sql_connection.h b/src/dpl/db/include/cchecker/dpl/db/sql_connection.h index d3612ce..dd27a1a 100644 --- a/src/dpl/db/include/cchecker/dpl/db/sql_connection.h +++ b/src/dpl/db/include/cchecker/dpl/db/sql_connection.h @@ -40,458 +40,451 @@ namespace DB { /** * SQL connection class */ -class SqlConnection -{ - public: - /** - * SQL Exception classes - */ - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, SyntaxError) - DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken) - DECLARE_EXCEPTION_TYPE(Base, InternalError) - DECLARE_EXCEPTION_TYPE(Base, InvalidColumn) - }; - - typedef int ColumnIndex; - typedef int ArgumentIndex; - - /* - * SQL processed data command - */ - class DataCommand : - private Noncopyable - { - private: - SqlConnection *m_masterConnection; - sqlite3_stmt *m_stmt; - - void CheckBindResult(int result); - void CheckColumnIndex(SqlConnection::ColumnIndex column); - - DataCommand(SqlConnection *connection, const char *buffer); - - friend class SqlConnection; - - public: - virtual ~DataCommand(); - - /** - * Bind null to the prepared statement argument - * - * @param position Index of argument to bind value to - */ - void BindNull(ArgumentIndex position); - - /** - * Bind int to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInteger(ArgumentIndex position, int value); - - /** - * Bind int8_t to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt8(ArgumentIndex position, int8_t value); - - /** - * Bind int16 to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt16(ArgumentIndex position, int16_t value); - - /** - * Bind int32 to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt32(ArgumentIndex position, int32_t value); - - /** - * Bind int64 to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt64(ArgumentIndex position, int64_t value); - - /** - * Bind float to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindFloat(ArgumentIndex position, float value); - - /** - * Bind double to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindDouble(ArgumentIndex position, double value); - - /** - * Bind string to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindString(ArgumentIndex position, const char *value); - - /** - * Bind string to the prepared statement argument - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindString(ArgumentIndex position, const String& value); - - /** - * Bind optional int to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInteger(ArgumentIndex position, const Optional<int> &value); - - /** - * Bind optional int8 to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt8(ArgumentIndex position, const Optional<int8_t> &value); - - /** - * Bind optional int16 to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt16(ArgumentIndex position, const Optional<int16_t> &value); - - /** - * Bind optional int32 to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt32(ArgumentIndex position, const Optional<int32_t> &value); - - /** - * Bind optional int64 to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindInt64(ArgumentIndex position, const Optional<int64_t> &value); - - /** - * Bind optional float to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindFloat(ArgumentIndex position, const Optional<float> &value); - - /** - * Bind optional double to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindDouble(ArgumentIndex position, const Optional<double> &value); - - /** - * Bind optional string to the prepared statement argument. - * If optional is not set null will be bound - * - * @param position Index of argument to bind value to - * @param value Value to bind - */ - void BindString(ArgumentIndex position, const Optional<String> &value); - - /** - * Execute the prepared statement and/or move - * to the next row of the result - * - * @return True when there was a row returned - */ - bool Step(); - - /** - * Reset prepared statement's arguments - * All parameters will become null - */ - void Reset(); - - /** - * Checks whether column value is null - * - * @throw Exception::InvalidColumn - */ - bool IsColumnNull(ColumnIndex column); - - /** - * Get integer value from column in current row. - * - * @throw Exception::InvalidColumn - */ - int GetColumnInteger(ColumnIndex column); - - /** - * Get int8 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - int8_t GetColumnInt8(ColumnIndex column); - - /** - * Get int16 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - int16_t GetColumnInt16(ColumnIndex column); - /** - * Get int32 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - int32_t GetColumnInt32(ColumnIndex column); - - /** - * Get int64 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - int64_t GetColumnInt64(ColumnIndex column); - - /** - * Get float value from column in current row. - * - * @throw Exception::InvalidColumn - */ - float GetColumnFloat(ColumnIndex column); - - /** - * Get double value from column in current row. - * - * @throw Exception::InvalidColumn - */ - double GetColumnDouble(ColumnIndex column); - - /** - * Get string value from column in current row. - * - * @throw Exception::InvalidColumn - */ - std::string GetColumnString(ColumnIndex column); - - /** - * Get optional integer value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<int> GetColumnOptionalInteger(ColumnIndex column); - - /** - * Get optional int8 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<int8_t> GetColumnOptionalInt8(ColumnIndex column); - - /** - * Get optional int16value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<int16_t> GetColumnOptionalInt16(ColumnIndex column); - - /** - * Get optional int32 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<int32_t> GetColumnOptionalInt32(ColumnIndex column); - - /** - * Get optional int64 value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<int64_t> GetColumnOptionalInt64(ColumnIndex column); - - /** - * Get optional float value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<float> GetColumnOptionalFloat(ColumnIndex column); - - /** - * Get optional double value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<double> GetColumnOptionalDouble(ColumnIndex column); - - /** - * Get optional string value from column in current row. - * - * @throw Exception::InvalidColumn - */ - Optional<String> GetColumnOptionalString(ColumnIndex column); - }; - - // Move on copy semantics - typedef std::auto_ptr<DataCommand> DataCommandAutoPtr; - - // Open flags - class Flag - { - public: - enum Type - { - None = 1 << 0, - UseLucene = 1 << 1 - }; - - enum Option - { - RO = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READONLY, - /** - * *TODO: please remove CREATE option from RW flag when all places - * that need that switched do CRW - */ - RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | - SQLITE_OPEN_CREATE, - CRW = RW | SQLITE_OPEN_CREATE - }; - }; - - // RowID - typedef sqlite3_int64 RowID; - - /** - * Synchronization object used to synchronize SQL connection - * to the same database across different threads and processes - */ - class SynchronizationObject - { - public: - virtual ~SynchronizationObject() {} - - /** - * Synchronizes SQL connection for multiple clients. - */ - virtual void Synchronize() = 0; - - /** - * Notify all waiting clients that the connection is no longer locked. - */ - virtual void NotifyAll() = 0; - }; - - protected: - sqlite3 *m_connection; - - // Options - bool m_usingLucene; - - // Stored data procedures - int m_dataCommandsCount; - - // Synchronization object - std::unique_ptr<SynchronizationObject> m_synchronizationObject; - - virtual void Connect(const std::string &address, - Flag::Type = Flag::None, Flag::Option = Flag::RO); - virtual void Disconnect(); - - void TurnOnForeignKeys(); - - static SynchronizationObject *AllocDefaultSynchronizationObject(); - - public: - /** - * Open SQL connection - * - * Synchronization is archieved by using provided asynchronization object. - * If synchronizationObject is set to NULL, so synchronization is performed. - * Ownership of the synchronization object is transfered to sql connection - * object. - * - * @param address Database file name - * @param flags Open flags - * @param synchronizationObject A synchronization object to use. - */ - explicit SqlConnection(const std::string &address = std::string(), - Flag::Type flags = Flag::None, - Flag::Option options = Flag::RO, - SynchronizationObject *synchronizationObject = - AllocDefaultSynchronizationObject()); - - /** - * Destructor - */ - virtual ~SqlConnection(); - - /** - * Execute SQL command without result - * - * @param format - * @param ... - */ - void ExecCommand(const char *format, ...); - - /** - * Prepare stored procedure - * - * @param format SQL statement - * @return Data command representing stored procedure - */ - DataCommandAutoPtr PrepareDataCommand(const char *format, ...); - - /** - * Check whether given table exists - * - * @param tableName Name of the table to check - * @return True if given table name exists - */ - bool CheckTableExist(const char *tableName); - - /** - * Get last insert operation new row id - * - * @return Row ID - */ - RowID GetLastInsertRowID() const; - - void BeginTransaction(); - - void RollbackTransaction(); - - void CommitTransaction(); +class SqlConnection { +public: + /** + * SQL Exception classes + */ + class Exception { + public: + DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, SyntaxError) + DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken) + DECLARE_EXCEPTION_TYPE(Base, InternalError) + DECLARE_EXCEPTION_TYPE(Base, InvalidColumn) + }; + + typedef int ColumnIndex; + typedef int ArgumentIndex; + + /* + * SQL processed data command + */ + class DataCommand : + private Noncopyable { + private: + SqlConnection *m_masterConnection; + sqlite3_stmt *m_stmt; + + void CheckBindResult(int result); + void CheckColumnIndex(SqlConnection::ColumnIndex column); + + DataCommand(SqlConnection *connection, const char *buffer); + + friend class SqlConnection; + + public: + virtual ~DataCommand(); + + /** + * Bind null to the prepared statement argument + * + * @param position Index of argument to bind value to + */ + void BindNull(ArgumentIndex position); + + /** + * Bind int to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInteger(ArgumentIndex position, int value); + + /** + * Bind int8_t to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt8(ArgumentIndex position, int8_t value); + + /** + * Bind int16 to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt16(ArgumentIndex position, int16_t value); + + /** + * Bind int32 to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt32(ArgumentIndex position, int32_t value); + + /** + * Bind int64 to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt64(ArgumentIndex position, int64_t value); + + /** + * Bind float to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindFloat(ArgumentIndex position, float value); + + /** + * Bind double to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindDouble(ArgumentIndex position, double value); + + /** + * Bind string to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindString(ArgumentIndex position, const char *value); + + /** + * Bind string to the prepared statement argument + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindString(ArgumentIndex position, const String &value); + + /** + * Bind optional int to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInteger(ArgumentIndex position, const Optional<int> &value); + + /** + * Bind optional int8 to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt8(ArgumentIndex position, const Optional<int8_t> &value); + + /** + * Bind optional int16 to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt16(ArgumentIndex position, const Optional<int16_t> &value); + + /** + * Bind optional int32 to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt32(ArgumentIndex position, const Optional<int32_t> &value); + + /** + * Bind optional int64 to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindInt64(ArgumentIndex position, const Optional<int64_t> &value); + + /** + * Bind optional float to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindFloat(ArgumentIndex position, const Optional<float> &value); + + /** + * Bind optional double to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindDouble(ArgumentIndex position, const Optional<double> &value); + + /** + * Bind optional string to the prepared statement argument. + * If optional is not set null will be bound + * + * @param position Index of argument to bind value to + * @param value Value to bind + */ + void BindString(ArgumentIndex position, const Optional<String> &value); + + /** + * Execute the prepared statement and/or move + * to the next row of the result + * + * @return True when there was a row returned + */ + bool Step(); + + /** + * Reset prepared statement's arguments + * All parameters will become null + */ + void Reset(); + + /** + * Checks whether column value is null + * + * @throw Exception::InvalidColumn + */ + bool IsColumnNull(ColumnIndex column); + + /** + * Get integer value from column in current row. + * + * @throw Exception::InvalidColumn + */ + int GetColumnInteger(ColumnIndex column); + + /** + * Get int8 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + int8_t GetColumnInt8(ColumnIndex column); + + /** + * Get int16 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + int16_t GetColumnInt16(ColumnIndex column); + /** + * Get int32 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + int32_t GetColumnInt32(ColumnIndex column); + + /** + * Get int64 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + int64_t GetColumnInt64(ColumnIndex column); + + /** + * Get float value from column in current row. + * + * @throw Exception::InvalidColumn + */ + float GetColumnFloat(ColumnIndex column); + + /** + * Get double value from column in current row. + * + * @throw Exception::InvalidColumn + */ + double GetColumnDouble(ColumnIndex column); + + /** + * Get string value from column in current row. + * + * @throw Exception::InvalidColumn + */ + std::string GetColumnString(ColumnIndex column); + + /** + * Get optional integer value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<int> GetColumnOptionalInteger(ColumnIndex column); + + /** + * Get optional int8 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<int8_t> GetColumnOptionalInt8(ColumnIndex column); + + /** + * Get optional int16value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<int16_t> GetColumnOptionalInt16(ColumnIndex column); + + /** + * Get optional int32 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<int32_t> GetColumnOptionalInt32(ColumnIndex column); + + /** + * Get optional int64 value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<int64_t> GetColumnOptionalInt64(ColumnIndex column); + + /** + * Get optional float value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<float> GetColumnOptionalFloat(ColumnIndex column); + + /** + * Get optional double value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<double> GetColumnOptionalDouble(ColumnIndex column); + + /** + * Get optional string value from column in current row. + * + * @throw Exception::InvalidColumn + */ + Optional<String> GetColumnOptionalString(ColumnIndex column); + }; + + // Move on copy semantics + typedef std::auto_ptr<DataCommand> DataCommandAutoPtr; + + // Open flags + class Flag { + public: + enum Type { + None = 1 << 0, + UseLucene = 1 << 1 + }; + + enum Option { + RO = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READONLY, + /** + * *TODO: please remove CREATE option from RW flag when all places + * that need that switched do CRW + */ + RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE, + CRW = RW | SQLITE_OPEN_CREATE + }; + }; + + // RowID + typedef sqlite3_int64 RowID; + + /** + * Synchronization object used to synchronize SQL connection + * to the same database across different threads and processes + */ + class SynchronizationObject { + public: + virtual ~SynchronizationObject() {} + + /** + * Synchronizes SQL connection for multiple clients. + */ + virtual void Synchronize() = 0; + + /** + * Notify all waiting clients that the connection is no longer locked. + */ + virtual void NotifyAll() = 0; + }; + +protected: + sqlite3 *m_connection; + + // Options + bool m_usingLucene; + + // Stored data procedures + int m_dataCommandsCount; + + // Synchronization object + std::unique_ptr<SynchronizationObject> m_synchronizationObject; + + virtual void Connect(const std::string &address, + Flag::Type = Flag::None, Flag::Option = Flag::RO); + virtual void Disconnect(); + + void TurnOnForeignKeys(); + + static SynchronizationObject *AllocDefaultSynchronizationObject(); + +public: + /** + * Open SQL connection + * + * Synchronization is archieved by using provided asynchronization object. + * If synchronizationObject is set to NULL, so synchronization is performed. + * Ownership of the synchronization object is transfered to sql connection + * object. + * + * @param address Database file name + * @param flags Open flags + * @param synchronizationObject A synchronization object to use. + */ + explicit SqlConnection(const std::string &address = std::string(), + Flag::Type flags = Flag::None, + Flag::Option options = Flag::RO, + SynchronizationObject *synchronizationObject = + AllocDefaultSynchronizationObject()); + + /** + * Destructor + */ + virtual ~SqlConnection(); + + /** + * Execute SQL command without result + * + * @param format + * @param ... + */ + void ExecCommand(const char *format, ...); + + /** + * Prepare stored procedure + * + * @param format SQL statement + * @return Data command representing stored procedure + */ + DataCommandAutoPtr PrepareDataCommand(const char *format, ...); + + /** + * Check whether given table exists + * + * @param tableName Name of the table to check + * @return True if given table name exists + */ + bool CheckTableExist(const char *tableName); + + /** + * Get last insert operation new row id + * + * @return Row ID + */ + RowID GetLastInsertRowID() const; + + void BeginTransaction(); + + void RollbackTransaction(); + + void CommitTransaction(); }; } // namespace DB } // namespace CCHECKER diff --git a/src/dpl/db/src/naive_synchronization_object.cpp b/src/dpl/db/src/naive_synchronization_object.cpp index 18eeefb..2a66db2 100644 --- a/src/dpl/db/src/naive_synchronization_object.cpp +++ b/src/dpl/db/src/naive_synchronization_object.cpp @@ -27,20 +27,20 @@ #include <cchecker/dpl/db/naive_synchronization_object.h> namespace { - unsigned int seed = time(NULL); +unsigned int seed = time(NULL); } namespace CCHECKER { namespace DB { void NaiveSynchronizationObject::Synchronize() { - // Sleep for about 10ms - 30ms - std::this_thread::sleep_for(std::chrono::milliseconds(10 + rand_r(&seed) % 20)); + // Sleep for about 10ms - 30ms + std::this_thread::sleep_for(std::chrono::milliseconds(10 + rand_r(&seed) % 20)); } void NaiveSynchronizationObject::NotifyAll() { - // No need to inform about anything + // No need to inform about anything } } // namespace DB } // namespace CCHECKER diff --git a/src/dpl/db/src/sql_connection.cpp b/src/dpl/db/src/sql_connection.cpp index 4bee5de..3cd274e 100644 --- a/src/dpl/db/src/sql_connection.cpp +++ b/src/dpl/db/src/sql_connection.cpp @@ -35,834 +35,817 @@ namespace CCHECKER { namespace DB { -namespace // anonymous -{ +namespace { // anonymous class ScopedNotifyAll : - public Noncopyable -{ - private: - SqlConnection::SynchronizationObject *m_synchronizationObject; - - public: - explicit ScopedNotifyAll( - SqlConnection::SynchronizationObject *synchronizationObject) : - m_synchronizationObject(synchronizationObject) - {} - - ~ScopedNotifyAll() - { - if (!m_synchronizationObject) { - return; - } - - LogDebug("Notifying after successful synchronize"); - m_synchronizationObject->NotifyAll(); - } + public Noncopyable { +private: + SqlConnection::SynchronizationObject *m_synchronizationObject; + +public: + explicit ScopedNotifyAll( + SqlConnection::SynchronizationObject *synchronizationObject) : + m_synchronizationObject(synchronizationObject) + {} + + ~ScopedNotifyAll() + { + if (!m_synchronizationObject) { + return; + } + + LogDebug("Notifying after successful synchronize"); + m_synchronizationObject->NotifyAll(); + } }; } // namespace anonymous SqlConnection::DataCommand::DataCommand(SqlConnection *connection, - const char *buffer) : - m_masterConnection(connection), - m_stmt(NULL) -{ - Assert(connection != NULL); - - // Notify all after potentially synchronized database connection access - ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get()); - - for (;;) { - int ret = sqlite3_prepare_v2(connection->m_connection, - buffer, strlen(buffer), - &m_stmt, NULL); - - if (ret == SQLITE_OK) { - LogDebug("Data command prepared successfuly"); - break; - } else if (ret == SQLITE_BUSY) { - LogDebug("Collision occurred while preparing SQL command"); - - // Synchronize if synchronization object is available - if (connection->m_synchronizationObject) { - LogDebug("Performing synchronization"); - connection->m_synchronizationObject->Synchronize(); - continue; - } - - // No synchronization object defined. Fail. - } - - // Fatal error - const char *error = sqlite3_errmsg(m_masterConnection->m_connection); - - LogDebug("SQL prepare data command failed"); - LogDebug(" Statement: " << buffer); - LogDebug(" Error: " << error); - - ThrowMsg(Exception::SyntaxError, error); - } - - LogDebug("Prepared data command: " << buffer); - - // Increment stored data command count - ++m_masterConnection->m_dataCommandsCount; + const char *buffer) : + m_masterConnection(connection), + m_stmt(NULL) +{ + Assert(connection != NULL); + // Notify all after potentially synchronized database connection access + ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get()); + + for (;;) { + int ret = sqlite3_prepare_v2(connection->m_connection, + buffer, strlen(buffer), + &m_stmt, NULL); + + if (ret == SQLITE_OK) { + LogDebug("Data command prepared successfuly"); + break; + } else if (ret == SQLITE_BUSY) { + LogDebug("Collision occurred while preparing SQL command"); + + // Synchronize if synchronization object is available + if (connection->m_synchronizationObject) { + LogDebug("Performing synchronization"); + connection->m_synchronizationObject->Synchronize(); + continue; + } + + // No synchronization object defined. Fail. + } + + // Fatal error + const char *error = sqlite3_errmsg(m_masterConnection->m_connection); + LogDebug("SQL prepare data command failed"); + LogDebug(" Statement: " << buffer); + LogDebug(" Error: " << error); + ThrowMsg(Exception::SyntaxError, error); + } + + LogDebug("Prepared data command: " << buffer); + // Increment stored data command count + ++m_masterConnection->m_dataCommandsCount; } SqlConnection::DataCommand::~DataCommand() { - LogDebug("SQL data command finalizing"); + LogDebug("SQL data command finalizing"); - if (sqlite3_finalize(m_stmt) != SQLITE_OK) { - LogDebug("Failed to finalize data command"); - } + if (sqlite3_finalize(m_stmt) != SQLITE_OK) { + LogDebug("Failed to finalize data command"); + } - // Decrement stored data command count - --m_masterConnection->m_dataCommandsCount; + // Decrement stored data command count + --m_masterConnection->m_dataCommandsCount; } void SqlConnection::DataCommand::CheckBindResult(int result) { - if (result != SQLITE_OK) { - const char *error = sqlite3_errmsg( - m_masterConnection->m_connection); - - LogDebug("Failed to bind SQL statement parameter"); - LogDebug(" Error: " << error); - - ThrowMsg(Exception::SyntaxError, error); - } + if (result != SQLITE_OK) { + const char *error = sqlite3_errmsg( + m_masterConnection->m_connection); + LogDebug("Failed to bind SQL statement parameter"); + LogDebug(" Error: " << error); + ThrowMsg(Exception::SyntaxError, error); + } } void SqlConnection::DataCommand::BindNull( - SqlConnection::ArgumentIndex position) + SqlConnection::ArgumentIndex position) { - CheckBindResult(sqlite3_bind_null(m_stmt, position)); - LogDebug("SQL data command bind null: [" - << position << "]"); + CheckBindResult(sqlite3_bind_null(m_stmt, position)); + LogDebug("SQL data command bind null: [" + << position << "]"); } void SqlConnection::DataCommand::BindInteger( - SqlConnection::ArgumentIndex position, - int value) + SqlConnection::ArgumentIndex position, + int value) { - CheckBindResult(sqlite3_bind_int(m_stmt, position, value)); - LogDebug("SQL data command bind integer: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_int(m_stmt, position, value)); + LogDebug("SQL data command bind integer: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindInt8( - SqlConnection::ArgumentIndex position, - int8_t value) + SqlConnection::ArgumentIndex position, + int8_t value) { - CheckBindResult(sqlite3_bind_int(m_stmt, position, - static_cast<int>(value))); - LogDebug("SQL data command bind int8: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_int(m_stmt, position, + static_cast<int>(value))); + LogDebug("SQL data command bind int8: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindInt16( - SqlConnection::ArgumentIndex position, - int16_t value) + SqlConnection::ArgumentIndex position, + int16_t value) { - CheckBindResult(sqlite3_bind_int(m_stmt, position, - static_cast<int>(value))); - LogDebug("SQL data command bind int16: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_int(m_stmt, position, + static_cast<int>(value))); + LogDebug("SQL data command bind int16: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindInt32( - SqlConnection::ArgumentIndex position, - int32_t value) + SqlConnection::ArgumentIndex position, + int32_t value) { - CheckBindResult(sqlite3_bind_int(m_stmt, position, - static_cast<int>(value))); - LogDebug("SQL data command bind int32: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_int(m_stmt, position, + static_cast<int>(value))); + LogDebug("SQL data command bind int32: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindInt64( - SqlConnection::ArgumentIndex position, - int64_t value) + SqlConnection::ArgumentIndex position, + int64_t value) { - CheckBindResult(sqlite3_bind_int64(m_stmt, position, - static_cast<sqlite3_int64>(value))); - LogDebug("SQL data command bind int64: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_int64(m_stmt, position, + static_cast<sqlite3_int64>(value))); + LogDebug("SQL data command bind int64: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindFloat( - SqlConnection::ArgumentIndex position, - float value) + SqlConnection::ArgumentIndex position, + float value) { - CheckBindResult(sqlite3_bind_double(m_stmt, position, - static_cast<double>(value))); - LogDebug("SQL data command bind float: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_double(m_stmt, position, + static_cast<double>(value))); + LogDebug("SQL data command bind float: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindDouble( - SqlConnection::ArgumentIndex position, - double value) + SqlConnection::ArgumentIndex position, + double value) { - CheckBindResult(sqlite3_bind_double(m_stmt, position, value)); - LogDebug("SQL data command bind double: [" - << position << "] -> " << value); + CheckBindResult(sqlite3_bind_double(m_stmt, position, value)); + LogDebug("SQL data command bind double: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindString( - SqlConnection::ArgumentIndex position, - const char *value) + SqlConnection::ArgumentIndex position, + const char *value) { - if (!value) { - BindNull(position); - return; - } + if (!value) { + BindNull(position); + return; + } - // Assume that text may disappear - CheckBindResult(sqlite3_bind_text(m_stmt, position, - value, strlen(value), - SQLITE_TRANSIENT)); - - LogDebug("SQL data command bind string: [" - << position << "] -> " << value); + // Assume that text may disappear + CheckBindResult(sqlite3_bind_text(m_stmt, position, + value, strlen(value), + SQLITE_TRANSIENT)); + LogDebug("SQL data command bind string: [" + << position << "] -> " << value); } void SqlConnection::DataCommand::BindString( - SqlConnection::ArgumentIndex position, - const String &value) + SqlConnection::ArgumentIndex position, + const String &value) { - BindString(position, ToUTF8String(value).c_str()); + BindString(position, ToUTF8String(value).c_str()); } void SqlConnection::DataCommand::BindInteger( - SqlConnection::ArgumentIndex position, - const Optional<int> &value) + SqlConnection::ArgumentIndex position, + const Optional<int> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindInteger(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindInteger(position, *value); + } } void SqlConnection::DataCommand::BindInt8( - SqlConnection::ArgumentIndex position, - const Optional<int8_t> &value) + SqlConnection::ArgumentIndex position, + const Optional<int8_t> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindInt8(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindInt8(position, *value); + } } void SqlConnection::DataCommand::BindInt16( - SqlConnection::ArgumentIndex position, - const Optional<int16_t> &value) + SqlConnection::ArgumentIndex position, + const Optional<int16_t> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindInt16(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindInt16(position, *value); + } } void SqlConnection::DataCommand::BindInt32( - SqlConnection::ArgumentIndex position, - const Optional<int32_t> &value) + SqlConnection::ArgumentIndex position, + const Optional<int32_t> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindInt32(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindInt32(position, *value); + } } void SqlConnection::DataCommand::BindInt64( - SqlConnection::ArgumentIndex position, - const Optional<int64_t> &value) + SqlConnection::ArgumentIndex position, + const Optional<int64_t> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindInt64(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindInt64(position, *value); + } } void SqlConnection::DataCommand::BindFloat( - SqlConnection::ArgumentIndex position, - const Optional<float> &value) + SqlConnection::ArgumentIndex position, + const Optional<float> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindFloat(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindFloat(position, *value); + } } void SqlConnection::DataCommand::BindDouble( - SqlConnection::ArgumentIndex position, - const Optional<double> &value) + SqlConnection::ArgumentIndex position, + const Optional<double> &value) { - if (value.IsNull()) { - BindNull(position); - } else { - BindDouble(position, *value); - } + if (value.IsNull()) { + BindNull(position); + } else { + BindDouble(position, *value); + } } void SqlConnection::DataCommand::BindString( - SqlConnection::ArgumentIndex position, - const Optional<String> &value) + SqlConnection::ArgumentIndex position, + const Optional<String> &value) { - if (!!value) { - BindString(position, ToUTF8String(*value).c_str()); - } else { - BindNull(position); - } + if (!!value) { + BindString(position, ToUTF8String(*value).c_str()); + } else { + BindNull(position); + } } bool SqlConnection::DataCommand::Step() { - // Notify all after potentially synchronized database connection access - ScopedNotifyAll notifyAll( - m_masterConnection->m_synchronizationObject.get()); - - for (;;) { - int ret = sqlite3_step(m_stmt); - - if (ret == SQLITE_ROW) { - LogDebug("SQL data command step ROW"); - return true; - } else if (ret == SQLITE_DONE) { - LogDebug("SQL data command step DONE"); - return false; - } else if (ret == SQLITE_BUSY) { - LogDebug("Collision occurred while executing SQL command"); - - // Synchronize if synchronization object is available - if (m_masterConnection->m_synchronizationObject) { - LogDebug("Performing synchronization"); - - m_masterConnection-> - m_synchronizationObject->Synchronize(); - - continue; - } - - // No synchronization object defined. Fail. - } - - // Fatal error - const char *error = sqlite3_errmsg(m_masterConnection->m_connection); - - LogDebug("SQL step data command failed"); - LogDebug(" Error: " << error); - - ThrowMsg(Exception::InternalError, error); - } + // Notify all after potentially synchronized database connection access + ScopedNotifyAll notifyAll( + m_masterConnection->m_synchronizationObject.get()); + + for (;;) { + int ret = sqlite3_step(m_stmt); + + if (ret == SQLITE_ROW) { + LogDebug("SQL data command step ROW"); + return true; + } else if (ret == SQLITE_DONE) { + LogDebug("SQL data command step DONE"); + return false; + } else if (ret == SQLITE_BUSY) { + LogDebug("Collision occurred while executing SQL command"); + + // Synchronize if synchronization object is available + if (m_masterConnection->m_synchronizationObject) { + LogDebug("Performing synchronization"); + m_masterConnection-> + m_synchronizationObject->Synchronize(); + continue; + } + + // No synchronization object defined. Fail. + } + + // Fatal error + const char *error = sqlite3_errmsg(m_masterConnection->m_connection); + LogDebug("SQL step data command failed"); + LogDebug(" Error: " << error); + ThrowMsg(Exception::InternalError, error); + } } void SqlConnection::DataCommand::Reset() { - /* - * According to: - * http://www.sqlite.org/c3ref/stmt.html - * - * if last sqlite3_step command on this stmt returned an error, - * then sqlite3_reset will return that error, althought it is not an error. - * So sqlite3_reset allways succedes. - */ - sqlite3_reset(m_stmt); - - LogDebug("SQL data command reset"); + /* + * According to: + * http://www.sqlite.org/c3ref/stmt.html + * + * if last sqlite3_step command on this stmt returned an error, + * then sqlite3_reset will return that error, althought it is not an error. + * So sqlite3_reset allways succedes. + */ + sqlite3_reset(m_stmt); + LogDebug("SQL data command reset"); } void SqlConnection::DataCommand::CheckColumnIndex( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - if (column < 0 || column >= sqlite3_column_count(m_stmt)) { - ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds"); - } + if (column < 0 || column >= sqlite3_column_count(m_stmt)) { + ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds"); + } } bool SqlConnection::DataCommand::IsColumnNull( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column type: [" << column << "]"); - CheckColumnIndex(column); - return sqlite3_column_type(m_stmt, column) == SQLITE_NULL; + LogDebug("SQL data command get column type: [" << column << "]"); + CheckColumnIndex(column); + return sqlite3_column_type(m_stmt, column) == SQLITE_NULL; } int SqlConnection::DataCommand::GetColumnInteger( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column integer: [" << column << "]"); - CheckColumnIndex(column); - int value = sqlite3_column_int(m_stmt, column); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column integer: [" << column << "]"); + CheckColumnIndex(column); + int value = sqlite3_column_int(m_stmt, column); + LogDebug(" Value: " << value); + return value; } int8_t SqlConnection::DataCommand::GetColumnInt8( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column int8: [" << column << "]"); - CheckColumnIndex(column); - int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column int8: [" << column << "]"); + CheckColumnIndex(column); + int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return value; } int16_t SqlConnection::DataCommand::GetColumnInt16( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column int16: [" << column << "]"); - CheckColumnIndex(column); - int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column int16: [" << column << "]"); + CheckColumnIndex(column); + int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return value; } int32_t SqlConnection::DataCommand::GetColumnInt32( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column int32: [" << column << "]"); - CheckColumnIndex(column); - int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column int32: [" << column << "]"); + CheckColumnIndex(column); + int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return value; } int64_t SqlConnection::DataCommand::GetColumnInt64( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column int64: [" << column << "]"); - CheckColumnIndex(column); - int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column)); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column int64: [" << column << "]"); + CheckColumnIndex(column); + int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column)); + LogDebug(" Value: " << value); + return value; } float SqlConnection::DataCommand::GetColumnFloat( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column float: [" << column << "]"); - CheckColumnIndex(column); - float value = static_cast<float>(sqlite3_column_double(m_stmt, column)); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column float: [" << column << "]"); + CheckColumnIndex(column); + float value = static_cast<float>(sqlite3_column_double(m_stmt, column)); + LogDebug(" Value: " << value); + return value; } double SqlConnection::DataCommand::GetColumnDouble( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column double: [" << column << "]"); - CheckColumnIndex(column); - double value = sqlite3_column_double(m_stmt, column); - LogDebug(" Value: " << value); - return value; + LogDebug("SQL data command get column double: [" << column << "]"); + CheckColumnIndex(column); + double value = sqlite3_column_double(m_stmt, column); + LogDebug(" Value: " << value); + return value; } std::string SqlConnection::DataCommand::GetColumnString( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column string: [" << column << "]"); - CheckColumnIndex(column); - - const char *value = reinterpret_cast<const char *>( - sqlite3_column_text(m_stmt, column)); - - LogDebug("Value: " << (value ? value : "NULL")); + LogDebug("SQL data command get column string: [" << column << "]"); + CheckColumnIndex(column); + const char *value = reinterpret_cast<const char *>( + sqlite3_column_text(m_stmt, column)); + LogDebug("Value: " << (value ? value : "NULL")); - if (value == NULL) { - return std::string(); - } + if (value == NULL) { + return std::string(); + } - return std::string(value); + return std::string(value); } Optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional integer: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<int>::Null; - } - int value = sqlite3_column_int(m_stmt, column); - LogDebug(" Value: " << value); - return Optional<int>(value); + LogDebug("SQL data command get column optional integer: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<int>::Null; + } + + int value = sqlite3_column_int(m_stmt, column); + LogDebug(" Value: " << value); + return Optional<int>(value); } Optional<int8_t> SqlConnection::DataCommand::GetColumnOptionalInt8( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional int8: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<int8_t>::Null; - } - int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return Optional<int8_t>(value); + LogDebug("SQL data command get column optional int8: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<int8_t>::Null; + } + + int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return Optional<int8_t>(value); } Optional<int16_t> SqlConnection::DataCommand::GetColumnOptionalInt16( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional int16: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<int16_t>::Null; - } - int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return Optional<int16_t>(value); + LogDebug("SQL data command get column optional int16: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<int16_t>::Null; + } + + int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return Optional<int16_t>(value); } Optional<int32_t> SqlConnection::DataCommand::GetColumnOptionalInt32( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional int32: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<int32_t>::Null; - } - int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column)); - LogDebug(" Value: " << value); - return Optional<int32_t>(value); + LogDebug("SQL data command get column optional int32: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<int32_t>::Null; + } + + int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column)); + LogDebug(" Value: " << value); + return Optional<int32_t>(value); } Optional<int64_t> SqlConnection::DataCommand::GetColumnOptionalInt64( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional int64: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<int64_t>::Null; - } - int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column)); - LogDebug(" Value: " << value); - return Optional<int64_t>(value); + LogDebug("SQL data command get column optional int64: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<int64_t>::Null; + } + + int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column)); + LogDebug(" Value: " << value); + return Optional<int64_t>(value); } Optional<float> SqlConnection::DataCommand::GetColumnOptionalFloat( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional float: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<float>::Null; - } - float value = static_cast<float>(sqlite3_column_double(m_stmt, column)); - LogDebug(" Value: " << value); - return Optional<float>(value); + LogDebug("SQL data command get column optional float: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<float>::Null; + } + + float value = static_cast<float>(sqlite3_column_double(m_stmt, column)); + LogDebug(" Value: " << value); + return Optional<float>(value); } Optional<double> SqlConnection::DataCommand::GetColumnOptionalDouble( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional double: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<double>::Null; - } - double value = sqlite3_column_double(m_stmt, column); - LogDebug(" Value: " << value); - return Optional<double>(value); + LogDebug("SQL data command get column optional double: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<double>::Null; + } + + double value = sqlite3_column_double(m_stmt, column); + LogDebug(" Value: " << value); + return Optional<double>(value); } Optional<String> SqlConnection::DataCommand::GetColumnOptionalString( - SqlConnection::ColumnIndex column) + SqlConnection::ColumnIndex column) { - LogDebug("SQL data command get column optional string: [" - << column << "]"); - CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { - return Optional<String>::Null; - } - const char *value = reinterpret_cast<const char *>( - sqlite3_column_text(m_stmt, column)); - LogDebug("Value: " << value); - String s = FromUTF8String(value); - return Optional<String>(s); + LogDebug("SQL data command get column optional string: [" + << column << "]"); + CheckColumnIndex(column); + + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { + return Optional<String>::Null; + } + + const char *value = reinterpret_cast<const char *>( + sqlite3_column_text(m_stmt, column)); + LogDebug("Value: " << value); + String s = FromUTF8String(value); + return Optional<String>(s); } void SqlConnection::Connect(const std::string &address, - Flag::Type type, - Flag::Option flag) -{ - if (m_connection != NULL) { - LogDebug("Already connected."); - return; - } - LogDebug("Connecting to DB: " << address << "..."); - - // Connect to database - int result; - if (type & Flag::UseLucene) { - result = db_util_open_with_options( - address.c_str(), - &m_connection, - flag, - NULL); - - m_usingLucene = true; - LogDebug("Lucene index enabled"); - } else { - result = sqlite3_open_v2( - address.c_str(), - &m_connection, - flag, - NULL); - - m_usingLucene = false; - LogDebug("Lucene index disabled"); - } - - if (result == SQLITE_OK) { - LogDebug("Connected to DB"); - } else { - LogDebug("Failed to connect to DB!"); - ThrowMsg(Exception::ConnectionBroken, address); - } - - // Enable foreign keys - TurnOnForeignKeys(); + Flag::Type type, + Flag::Option flag) +{ + if (m_connection != NULL) { + LogDebug("Already connected."); + return; + } + + LogDebug("Connecting to DB: " << address << "..."); + // Connect to database + int result; + + if (type & Flag::UseLucene) { + result = db_util_open_with_options( + address.c_str(), + &m_connection, + flag, + NULL); + m_usingLucene = true; + LogDebug("Lucene index enabled"); + } else { + result = sqlite3_open_v2( + address.c_str(), + &m_connection, + flag, + NULL); + m_usingLucene = false; + LogDebug("Lucene index disabled"); + } + + if (result == SQLITE_OK) { + LogDebug("Connected to DB"); + } else { + LogDebug("Failed to connect to DB!"); + ThrowMsg(Exception::ConnectionBroken, address); + } + + // Enable foreign keys + TurnOnForeignKeys(); } void SqlConnection::Disconnect() { - if (m_connection == NULL) { - LogDebug("Already disconnected."); - return; - } - - LogDebug("Disconnecting from DB..."); + if (m_connection == NULL) { + LogDebug("Already disconnected."); + return; + } - // All stored data commands must be deleted before disconnect - Assert(m_dataCommandsCount == 0 && - "All stored procedures must be deleted" - " before disconnecting SqlConnection"); + LogDebug("Disconnecting from DB..."); + // All stored data commands must be deleted before disconnect + Assert(m_dataCommandsCount == 0 && + "All stored procedures must be deleted" + " before disconnecting SqlConnection"); + int result; - int result; + if (m_usingLucene) { + result = db_util_close(m_connection); + } else { + result = sqlite3_close(m_connection); + } - if (m_usingLucene) { - result = db_util_close(m_connection); - } else { - result = sqlite3_close(m_connection); - } + if (result != SQLITE_OK) { + const char *error = sqlite3_errmsg(m_connection); + LogDebug("SQL close failed"); + LogDebug(" Error: " << error); + Throw(Exception::InternalError); + } - if (result != SQLITE_OK) { - const char *error = sqlite3_errmsg(m_connection); - LogDebug("SQL close failed"); - LogDebug(" Error: " << error); - Throw(Exception::InternalError); - } - - m_connection = NULL; - - LogDebug("Disconnected from DB"); + m_connection = NULL; + LogDebug("Disconnected from DB"); } bool SqlConnection::CheckTableExist(const char *tableName) { - if (m_connection == NULL) { - LogDebug("Cannot execute command. Not connected to DB!"); - return false; - } - - DataCommandAutoPtr command = - PrepareDataCommand("select tbl_name from sqlite_master where name=?;"); + if (m_connection == NULL) { + LogDebug("Cannot execute command. Not connected to DB!"); + return false; + } - command->BindString(1, tableName); + DataCommandAutoPtr command = + PrepareDataCommand("select tbl_name from sqlite_master where name=?;"); + command->BindString(1, tableName); - if (!command->Step()) { - LogDebug("No matching records in table"); - return false; - } + if (!command->Step()) { + LogDebug("No matching records in table"); + return false; + } - return command->GetColumnString(0) == tableName; + return command->GetColumnString(0) == tableName; } SqlConnection::SqlConnection(const std::string &address, - Flag::Type flag, - Flag::Option option, - SynchronizationObject *synchronizationObject) : - m_connection(NULL), - m_usingLucene(false), - m_dataCommandsCount(0), - m_synchronizationObject(synchronizationObject) + Flag::Type flag, + Flag::Option option, + SynchronizationObject *synchronizationObject) : + m_connection(NULL), + m_usingLucene(false), + m_dataCommandsCount(0), + m_synchronizationObject(synchronizationObject) { - LogDebug("Opening database connection to: " << address); + LogDebug("Opening database connection to: " << address); + // Connect to DB + SqlConnection::Connect(address, flag, option); - // Connect to DB - SqlConnection::Connect(address, flag, option); - - if (!m_synchronizationObject) { - LogDebug("No synchronization object defined"); - } + if (!m_synchronizationObject) { + LogDebug("No synchronization object defined"); + } } SqlConnection::~SqlConnection() { - LogDebug("Closing database connection"); - - // Disconnect from DB - Try - { - SqlConnection::Disconnect(); - } - Catch(Exception::Base) - { - LogDebug("Failed to disconnect from database"); - } + LogDebug("Closing database connection"); + // Disconnect from DB + Try { + SqlConnection::Disconnect(); + } + Catch(Exception::Base) { + LogDebug("Failed to disconnect from database"); + } } void SqlConnection::ExecCommand(const char *format, ...) { - if (m_connection == NULL) { - LogDebug("Cannot execute command. Not connected to DB!"); - return; - } - - if (format == NULL) { - LogDebug("Null query!"); - ThrowMsg(Exception::SyntaxError, "Null statement"); - } - - char *rawBuffer; - - va_list args; - va_start(args, format); - - if (vasprintf(&rawBuffer, format, args) == -1) { - rawBuffer = NULL; - } - - va_end(args); - - ScopedFree<char> buffer(rawBuffer); - - if (!buffer) { - LogDebug("Failed to allocate statement string"); - return; - } - - LogDebug("Executing SQL command: " << buffer.Get()); - - // Notify all after potentially synchronized database connection access - ScopedNotifyAll notifyAll(m_synchronizationObject.get()); - - for (;;) { - char *errorBuffer; - - int ret = sqlite3_exec(m_connection, - buffer.Get(), - NULL, - NULL, - &errorBuffer); - - std::string errorMsg; - - // Take allocated error buffer - if (errorBuffer != NULL) { - errorMsg = errorBuffer; - sqlite3_free(errorBuffer); - } - - if (ret == SQLITE_OK) { - return; - } - - if (ret == SQLITE_BUSY) { - LogDebug("Collision occurred while executing SQL command"); - - // Synchronize if synchronization object is available - if (m_synchronizationObject) { - LogDebug("Performing synchronization"); - m_synchronizationObject->Synchronize(); - continue; - } - - // No synchronization object defined. Fail. - } - - // Fatal error - LogDebug("Failed to execute SQL command. Error: " << errorMsg); - ThrowMsg(Exception::SyntaxError, errorMsg); - } + if (m_connection == NULL) { + LogDebug("Cannot execute command. Not connected to DB!"); + return; + } + + if (format == NULL) { + LogDebug("Null query!"); + ThrowMsg(Exception::SyntaxError, "Null statement"); + } + + char *rawBuffer; + va_list args; + va_start(args, format); + + if (vasprintf(&rawBuffer, format, args) == -1) { + rawBuffer = NULL; + } + + va_end(args); + ScopedFree<char> buffer(rawBuffer); + + if (!buffer) { + LogDebug("Failed to allocate statement string"); + return; + } + + LogDebug("Executing SQL command: " << buffer.Get()); + // Notify all after potentially synchronized database connection access + ScopedNotifyAll notifyAll(m_synchronizationObject.get()); + + for (;;) { + char *errorBuffer; + int ret = sqlite3_exec(m_connection, + buffer.Get(), + NULL, + NULL, + &errorBuffer); + std::string errorMsg; + + // Take allocated error buffer + if (errorBuffer != NULL) { + errorMsg = errorBuffer; + sqlite3_free(errorBuffer); + } + + if (ret == SQLITE_OK) { + return; + } + + if (ret == SQLITE_BUSY) { + LogDebug("Collision occurred while executing SQL command"); + + // Synchronize if synchronization object is available + if (m_synchronizationObject) { + LogDebug("Performing synchronization"); + m_synchronizationObject->Synchronize(); + continue; + } + + // No synchronization object defined. Fail. + } + + // Fatal error + LogDebug("Failed to execute SQL command. Error: " << errorMsg); + ThrowMsg(Exception::SyntaxError, errorMsg); + } } SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand( - const char *format, - ...) + const char *format, + ...) { - if (m_connection == NULL) { - LogDebug("Cannot execute data command. Not connected to DB!"); - return DataCommandAutoPtr(); - } - - char *rawBuffer; - - va_list args; - va_start(args, format); - - if (vasprintf(&rawBuffer, format, args) == -1) { - rawBuffer = NULL; - } + if (m_connection == NULL) { + LogDebug("Cannot execute data command. Not connected to DB!"); + return DataCommandAutoPtr(); + } - va_end(args); + char *rawBuffer; + va_list args; + va_start(args, format); - ScopedFree<char> buffer(rawBuffer); + if (vasprintf(&rawBuffer, format, args) == -1) { + rawBuffer = NULL; + } - if (!buffer) { - LogDebug("Failed to allocate statement string"); - return DataCommandAutoPtr(); - } + va_end(args); + ScopedFree<char> buffer(rawBuffer); - LogDebug("Executing SQL data command: " << buffer.Get()); + if (!buffer) { + LogDebug("Failed to allocate statement string"); + return DataCommandAutoPtr(); + } - return DataCommandAutoPtr(new DataCommand(this, buffer.Get())); + LogDebug("Executing SQL data command: " << buffer.Get()); + return DataCommandAutoPtr(new DataCommand(this, buffer.Get())); } SqlConnection::RowID SqlConnection::GetLastInsertRowID() const { - return static_cast<RowID>(sqlite3_last_insert_rowid(m_connection)); + return static_cast<RowID>(sqlite3_last_insert_rowid(m_connection)); } void SqlConnection::TurnOnForeignKeys() { - ExecCommand("PRAGMA foreign_keys = ON;"); + ExecCommand("PRAGMA foreign_keys = ON;"); } SqlConnection::SynchronizationObject * SqlConnection::AllocDefaultSynchronizationObject() { - return new NaiveSynchronizationObject(); + return new NaiveSynchronizationObject(); } void SqlConnection::BeginTransaction() { - ExecCommand("BEGIN;"); + ExecCommand("BEGIN;"); } void SqlConnection::RollbackTransaction() { - ExecCommand("ROLLBACK;"); + ExecCommand("ROLLBACK;"); } void SqlConnection::CommitTransaction() { - ExecCommand("COMMIT;"); + ExecCommand("COMMIT;"); } } // namespace DB diff --git a/src/include/cchecker/UIBackend.h b/src/include/cchecker/UIBackend.h index 659adb8..c0ff3ab 100644 --- a/src/include/cchecker/UIBackend.h +++ b/src/include/cchecker/UIBackend.h @@ -27,31 +27,31 @@ namespace CCHECKER { namespace UI { enum popup_status : int { - NO_ERROR = 0, - EXIT_ERROR = 1 + NO_ERROR = 0, + EXIT_ERROR = 1 }; enum response_e : int { - DONT_UNINSTALL = 2, - UNINSTALL = 3, - RESPONSE_ERROR = 4 + DONT_UNINSTALL = 2, + UNINSTALL = 3, + RESPONSE_ERROR = 4 }; class UIBackend { public: - explicit UIBackend(int timeout = 60); //timeout in seconds (zero or less means infinity) - virtual ~UIBackend(); + explicit UIBackend(int timeout = 60); //timeout in seconds (zero or less means infinity) + virtual ~UIBackend(); - // Displays popup with question, and - if needed - app_control for removing application. - // Returns true if UI was displayed correctly and user's response was collected. - // If there was a problem with displaying UI or a timeout has been reached (no user's response) - // then returns false. - bool call_popup(const app_t &app); + // Displays popup with question, and - if needed - app_control for removing application. + // Returns true if UI was displayed correctly and user's response was collected. + // If there was a problem with displaying UI or a timeout has been reached (no user's response) + // then returns false. + bool call_popup(const app_t &app); private: - response_e run(const app_t &app); + response_e run(const app_t &app); - const int m_responseTimeout; // seconds + const int m_responseTimeout; // seconds }; } // UI diff --git a/src/include/cchecker/popup-runner.h b/src/include/cchecker/popup-runner.h index addaa3b..17aaccd 100644 --- a/src/include/cchecker/popup-runner.h +++ b/src/include/cchecker/popup-runner.h @@ -23,28 +23,28 @@ #include <cchecker/dpl/serialization.h> -namespace CCHECKER{ -namespace UI{ +namespace CCHECKER { +namespace UI { class BinaryStream : public CCHECKER::IStream { - public: - void Read (size_t num, void * bytes); - void Write(size_t num, const void * bytes); +public: + void Read(size_t num, void *bytes); + void Write(size_t num, const void *bytes); - BinaryStream(); - ~BinaryStream(); + BinaryStream(); + ~BinaryStream(); - const unsigned char* char_pointer() const; - size_t size() const; + const unsigned char *char_pointer() const; + size_t size() const; - private: - std::vector<unsigned char> m_data; - size_t m_readPosition; +private: + std::vector<unsigned char> m_data; + size_t m_readPosition; }; response_e run_popup( - const app_t &app, - int timeout); // zero or negative timeout means infinity + const app_t &app, + int timeout); // zero or negative timeout means infinity } // UI } // CCHECKER diff --git a/src/include/cchecker/sql_query.h b/src/include/cchecker/sql_query.h index 6338561..ed1f1a8 100644 --- a/src/include/cchecker/sql_query.h +++ b/src/include/cchecker/sql_query.h @@ -29,41 +29,45 @@ namespace CCHECKER { namespace DB { class SqlQuery { - public: - class Exception { - public: DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base); - public: DECLARE_EXCEPTION_TYPE(Base, InternalError); - public: DECLARE_EXCEPTION_TYPE(Base, TransactionError); - public: DECLARE_EXCEPTION_TYPE(Base, InvalidArgs); - }; - SqlQuery() : - m_connection(NULL), - m_inUserTransaction(false) - {}; - explicit SqlQuery(const std::string &path); - virtual ~SqlQuery(); +public: + class Exception { + public: + DECLARE_EXCEPTION_TYPE(CCHECKER::Exception, Base); + public: + DECLARE_EXCEPTION_TYPE(Base, InternalError); + public: + DECLARE_EXCEPTION_TYPE(Base, TransactionError); + public: + DECLARE_EXCEPTION_TYPE(Base, InvalidArgs); + }; + SqlQuery() : + m_connection(NULL), + m_inUserTransaction(false) + {}; + explicit SqlQuery(const std::string &path); + virtual ~SqlQuery(); - // Connecting outside the constructor - bool connect(const std::string& path); + // Connecting outside the constructor + bool connect(const std::string &path); - // Apps - bool add_app_to_check_list(const app_t &app); - void remove_app_from_check_list(const app_t &app); - void mark_as_verified(const app_t &app, const app_t::verified_t &verified); - void get_app_list(std::list<app_t> &apps_buffer); // TODO: typedef std::list<app_t> + // Apps + bool add_app_to_check_list(const app_t &app); + void remove_app_from_check_list(const app_t &app); + void mark_as_verified(const app_t &app, const app_t::verified_t &verified); + void get_app_list(std::list<app_t> &apps_buffer); // TODO: typedef std::list<app_t> - protected: - SqlConnection *m_connection; +protected: + SqlConnection *m_connection; - private: - bool m_inUserTransaction; - int getDBVersion(void); - void get_apps(std::list<app_t> &apps_buffer); - bool check_if_app_exists(const app_t &app); - bool get_check_id(const app_t &app, int32_t &check_id); - bool add_chain_id(const int32_t check_id, int32_t &chain_id); - int verified_enum_to_int(const app_t::verified_t &verified); - app_t::verified_t verified_int_to_enum(const int &verified); +private: + bool m_inUserTransaction; + int getDBVersion(void); + void get_apps(std::list<app_t> &apps_buffer); + bool check_if_app_exists(const app_t &app); + bool get_check_id(const app_t &app, int32_t &check_id); + bool add_chain_id(const int32_t check_id, int32_t &chain_id); + int verified_enum_to_int(const app_t::verified_t &verified); + app_t::verified_t verified_int_to_enum(const int &verified); }; } // DB } // CCHECKER diff --git a/src/main/cert-checker.cpp b/src/main/cert-checker.cpp index 18fe21a..98eeef8 100644 --- a/src/main/cert-checker.cpp +++ b/src/main/cert-checker.cpp @@ -33,16 +33,11 @@ int main(void) { try { LogInfo("Cert-checker start!"); - CCHECKER::OcspService service(SERVICE_STREAM); - setlocale(LC_ALL, ""); - service.start(); - LogInfo("Cert-checker exit!"); return 0; - } catch (const std::exception &e) { LogError("Exception occured in cert-checker main : " << e.what()); return -1; diff --git a/src/service/app.cpp b/src/service/app.cpp index c35bc73..3a7bd79 100644 --- a/src/service/app.cpp +++ b/src/service/app.cpp @@ -30,48 +30,51 @@ namespace CCHECKER { app_t::app_t(void): - uid((uid_t)-1), // (uid_t)-1 (0xFF) is defined to be invalid uid. According - // to chown manual page, you cannot change file group of owner - // to (uid_t)-1, so we'll use it as initial, invalid value. - verified(verified_t::UNKNOWN) + uid((uid_t) - 1), // (uid_t)-1 (0xFF) is defined to be invalid uid. According + // to chown manual page, you cannot change file group of owner + // to (uid_t)-1, so we'll use it as initial, invalid value. + verified(verified_t::UNKNOWN) {} app_t::app_t(const std::string &app_id, - const std::string &pkg_id, - uid_t uid, - const signatures_t &signatures): - app_id(app_id), - pkg_id(pkg_id), - uid(uid), - signatures(signatures), - verified(verified_t::UNKNOWN) + const std::string &pkg_id, + uid_t uid, + const signatures_t &signatures): + app_id(app_id), + pkg_id(pkg_id), + uid(uid), + signatures(signatures), + verified(verified_t::UNKNOWN) {} -std::ostream & operator<< (std::ostream &out, const app_t &app) +std::ostream &operator<< (std::ostream &out, const app_t &app) { - out << "app: " << app.app_id << ", pkg: " << app.pkg_id << ", uid: " << app.uid; - return out; + out << "app: " << app.app_id << ", pkg: " << app.pkg_id << ", uid: " << app.uid; + return out; } std::string app_t::str() const { - std::stringstream ss; - ss << *this; - return ss.str(); + std::stringstream ss; + ss << *this; + return ss.str(); } std::string app_t::str_certs(void) const { - std::stringstream ss; + std::stringstream ss; - for (const auto &iter : signatures) { - ss << " { "; - for (const auto iter_cert : iter) { - ss << "\"" << iter_cert << "\", "; - } - ss << " } ,"; - } - return ss.str(); + for (const auto &iter : signatures) { + ss << " { "; + + for (const auto iter_cert : iter) { + ss << "\"" << iter_cert << "\", "; + } + + ss << " } ,"; + } + + return ss.str(); } } //CCHECKER diff --git a/src/service/app.h b/src/service/app.h index df4a860..a12703d 100644 --- a/src/service/app.h +++ b/src/service/app.h @@ -36,25 +36,25 @@ typedef std::list<std::string> chain_t; typedef std::list<chain_t> signatures_t; struct app_t { - enum class verified_t : int32_t { - NO = 0, - YES = 1, - UNKNOWN = 2 - }; - - std::string app_id; - std::string pkg_id; - uid_t uid; - signatures_t signatures; - verified_t verified; - - app_t(void); - app_t(const std::string &app_id, - const std::string &pkg_id, - uid_t uid, - const signatures_t &signatures); - std::string str(void) const; - std::string str_certs(void) const; + enum class verified_t : int32_t { + NO = 0, + YES = 1, + UNKNOWN = 2 + }; + + std::string app_id; + std::string pkg_id; + uid_t uid; + signatures_t signatures; + verified_t verified; + + app_t(void); + app_t(const std::string &app_id, + const std::string &pkg_id, + uid_t uid, + const signatures_t &signatures); + std::string str(void) const; + std::string str_certs(void) const; }; } //CCHECKER diff --git a/src/service/certs.cpp b/src/service/certs.cpp index c06fe6f..8abdc43 100644 --- a/src/service/certs.cpp +++ b/src/service/certs.cpp @@ -39,65 +39,65 @@ namespace CCHECKER { namespace { struct PkgmgrinfoCertInfo { - PkgmgrinfoCertInfo() - { - ret = pkgmgrinfo_pkginfo_create_certinfo(&handle); - } - ~PkgmgrinfoCertInfo() - { - pkgmgrinfo_pkginfo_destroy_certinfo(handle); - } - - pkgmgrinfo_certinfo_h handle; - int ret; + PkgmgrinfoCertInfo() + { + ret = pkgmgrinfo_pkginfo_create_certinfo(&handle); + } + ~PkgmgrinfoCertInfo() + { + pkgmgrinfo_pkginfo_destroy_certinfo(handle); + } + + pkgmgrinfo_certinfo_h handle; + int ret; }; static void get_cert_chain(const char *pkgid, uid_t uid, int sig_type, chain_t &chain) { - LogDebug("Get cert chain start. pkgid : " << pkgid << ", uid : " << uid); - int ret; - int cert_type; - const char *cert_value; - - auto pm_certinfo = std::make_shared<PkgmgrinfoCertInfo>(); - - if (pm_certinfo->ret != PMINFO_R_OK) { - LogError("Get pkgmgrinfo certinfo failed. ret : " << ret); - return; - } - - ret = pkgmgrinfo_pkginfo_load_certinfo(pkgid, pm_certinfo->handle, uid); - if (ret != PMINFO_R_OK) { - LogError("Load pkgmgrinfo certinfo failed. ret : " << ret); - return; - } - - // add signer, intermediate, root certificates. - for (int cert_cnt = 0; cert_cnt < 3; cert_cnt++) { - cert_type = sig_type - cert_cnt; - ret = pkgmgrinfo_pkginfo_get_cert_value(pm_certinfo->handle, - static_cast<pkgmgrinfo_cert_type>(cert_type), &cert_value); - - if (ret != PMINFO_R_OK) { - LogError("Get cert value from certinfo failed. ret : " << ret); - return; - } - - if (cert_value == NULL) { - LogDebug("cert_type[" << cert_type << "] is null"); - } else { - LogDebug("Add cert_type[" << cert_type << "] data : " << cert_value); - chain.push_back(cert_value); - } - } - - return; + LogDebug("Get cert chain start. pkgid : " << pkgid << ", uid : " << uid); + int ret; + int cert_type; + const char *cert_value; + auto pm_certinfo = std::make_shared<PkgmgrinfoCertInfo>(); + + if (pm_certinfo->ret != PMINFO_R_OK) { + LogError("Get pkgmgrinfo certinfo failed. ret : " << ret); + return; + } + + ret = pkgmgrinfo_pkginfo_load_certinfo(pkgid, pm_certinfo->handle, uid); + + if (ret != PMINFO_R_OK) { + LogError("Load pkgmgrinfo certinfo failed. ret : " << ret); + return; + } + + // add signer, intermediate, root certificates. + for (int cert_cnt = 0; cert_cnt < 3; cert_cnt++) { + cert_type = sig_type - cert_cnt; + ret = pkgmgrinfo_pkginfo_get_cert_value(pm_certinfo->handle, + static_cast<pkgmgrinfo_cert_type>(cert_type), &cert_value); + + if (ret != PMINFO_R_OK) { + LogError("Get cert value from certinfo failed. ret : " << ret); + return; + } + + if (cert_value == NULL) { + LogDebug("cert_type[" << cert_type << "] is null"); + } else { + LogDebug("Add cert_type[" << cert_type << "] data : " << cert_value); + chain.push_back(cert_value); + } + } + + return; } } Certs::Certs() { - m_ckm = CKM::Manager::create(); + m_ckm = CKM::Manager::create(); } Certs::~Certs() @@ -105,100 +105,109 @@ Certs::~Certs() void Certs::get_certificates(app_t &app) { - // build chain using pkgmgr-info - std::map<int, int> sig_type; - sig_type[AUTHOR_SIG] = PMINFO_AUTHOR_SIGNER_CERT; - sig_type[DISTRIBUTOR_SIG] = PMINFO_DISTRIBUTOR_SIGNER_CERT; - sig_type[DISTRIBUTOR2_SIG] = PMINFO_DISTRIBUTOR2_SIGNER_CERT; - - for (auto s : sig_type) { - chain_t chain; - get_cert_chain(app.pkg_id.c_str(), app.uid, s.second, chain); - - if(!chain.empty()) { - LogDebug("Add certificates chain to app. Size of chain : " << chain.size()); - app.signatures.emplace_back(std::move(chain)); - } - } + // build chain using pkgmgr-info + std::map<int, int> sig_type; + sig_type[AUTHOR_SIG] = PMINFO_AUTHOR_SIGNER_CERT; + sig_type[DISTRIBUTOR_SIG] = PMINFO_DISTRIBUTOR_SIGNER_CERT; + sig_type[DISTRIBUTOR2_SIG] = PMINFO_DISTRIBUTOR2_SIGNER_CERT; + + for (auto s : sig_type) { + chain_t chain; + get_cert_chain(app.pkg_id.c_str(), app.uid, s.second, chain); + + if (!chain.empty()) { + LogDebug("Add certificates chain to app. Size of chain : " << chain.size()); + app.signatures.emplace_back(std::move(chain)); + } + } } Certs::ocsp_response_t Certs::check_ocsp_chain(const chain_t &chain) { - CKM::CertificateShPtrVector vect_ckm_chain; - - LogDebug("Size of chain: " << chain.size()); - for (auto &iter : chain) { - CKM::RawBuffer buff(iter.begin(), iter.end()); - auto cert = CKM::Certificate::create(buff, CKM::DataFormat::FORM_DER_BASE64); - vect_ckm_chain.emplace_back(std::move(cert)); - } - - int status = CKM_API_OCSP_STATUS_UNKNOWN; - int ret = m_ckm->ocspCheck(vect_ckm_chain, status); - if (ret != CKM_API_SUCCESS) { - LogError("CKM ckeck OCSP returned " << ret); - // Add handling for different errors codes - // For these we can try to check ocsp again later: - switch (ret) { - case CKM_API_ERROR_NOT_SUPPORTED: - LogDebug("Key-manager OCSP API temporary diabled."); - case CKM_API_ERROR_SOCKET: - case CKM_API_ERROR_BAD_REQUEST: - case CKM_API_ERROR_BAD_RESPONSE: - case CKM_API_ERROR_SEND_FAILED: - case CKM_API_ERROR_RECV_FAILED: - case CKM_API_ERROR_SERVER_ERROR: - case CKM_API_ERROR_OUT_OF_MEMORY: - return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; - // Any other error should be recurrent - checking the same app again - // should give the same result. - default: - return Certs::ocsp_response_t::OCSP_CERT_ERROR; - } - } - - LogDebug("OCSP status: " << status); - switch (status) { - // Remove app from "to-check" list: - case CKM_API_OCSP_STATUS_GOOD: - return Certs::ocsp_response_t::OCSP_APP_OK; - case CKM_API_OCSP_STATUS_UNSUPPORTED: - case CKM_API_OCSP_STATUS_UNKNOWN: - case CKM_API_OCSP_STATUS_INVALID_URL: - return Certs::ocsp_response_t::OCSP_CERT_ERROR; - - //Show popup to user and remove app from "to-check" list - case CKM_API_OCSP_STATUS_REVOKED: - return Certs::ocsp_response_t::OCSP_APP_REVOKED; - - //Keep app for checking it again later: - case CKM_API_OCSP_STATUS_NET_ERROR: - case CKM_API_OCSP_STATUS_INVALID_RESPONSE: - case CKM_API_OCSP_STATUS_REMOTE_ERROR: - case CKM_API_OCSP_STATUS_INTERNAL_ERROR: - return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; - - default: - // This should never happen - return Certs::ocsp_response_t::OCSP_CERT_ERROR; - } + CKM::CertificateShPtrVector vect_ckm_chain; + LogDebug("Size of chain: " << chain.size()); + + for (auto &iter : chain) { + CKM::RawBuffer buff(iter.begin(), iter.end()); + auto cert = CKM::Certificate::create(buff, CKM::DataFormat::FORM_DER_BASE64); + vect_ckm_chain.emplace_back(std::move(cert)); + } + + int status = CKM_API_OCSP_STATUS_UNKNOWN; + int ret = m_ckm->ocspCheck(vect_ckm_chain, status); + + if (ret != CKM_API_SUCCESS) { + LogError("CKM ckeck OCSP returned " << ret); + + // Add handling for different errors codes + // For these we can try to check ocsp again later: + switch (ret) { + case CKM_API_ERROR_NOT_SUPPORTED: + LogDebug("Key-manager OCSP API temporary diabled."); + + case CKM_API_ERROR_SOCKET: + case CKM_API_ERROR_BAD_REQUEST: + case CKM_API_ERROR_BAD_RESPONSE: + case CKM_API_ERROR_SEND_FAILED: + case CKM_API_ERROR_RECV_FAILED: + case CKM_API_ERROR_SERVER_ERROR: + case CKM_API_ERROR_OUT_OF_MEMORY: + return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; + + // Any other error should be recurrent - checking the same app again + // should give the same result. + default: + return Certs::ocsp_response_t::OCSP_CERT_ERROR; + } + } + + LogDebug("OCSP status: " << status); + + switch (status) { + // Remove app from "to-check" list: + case CKM_API_OCSP_STATUS_GOOD: + return Certs::ocsp_response_t::OCSP_APP_OK; + + case CKM_API_OCSP_STATUS_UNSUPPORTED: + case CKM_API_OCSP_STATUS_UNKNOWN: + case CKM_API_OCSP_STATUS_INVALID_URL: + return Certs::ocsp_response_t::OCSP_CERT_ERROR; + + //Show popup to user and remove app from "to-check" list + case CKM_API_OCSP_STATUS_REVOKED: + return Certs::ocsp_response_t::OCSP_APP_REVOKED; + + //Keep app for checking it again later: + case CKM_API_OCSP_STATUS_NET_ERROR: + case CKM_API_OCSP_STATUS_INVALID_RESPONSE: + case CKM_API_OCSP_STATUS_REMOTE_ERROR: + case CKM_API_OCSP_STATUS_INTERNAL_ERROR: + return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; + + default: + // This should never happen + return Certs::ocsp_response_t::OCSP_CERT_ERROR; + } } -Certs::ocsp_response_t Certs::check_ocsp (const app_t &app) +Certs::ocsp_response_t Certs::check_ocsp(const app_t &app) { - bool check_again = false; - - for (auto &iter : app.signatures) { - Certs::ocsp_response_t resp = check_ocsp_chain(iter); - if (resp == Certs::ocsp_response_t::OCSP_APP_REVOKED) - return Certs::ocsp_response_t::OCSP_APP_REVOKED; - if (resp == Certs::ocsp_response_t::OCSP_CHECK_AGAIN) - check_again = true; - } - - if (check_again) - return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; - return Certs::ocsp_response_t::OCSP_APP_OK; + bool check_again = false; + + for (auto &iter : app.signatures) { + Certs::ocsp_response_t resp = check_ocsp_chain(iter); + + if (resp == Certs::ocsp_response_t::OCSP_APP_REVOKED) + return Certs::ocsp_response_t::OCSP_APP_REVOKED; + + if (resp == Certs::ocsp_response_t::OCSP_CHECK_AGAIN) + check_again = true; + } + + if (check_again) + return Certs::ocsp_response_t::OCSP_CHECK_AGAIN; + + return Certs::ocsp_response_t::OCSP_APP_OK; } } // CCHECKER diff --git a/src/service/certs.h b/src/service/certs.h index 4871c39..46c688e 100644 --- a/src/service/certs.h +++ b/src/service/certs.h @@ -34,29 +34,29 @@ namespace CCHECKER { enum sig_t { - AUTHOR_SIG, - DISTRIBUTOR_SIG, - DISTRIBUTOR2_SIG + AUTHOR_SIG, + DISTRIBUTOR_SIG, + DISTRIBUTOR2_SIG }; class Certs { - public: - enum class ocsp_response_t { - OCSP_APP_OK, - OCSP_APP_REVOKED, - OCSP_CHECK_AGAIN, - OCSP_CERT_ERROR - }; - Certs(); - virtual ~Certs(); - void get_certificates (app_t &app); - ocsp_response_t check_ocsp (const app_t &app); +public: + enum class ocsp_response_t { + OCSP_APP_OK, + OCSP_APP_REVOKED, + OCSP_CHECK_AGAIN, + OCSP_CERT_ERROR + }; + Certs(); + virtual ~Certs(); + void get_certificates(app_t &app); + ocsp_response_t check_ocsp(const app_t &app); - protected: // Needed for tests - ocsp_response_t check_ocsp_chain (const chain_t &chain); +protected: // Needed for tests + ocsp_response_t check_ocsp_chain(const chain_t &chain); - //private: - CKM::ManagerShPtr m_ckm; + //private: + CKM::ManagerShPtr m_ckm; }; } // CCHECKER diff --git a/src/service/logic.cpp b/src/service/logic.cpp index 574b9b2..0bef2ee 100644 --- a/src/service/logic.cpp +++ b/src/service/logic.cpp @@ -38,38 +38,38 @@ namespace CCHECKER { namespace { struct PkgmgrinfoEvent { - PkgmgrinfoEvent(uid_t _uid, const char *_pkgid) - : uid(_uid) - , pkgid(_pkgid) {} - - inline bool operator==(const PkgmgrinfoEvent &rhs) const - { - return uid == rhs.uid && pkgid.compare(rhs.pkgid) == 0; - } - - inline bool operator<(const PkgmgrinfoEvent &rhs) const - { - if (uid < rhs.uid) - return true; - else if (uid < rhs.uid) - return false; - else - return pkgid.compare(rhs.pkgid) < 0; - } - - inline bool operator>(const PkgmgrinfoEvent &rhs) const - { - if (uid > rhs.uid) - return true; - else if (uid < rhs.uid) - return false; - else - return pkgid.compare(rhs.pkgid) > 0; - } - - uid_t uid; - std::string pkgid; - pkgmgr_event_t type; + PkgmgrinfoEvent(uid_t _uid, const char *_pkgid) + : uid(_uid) + , pkgid(_pkgid) {} + + inline bool operator==(const PkgmgrinfoEvent &rhs) const + { + return uid == rhs.uid && pkgid.compare(rhs.pkgid) == 0; + } + + inline bool operator<(const PkgmgrinfoEvent &rhs) const + { + if (uid < rhs.uid) + return true; + else if (uid < rhs.uid) + return false; + else + return pkgid.compare(rhs.pkgid) < 0; + } + + inline bool operator>(const PkgmgrinfoEvent &rhs) const + { + if (uid > rhs.uid) + return true; + else if (uid < rhs.uid) + return false; + else + return pkgid.compare(rhs.pkgid) > 0; + } + + uid_t uid; + std::string pkgid; + pkgmgr_event_t type; }; std::set<PkgmgrinfoEvent> pkgmgrinfo_event_set; @@ -79,395 +79,388 @@ const char *const DB_PATH = DB_INSTALL_DIR"/.cert-checker.db"; Logic::~Logic(void) { - clean(); + clean(); } void Logic::clean(void) { - LogDebug("Cert-checker cleaning start."); - - // wait and join processing thread - if (m_thread.joinable()) { - LogDebug("Waiting for join processing thread"); - { - std::lock_guard<std::mutex> lock(m_mutex_cv); - set_should_exit(); - LogDebug("Notify thread : enforced by cleaning"); - m_to_process.notify_one(); - } - m_thread.join(); - LogDebug("Processing thread joined"); - } - else - LogDebug("No thread to join"); - - if (m_proxy_connman) - g_object_unref(m_proxy_connman); - - if (m_loop) - g_main_loop_unref(m_loop); - - delete m_sqlquery; - - timerStop(); - - LogDebug("Cert-checker cleaning finish."); + LogDebug("Cert-checker cleaning start."); + + // wait and join processing thread + if (m_thread.joinable()) { + LogDebug("Waiting for join processing thread"); + { + std::lock_guard<std::mutex> lock(m_mutex_cv); + set_should_exit(); + LogDebug("Notify thread : enforced by cleaning"); + m_to_process.notify_one(); + } + m_thread.join(); + LogDebug("Processing thread joined"); + } else { + LogDebug("No thread to join"); + } + + if (m_proxy_connman) + g_object_unref(m_proxy_connman); + + if (m_loop) + g_main_loop_unref(m_loop); + + delete m_sqlquery; + timerStop(); + LogDebug("Cert-checker cleaning finish."); } Logic::Logic(void) : - m_loop(g_main_loop_new(NULL, FALSE)), - m_sqlquery(NULL), - m_was_setup_called(false), - m_is_online(false), - m_is_online_enabled(false), - m_should_exit(false), - m_proxy_connman(NULL), - m_pc_install(nullptr, nullptr), - m_pc_uninstall(nullptr, nullptr) + m_loop(g_main_loop_new(NULL, FALSE)), + m_sqlquery(NULL), + m_was_setup_called(false), + m_is_online(false), + m_is_online_enabled(false), + m_should_exit(false), + m_proxy_connman(NULL), + m_pc_install(nullptr, nullptr), + m_pc_uninstall(nullptr, nullptr) { } bool Logic::get_online() const { - return m_is_online; + return m_is_online; } void Logic::set_online(bool online) { - std::lock_guard<std::mutex> lock(m_mutex_cv); - - m_is_online = online; - if (m_is_online) { - m_is_online_enabled = true; - LogDebug("Notify thread : Network connected"); - m_to_process.notify_one(); - } + std::lock_guard<std::mutex> lock(m_mutex_cv); + m_is_online = online; + + if (m_is_online) { + m_is_online_enabled = true; + LogDebug("Notify thread : Network connected"); + m_to_process.notify_one(); + } } error_t Logic::setup_db() { - // TODO: If database doesn't exist -should we create a new one? - Try { - m_sqlquery = new DB::SqlQuery(DB_PATH); - } Catch (runtime_error) { - LogError("Error while creating SqlQuery object"); - return DATABASE_ERROR; - } - - if(!m_sqlquery) { - LogError("Cannot open database"); - return DATABASE_ERROR; - } - - return NO_ERROR; + // TODO: If database doesn't exist -should we create a new one? + Try { + m_sqlquery = new DB::SqlQuery(DB_PATH); + } Catch(runtime_error) { + LogError("Error while creating SqlQuery object"); + return DATABASE_ERROR; + } + + if (!m_sqlquery) { + LogError("Cannot open database"); + return DATABASE_ERROR; + } + + return NO_ERROR; } error_t Logic::setup() { - // Check if setup was called - if (m_was_setup_called) { - LogDebug("Setup is already done."); - return NO_ERROR; - } - m_was_setup_called = true; - - // Check if DB exists and create a new one if it doesn't - error_t err = setup_db(); - if (err != NO_ERROR) { - LogError("Database error"); - return err; - } - - load_database_to_buffer(); - - // run process thread - thread will be waiting on condition variable - m_thread = std::thread(&Logic::process_all, this); - - // Add connman callback - LogDebug("register connman event callback start"); - if (register_dbus_signal_handler(&m_proxy_connman, - "net.connman", - "/", - "net.connman.Manager", - connman_callback) != NO_ERROR) { - LogError("Error in register_connman_signal_handler"); - return REGISTER_CALLBACK_ERROR; - } - LogDebug("register connman event callback success"); - - set_connman_online_state(); - - // Add pkgmgrinfo callback - LogDebug("Register package event handler start"); - - std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> - _pcInstall(pkgmgrinfo_client_new(PMINFO_LISTENING), pkgmgrinfo_client_free); - std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> - _pcUninstall(pkgmgrinfo_client_new(PMINFO_LISTENING), pkgmgrinfo_client_free); - m_pc_install = std::move(_pcInstall); - m_pc_uninstall = std::move(_pcUninstall); - - if (!m_pc_install || !m_pc_uninstall) { - LogError("Get pkgmgrinfo client failed"); - return REGISTER_CALLBACK_ERROR; - } - - int ret_status_install; - int ret_status_uninstall; - ret_status_install = pkgmgrinfo_client_set_status_type( - m_pc_install.get(), PKGMGR_CLIENT_STATUS_INSTALL); - ret_status_uninstall = pkgmgrinfo_client_set_status_type( - m_pc_uninstall.get(), PKGMGR_CLIENT_STATUS_UNINSTALL); - - if (ret_status_install == PMINFO_R_ERROR || ret_status_uninstall == PMINFO_R_ERROR) { - LogError("Set pkgmgrinfo status fail"); - return REGISTER_CALLBACK_ERROR; - } - m_reqid_install = pkgmgrinfo_client_listen_status( - m_pc_install.get(), pkgmgrinfo_event_handler_static, this); - m_reqid_uninstall = pkgmgrinfo_client_listen_status( - m_pc_uninstall.get(), pkgmgrinfo_event_handler_static, this); - - if (m_reqid_install < 0 || m_reqid_uninstall < 0) { - LogError("Register pacakge install event handler fail"); - return REGISTER_CALLBACK_ERROR; - } - - // Init for gio timeout. - m_is_first_run = false; - - LogDebug("Register package event handler success"); - - return NO_ERROR; + // Check if setup was called + if (m_was_setup_called) { + LogDebug("Setup is already done."); + return NO_ERROR; + } + + m_was_setup_called = true; + // Check if DB exists and create a new one if it doesn't + error_t err = setup_db(); + + if (err != NO_ERROR) { + LogError("Database error"); + return err; + } + + load_database_to_buffer(); + // run process thread - thread will be waiting on condition variable + m_thread = std::thread(&Logic::process_all, this); + // Add connman callback + LogDebug("register connman event callback start"); + + if (register_dbus_signal_handler(&m_proxy_connman, + "net.connman", + "/", + "net.connman.Manager", + connman_callback) != NO_ERROR) { + LogError("Error in register_connman_signal_handler"); + return REGISTER_CALLBACK_ERROR; + } + + LogDebug("register connman event callback success"); + set_connman_online_state(); + // Add pkgmgrinfo callback + LogDebug("Register package event handler start"); + std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> + _pcInstall(pkgmgrinfo_client_new(PMINFO_LISTENING), pkgmgrinfo_client_free); + std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> + _pcUninstall(pkgmgrinfo_client_new(PMINFO_LISTENING), pkgmgrinfo_client_free); + m_pc_install = std::move(_pcInstall); + m_pc_uninstall = std::move(_pcUninstall); + + if (!m_pc_install || !m_pc_uninstall) { + LogError("Get pkgmgrinfo client failed"); + return REGISTER_CALLBACK_ERROR; + } + + int ret_status_install; + int ret_status_uninstall; + ret_status_install = pkgmgrinfo_client_set_status_type( + m_pc_install.get(), PKGMGR_CLIENT_STATUS_INSTALL); + ret_status_uninstall = pkgmgrinfo_client_set_status_type( + m_pc_uninstall.get(), PKGMGR_CLIENT_STATUS_UNINSTALL); + + if (ret_status_install == PMINFO_R_ERROR || ret_status_uninstall == PMINFO_R_ERROR) { + LogError("Set pkgmgrinfo status fail"); + return REGISTER_CALLBACK_ERROR; + } + + m_reqid_install = pkgmgrinfo_client_listen_status( + m_pc_install.get(), pkgmgrinfo_event_handler_static, this); + m_reqid_uninstall = pkgmgrinfo_client_listen_status( + m_pc_uninstall.get(), pkgmgrinfo_event_handler_static, this); + + if (m_reqid_install < 0 || m_reqid_uninstall < 0) { + LogError("Register pacakge install event handler fail"); + return REGISTER_CALLBACK_ERROR; + } + + // Init for gio timeout. + m_is_first_run = false; + LogDebug("Register package event handler success"); + return NO_ERROR; } void Logic::run(guint timeout) { - LogDebug("Running the main loop"); - - g_timeout_add_seconds(timeout, timeout_cb, m_loop); - g_main_loop_run(m_loop); + LogDebug("Running the main loop"); + g_timeout_add_seconds(timeout, timeout_cb, m_loop); + g_main_loop_run(m_loop); } int Logic::pkgmgrinfo_event_handler_static( - uid_t uid, - int reqid, - const char *pkgtype, - const char *pkgid, - const char *key, - const char *val, - const void *pmsg, - void *data) + uid_t uid, + int reqid, + const char *pkgtype, + const char *pkgid, + const char *key, + const char *val, + const void *pmsg, + void *data) { - LogDebug("pkgmgrinfo event handler start!!"); - if (data == nullptr) - return -1; - - std::string keyStr(key); - std::string valStr(val); - LogDebug("pkgmgrinfo event was caught. type : " << valStr << ", status : " << keyStr); - - if ((valStr.compare("install") == 0 || valStr.compare("uninstall") == 0) - && keyStr.compare("start") == 0) { - return static_cast<Logic *>(data)->pkgmgrinfo_event_handler( - uid, reqid, pkgtype, pkgid, key, val, pmsg, data); - } else if (keyStr.compare("end") == 0 && valStr.compare("ok") == 0) { - return static_cast<Logic *>(data)->push_pkgmgrinfo_event(uid, pkgid); - } else { - // TODO(sangwan.kwon) if get untreat event like fail, must quit loop - LogDebug("Untreated event was caught : " << val); - return -1; - } + LogDebug("pkgmgrinfo event handler start!!"); + + if (data == nullptr) + return -1; + + std::string keyStr(key); + std::string valStr(val); + LogDebug("pkgmgrinfo event was caught. type : " << valStr << ", status : " << keyStr); + + if ((valStr.compare("install") == 0 || valStr.compare("uninstall") == 0) + && keyStr.compare("start") == 0) { + return static_cast<Logic *>(data)->pkgmgrinfo_event_handler( + uid, reqid, pkgtype, pkgid, key, val, pmsg, data); + } else if (keyStr.compare("end") == 0 && valStr.compare("ok") == 0) { + return static_cast<Logic *>(data)->push_pkgmgrinfo_event(uid, pkgid); + } else { + // TODO(sangwan.kwon) if get untreat event like fail, must quit loop + LogDebug("Untreated event was caught : " << val); + return -1; + } } int Logic::pkgmgrinfo_event_handler( - uid_t uid, - int reqid, - const char */*pkgtype*/, - const char *pkgid, - const char *key, - const char *val, - const void */*pmsg*/, - void */*data*/) + uid_t uid, + int reqid, + const char */*pkgtype*/, + const char *pkgid, + const char *key, + const char *val, + const void */*pmsg*/, + void */*data*/) { - if (pkgid == nullptr || key == nullptr || val == nullptr) { - LogError("Invalid parameter."); - return -1; - } - - std::string keyStr(key); - std::string valStr(val); - - LogDebug("uid: " << uid << " pkgid: " << pkgid << " key: " << keyStr << " val: " << valStr); - - PkgmgrinfoEvent event(uid, pkgid); - - if(valStr.compare("install") == 0) { - if (reqid != m_reqid_install) { - LogError("pkgmgrinfo event reqid unmatched"); - return -1; - } - event.type = EVENT_INSTALL; - } else if(valStr.compare("uninstall") == 0) { - if (reqid != m_reqid_uninstall) { - LogError("pkgmgrinfo event reqid unmatched"); - return -1; - } - event.type = EVENT_UNINSTALL; - } - - pkgmgrinfo_event_set.insert(event); - - return 0; + if (pkgid == nullptr || key == nullptr || val == nullptr) { + LogError("Invalid parameter."); + return -1; + } + + std::string keyStr(key); + std::string valStr(val); + LogDebug("uid: " << uid << " pkgid: " << pkgid << " key: " << keyStr << " val: " << valStr); + PkgmgrinfoEvent event(uid, pkgid); + + if (valStr.compare("install") == 0) { + if (reqid != m_reqid_install) { + LogError("pkgmgrinfo event reqid unmatched"); + return -1; + } + + event.type = EVENT_INSTALL; + } else if (valStr.compare("uninstall") == 0) { + if (reqid != m_reqid_uninstall) { + LogError("pkgmgrinfo event reqid unmatched"); + return -1; + } + + event.type = EVENT_UNINSTALL; + } + + pkgmgrinfo_event_set.insert(event); + return 0; } int Logic::push_pkgmgrinfo_event(uid_t uid, const char *pkgid) { - PkgmgrinfoEvent event(uid, pkgid); - std::set<PkgmgrinfoEvent>::iterator pkgmgrinfo_event_iter = pkgmgrinfo_event_set.find(event); - - if (pkgmgrinfo_event_iter != pkgmgrinfo_event_set.end()) { - // FIXME: No information about app_id in the signal. Use stub. - app_t app(TEMP_APP_ID, pkgid, uid, {}); - - if (pkgmgrinfo_event_iter->type == EVENT_INSTALL) { - LogDebug("Successfully Installed. uid: " << uid << ", pkgid: " << pkgid); - push_event(event_t(app, event_t::event_type_t::APP_INSTALL)); - } else if (pkgmgrinfo_event_iter->type == EVENT_UNINSTALL) { - LogDebug("Successfully Uninstalled. uid: " << uid << ", pkgid: " << pkgid); - push_event(event_t(app, event_t::event_type_t::APP_UNINSTALL)); - } - - LogDebug("push pkgmgrifo success. pkgid: " << pkgid << ", uid: " << uid); - pkgmgrinfo_event_set.erase(event); - return 0; - } else { - // if update status, return fail - LogDebug("push pkgmgrifo fail. pkgid: " << pkgid << ", uid: " << uid); - return -1; - } + PkgmgrinfoEvent event(uid, pkgid); + std::set<PkgmgrinfoEvent>::iterator pkgmgrinfo_event_iter = pkgmgrinfo_event_set.find(event); + + if (pkgmgrinfo_event_iter != pkgmgrinfo_event_set.end()) { + // FIXME: No information about app_id in the signal. Use stub. + app_t app(TEMP_APP_ID, pkgid, uid, {}); + + if (pkgmgrinfo_event_iter->type == EVENT_INSTALL) { + LogDebug("Successfully Installed. uid: " << uid << ", pkgid: " << pkgid); + push_event(event_t(app, event_t::event_type_t::APP_INSTALL)); + } else if (pkgmgrinfo_event_iter->type == EVENT_UNINSTALL) { + LogDebug("Successfully Uninstalled. uid: " << uid << ", pkgid: " << pkgid); + push_event(event_t(app, event_t::event_type_t::APP_UNINSTALL)); + } + + LogDebug("push pkgmgrifo success. pkgid: " << pkgid << ", uid: " << uid); + pkgmgrinfo_event_set.erase(event); + return 0; + } else { + // if update status, return fail + LogDebug("push pkgmgrifo fail. pkgid: " << pkgid << ", uid: " << uid); + return -1; + } } error_t Logic::register_dbus_signal_handler(GDBusProxy **proxy, - const char *name, - const char *object_path, - const char *interface_name, - void (*callback) (GDBusProxy *proxy, - gchar *sender_name, - gchar *signal_name, - GVariant *parameters, - void *logic_ptr) - ) + const char *name, + const char *object_path, + const char *interface_name, + void (*callback)(GDBusProxy *proxy, + gchar *sender_name, + gchar *signal_name, + GVariant *parameters, + void *logic_ptr) + ) { - GError *error = NULL; - GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_NONE; - - // Obtain a connection to the System Bus - *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, - flags, - NULL, /* GDBusInterfaceInfo */ - name, - object_path, - interface_name, - NULL, /* GCancellable */ - &error); - - if (*proxy == NULL) { - if (error) { - LogError("Error creating D-Bus proxy for /'" << interface_name <<"/': " << error->message); - g_error_free(error); - } else { - LogError("Error creating D-Bus proxy for /'" << interface_name <<"/'. Unknown error"); - } - return DBUS_ERROR; - } - - // Connect to g-signal to receive signals from proxy - if (g_signal_connect(*proxy, "g-signal", G_CALLBACK(callback), this) < 1) { - LogError("g_signal_connect error while connecting " << interface_name); - return REGISTER_CALLBACK_ERROR; - } - - return NO_ERROR; + GError *error = NULL; + GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_NONE; + // Obtain a connection to the System Bus + *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, + flags, + NULL, /* GDBusInterfaceInfo */ + name, + object_path, + interface_name, + NULL, /* GCancellable */ + &error); + + if (*proxy == NULL) { + if (error) { + LogError("Error creating D-Bus proxy for /'" << interface_name << "/': " << error->message); + g_error_free(error); + } else { + LogError("Error creating D-Bus proxy for /'" << interface_name << "/'. Unknown error"); + } + + return DBUS_ERROR; + } + + // Connect to g-signal to receive signals from proxy + if (g_signal_connect(*proxy, "g-signal", G_CALLBACK(callback), this) < 1) { + LogError("g_signal_connect error while connecting " << interface_name); + return REGISTER_CALLBACK_ERROR; + } + + return NO_ERROR; } void Logic::set_connman_online_state() { - GError *error = NULL; - GVariant *response; - - if (m_proxy_connman == NULL) { - LogError("connman proxy is NULL"); - return; - } - - response = g_dbus_proxy_call_sync (m_proxy_connman, - "GetProperties", - NULL, // GetProperties gets no parameters - G_DBUS_CALL_FLAGS_NONE, - -1, // Default timeout - NULL, - &error); - - if (error) { - LogError("Error while calling connman GetProperties() Dbus API: " << error->message); - g_error_free(error); - return; - } - - if (response == NULL) { - // This should never happen - return; - } - - gchar *resp_g = g_variant_print(response, TRUE); - std::string resp_s(resp_g); - LogDebug("response: " << resp_s); - g_free(resp_g); - - // Response should look like this: - // ({'State': <'online'>, 'OfflineMode': <false>, 'SessionMode': <false>},) - if (resp_s.find("'State': <'online'>", 0) != std::string::npos) { - LogDebug("Connman has returned: online"); - set_online(true); - } - - // free memory - g_variant_unref(response); + GError *error = NULL; + GVariant *response; + + if (m_proxy_connman == NULL) { + LogError("connman proxy is NULL"); + return; + } + + response = g_dbus_proxy_call_sync(m_proxy_connman, + "GetProperties", + NULL, // GetProperties gets no parameters + G_DBUS_CALL_FLAGS_NONE, + -1, // Default timeout + NULL, + &error); + + if (error) { + LogError("Error while calling connman GetProperties() Dbus API: " << error->message); + g_error_free(error); + return; + } + + if (response == NULL) { + // This should never happen + return; + } + + gchar *resp_g = g_variant_print(response, TRUE); + std::string resp_s(resp_g); + LogDebug("response: " << resp_s); + g_free(resp_g); + + // Response should look like this: + // ({'State': <'online'>, 'OfflineMode': <false>, 'SessionMode': <false>},) + if (resp_s.find("'State': <'online'>", 0) != std::string::npos) { + LogDebug("Connman has returned: online"); + set_online(true); + } + + // free memory + g_variant_unref(response); } void Logic::connman_callback(GDBusProxy */*proxy*/, - gchar */*sender_name*/, - gchar *signal_name, - GVariant *parameters, - void *logic_ptr) + gchar */*sender_name*/, + gchar *signal_name, + GVariant *parameters, + void *logic_ptr) { - string signal_name_str = string(signal_name); - if (signal_name_str != "PropertyChanged") { - // Invalid param. Nothing to do here. - return; - } - - gchar *parameters_g = g_variant_print(parameters, TRUE); - string params_str = string(parameters_g); - g_free (parameters_g); - - Logic *logic = static_cast<Logic*> (logic_ptr); - - if (params_str == "('State', <'online'>)") { - LogDebug("Device online"); - logic->set_online(true); - } - else if (params_str == "('State', <'offline'>)") { - LogDebug("Device offline"); - logic->set_online(false); - } + string signal_name_str = string(signal_name); + + if (signal_name_str != "PropertyChanged") { + // Invalid param. Nothing to do here. + return; + } + + gchar *parameters_g = g_variant_print(parameters, TRUE); + string params_str = string(parameters_g); + g_free(parameters_g); + Logic *logic = static_cast<Logic *>(logic_ptr); + + if (params_str == "('State', <'online'>)") { + LogDebug("Device online"); + logic->set_online(true); + } else if (params_str == "('State', <'offline'>)") { + LogDebug("Device offline"); + logic->set_online(false); + } } void Logic::load_database_to_buffer() { - LogDebug("Loading database to the buffer"); - m_sqlquery->get_app_list(m_buffer); + LogDebug("Loading database to the buffer"); + m_sqlquery->get_app_list(m_buffer); } /** @@ -475,182 +468,184 @@ void Logic::load_database_to_buffer() **/ void Logic::process_queue(void) { - event_t event; - while(m_queue.pop_event(event)) { - process_event(event); - } + event_t event; + + while (m_queue.pop_event(event)) { + process_event(event); + } } bool Logic::call_ui(const app_t &app) { - UI::UIBackend ui; - - if (ui.call_popup(app)) { // If calling popup or app_controll service will fail, - // do not remove application, and ask about it once again later - LogDebug("Popup shown correctly. Application will be removed from DB and buffer"); - return true; - } - LogDebug("Popup error. Application will be marked to show popup later."); - return false; + UI::UIBackend ui; + + if (ui.call_popup(app)) { // If calling popup or app_controll service will fail, + // do not remove application, and ask about it once again later + LogDebug("Popup shown correctly. Application will be removed from DB and buffer"); + return true; + } + + LogDebug("Popup error. Application will be marked to show popup later."); + return false; } -bool Logic::process_app(app_t& app) { - // Check if app hasn't already been verified. - // If yes then just try to display popup once again, and go the next app. +bool Logic::process_app(app_t &app) +{ + // Check if app hasn't already been verified. + // If yes then just try to display popup once again, and go the next app. #if POPUP - if (app.verified == app_t::verified_t::NO) { - LogDebug(app.str() << " has been verified before. Popup should be shown."); - return call_ui(app); - } -#endif + if (app.verified == app_t::verified_t::NO) { + LogDebug(app.str() << " has been verified before. Popup should be shown."); + return call_ui(app); + } - Certs::ocsp_response_t ret; - ret = m_certs.check_ocsp(app); - - // If OCSP returns success or OCSP checking fails we should remove application from buffer and database - if (ret == Certs::ocsp_response_t::OCSP_APP_OK || - ret == Certs::ocsp_response_t::OCSP_CERT_ERROR) { - LogDebug(app.str() << " OCSP verified (or not available for app's chains)"); - return true; - } - else if (ret == Certs::ocsp_response_t::OCSP_APP_REVOKED) { - LogDebug(app.str() << " certificate has been revoked. Popup should be shown"); - app.verified = app_t::verified_t::NO; +#endif + Certs::ocsp_response_t ret; + ret = m_certs.check_ocsp(app); + + // If OCSP returns success or OCSP checking fails we should remove application from buffer and database + if (ret == Certs::ocsp_response_t::OCSP_APP_OK || + ret == Certs::ocsp_response_t::OCSP_CERT_ERROR) { + LogDebug(app.str() << " OCSP verified (or not available for app's chains)"); + return true; + } else if (ret == Certs::ocsp_response_t::OCSP_APP_REVOKED) { + LogDebug(app.str() << " certificate has been revoked. Popup should be shown"); + app.verified = app_t::verified_t::NO; #if POPUP -// Do not remove app here - just waits for user answer from popup - return call_ui(app); + // Do not remove app here - just waits for user answer from popup + return call_ui(app); #else - return true; + return true; #endif - } - else { - LogDebug(app.str() << " should be checked again later"); - // If check_ocsp returns Certs::ocsp_response_t::OCSP_CHECK_AGAIN - // app should be checked again later - } - return false; + } else { + LogDebug(app.str() << " should be checked again later"); + // If check_ocsp returns Certs::ocsp_response_t::OCSP_CHECK_AGAIN + // app should be checked again later + } + + return false; } void Logic::process_buffer(void) { - for (auto iter = m_buffer.begin(); iter != m_buffer.end();) { - bool remove = process_app(*iter); - auto prev = *iter; - iter++; - if (remove) - remove_app_from_buffer_and_database(prev); - app_processed(); - } + for (auto iter = m_buffer.begin(); iter != m_buffer.end();) { + bool remove = process_app(*iter); + auto prev = *iter; + iter++; + + if (remove) + remove_app_from_buffer_and_database(prev); + + app_processed(); + } } void Logic::push_event(event_t event) { - std::lock_guard<std::mutex> lock(m_mutex_cv); - m_queue.push_event(std::move(event)); - LogDebug("Notify thread : pkgmgr event added"); - m_to_process.notify_one(); + std::lock_guard<std::mutex> lock(m_mutex_cv); + m_queue.push_event(std::move(event)); + LogDebug("Notify thread : pkgmgr event added"); + m_to_process.notify_one(); } void Logic::process_all() { - LogInfo("[thread] Start to process event."); - for(;;) { - std::unique_lock<std::mutex> lock(m_mutex_cv); - - // Wait condition. - if(m_queue.empty() && !m_is_online_enabled) { - LogDebug("[thread] wait condition <queue, Network> : " - << !m_queue.empty() << ", " << get_online()); - m_to_process.wait(lock); // spurious wakeups do not concern us - - LogDebug("[thread] wake up! running stage"); - m_is_first_run = true; - } - - // Value for prevent infinite loop. - m_is_online_enabled = false; - // Move event data from queue to buffer & database. - process_queue(); - - lock.unlock(); - - if (get_online() && !m_buffer.empty()) { - - process_buffer(); - - // This is for OCSP_CHECK_AGAIN case. - if(m_buffer.empty()) { - LogInfo("[thread] Finish processing event."); - g_main_loop_quit(m_loop); - break; - } else { - LogDebug("[thread] Check again : " << m_buffer.size()); - // Timer running periodically - timerStart(TIMEOUT_TIMER); - } - } else if (!get_online()) { - LogDebug("[thread] No network. Buffer won't be processed."); - } else { - LogDebug("[thread] No event since cert-checker started."); - } - - if (m_should_exit) - break; - } + LogInfo("[thread] Start to process event."); + + for (;;) { + std::unique_lock<std::mutex> lock(m_mutex_cv); + + // Wait condition. + if (m_queue.empty() && !m_is_online_enabled) { + LogDebug("[thread] wait condition <queue, Network> : " + << !m_queue.empty() << ", " << get_online()); + m_to_process.wait(lock); // spurious wakeups do not concern us + LogDebug("[thread] wake up! running stage"); + m_is_first_run = true; + } + + // Value for prevent infinite loop. + m_is_online_enabled = false; + // Move event data from queue to buffer & database. + process_queue(); + lock.unlock(); + + if (get_online() && !m_buffer.empty()) { + process_buffer(); + + // This is for OCSP_CHECK_AGAIN case. + if (m_buffer.empty()) { + LogInfo("[thread] Finish processing event."); + g_main_loop_quit(m_loop); + break; + } else { + LogDebug("[thread] Check again : " << m_buffer.size()); + // Timer running periodically + timerStart(TIMEOUT_TIMER); + } + } else if (!get_online()) { + LogDebug("[thread] No network. Buffer won't be processed."); + } else { + LogDebug("[thread] No event since cert-checker started."); + } + + if (m_should_exit) + break; + } } void Logic::job(void) { - std::lock_guard<std::mutex> lock(m_mutex_cv); - - if (m_buffer.empty()) { - LogDebug("[timer] Buffer is empty."); - timerStop(); - } else { - LogDebug("[timer] Notify thread - periodic wakeup"); - m_to_process.notify_one(); - } + std::lock_guard<std::mutex> lock(m_mutex_cv); + + if (m_buffer.empty()) { + LogDebug("[timer] Buffer is empty."); + timerStop(); + } else { + LogDebug("[timer] Notify thread - periodic wakeup"); + m_to_process.notify_one(); + } } void Logic::process_event(const event_t &event) { - LogDebug("Move event from queue to (buffer and db)."); - if (event.event_type == event_t::event_type_t::APP_INSTALL) { - // pulling out certificates from signatures - app_t app = event.app; - m_certs.get_certificates(app); - add_app_to_buffer_and_database(app); - } - else if (event.event_type == event_t::event_type_t::APP_UNINSTALL) { - remove_app_from_buffer_and_database(event.app); - } - else - LogError("Unknown event type"); + LogDebug("Move event from queue to (buffer and db)."); + + if (event.event_type == event_t::event_type_t::APP_INSTALL) { + // pulling out certificates from signatures + app_t app = event.app; + m_certs.get_certificates(app); + add_app_to_buffer_and_database(app); + } else if (event.event_type == event_t::event_type_t::APP_UNINSTALL) { + remove_app_from_buffer_and_database(event.app); + } else { + LogError("Unknown event type"); + } } void Logic::add_app_to_buffer_and_database(const app_t &app) { - // First add app to DB - if(!m_sqlquery->add_app_to_check_list(app)) { - LogError("Failed to add " << app.str() << "to database"); - // We can do nothing about it. We can only log the error. - } - - // Then add app to buffer - skip if already added. - // FIXME: What to do if the same app will be installed twice? - // Add it twice to the buffer, or check if apps in buffer are unique? - // At the moment doubled apps are skipped. - for (auto &iter : m_buffer) { - if (iter.app_id == app.app_id && - iter.pkg_id == app.pkg_id && - iter.uid == app.uid) { - LogDebug(app.str() << " already in buffer. Skip."); - return; - } - } - - // Then add app to buffer - m_buffer.push_back(app); + // First add app to DB + if (!m_sqlquery->add_app_to_check_list(app)) { + LogError("Failed to add " << app.str() << "to database"); + // We can do nothing about it. We can only log the error. + } + + // Then add app to buffer - skip if already added. + // FIXME: What to do if the same app will be installed twice? + // Add it twice to the buffer, or check if apps in buffer are unique? + // At the moment doubled apps are skipped. + for (auto &iter : m_buffer) { + if (iter.app_id == app.app_id && + iter.pkg_id == app.pkg_id && + iter.uid == app.uid) { + LogDebug(app.str() << " already in buffer. Skip."); + return; + } + } + + // Then add app to buffer + m_buffer.push_back(app); } // Notice that this operator doesn't compare list of certificate, because it isn't needed here. @@ -658,45 +653,44 @@ void Logic::add_app_to_buffer_and_database(const app_t &app) // Operator which compares certificates is implemented in tests. bool operator ==(const app_t &app1, const app_t &app2) { - return app1.app_id == app2.app_id && - app1.pkg_id == app2.pkg_id && - app1.uid == app2.uid; + return app1.app_id == app2.app_id && + app1.pkg_id == app2.pkg_id && + app1.uid == app2.uid; } void Logic::remove_app_from_buffer_and_database(const app_t &app) { - // First remove app from DB - m_sqlquery->remove_app_from_check_list(app); - - // Then remove app from buffer - m_buffer.remove(app); + // First remove app from DB + m_sqlquery->remove_app_from_check_list(app); + // Then remove app from buffer + m_buffer.remove(app); } bool Logic::get_should_exit(void) const { - return m_should_exit; + return m_should_exit; } void Logic::set_should_exit(void) { - m_should_exit = true; + m_should_exit = true; } std::atomic<bool> Logic::m_is_first_run(false); bool Logic::is_running() { - return g_main_loop_is_running(m_loop); + return g_main_loop_is_running(m_loop); } gboolean Logic::timeout_cb(gpointer data) { - if (!m_is_first_run) { - LogDebug("No event Since cchecker launched. timeout."); - g_main_loop_quit(static_cast<GMainLoop *>(data)); - } + if (!m_is_first_run) { + LogDebug("No event Since cchecker launched. timeout."); + g_main_loop_quit(static_cast<GMainLoop *>(data)); + } - return FALSE; + return FALSE; } } // namespace CCHECKER diff --git a/src/service/logic.h b/src/service/logic.h index e2d5fd7..eedd2e4 100644 --- a/src/service/logic.h +++ b/src/service/logic.h @@ -51,119 +51,118 @@ class SqlQuery; } // namespace DB enum error_t { - NO_ERROR, - REGISTER_CALLBACK_ERROR, - DBUS_ERROR, - PACKAGE_MANAGER_ERROR, - DATABASE_ERROR, - INTERNAL_ERROR + NO_ERROR, + REGISTER_CALLBACK_ERROR, + DBUS_ERROR, + PACKAGE_MANAGER_ERROR, + DATABASE_ERROR, + INTERNAL_ERROR }; enum pkgmgr_event_t { - EVENT_INSTALL, - EVENT_UNINSTALL + EVENT_INSTALL, + EVENT_UNINSTALL }; class Logic : public Timer { - public: - Logic(void); - virtual ~Logic(void); - error_t setup(void); - void run(guint timeout); - bool is_running(); - virtual void clean(void); - - static void connman_callback(GDBusProxy *proxy, - gchar *sender_name, - gchar *signal_name, - GVariant *parameters, - void *logic_ptr); - - protected: - // Timer function - void job(void) override; - - virtual void process_event(const event_t &event); - virtual void app_processed() {}; // for tests - void set_should_exit(void); - void push_event(event_t event); - void set_online(bool online); - - std::list<app_t> m_buffer; - std::condition_variable m_to_process; - std::mutex m_mutex_cv; - std::thread m_thread; - - private: - error_t setup_db(); - void load_database_to_buffer(); - void add_app_to_buffer_and_database(const app_t &app); - void remove_app_from_buffer_and_database(const app_t &app); - - void set_connman_online_state(); - error_t register_dbus_signal_handler(GDBusProxy **proxy, - const char *name, - const char *object_path, - const char *interface_name, - void (*callback) (GDBusProxy *proxy, - gchar *sender_name, - gchar *signal_name, - GVariant *parameters, - void *logic_ptr) - ); - bool get_online(void) const; - - static int pkgmgrinfo_event_handler_static( - uid_t uid, - int reqid, - const char *pkgtype, - const char *pkgid, - const char *key, - const char *val, - const void *pmsg, - void *data); - int pkgmgrinfo_event_handler( - uid_t uid, - int reqid, - const char *pkgtype, - const char *pkgid, - const char *key, - const char *val, - const void *pmsg, - void *data); - int push_pkgmgrinfo_event(uid_t uid, const char *pkgid); - - void process_all(void); - void process_queue(void); - bool process_app(app_t& app); - void process_buffer(void); - bool get_should_exit(void) const; - - bool call_ui(const app_t &app); - - static gboolean timeout_cb(gpointer data); - - // main event loop data type - GMainLoop *m_loop; - - Queue m_queue; - Certs m_certs; - DB::SqlQuery *m_sqlquery; - bool m_was_setup_called; - - bool m_is_online; - // TODO: use m_queue for online events - bool m_is_online_enabled; - bool m_should_exit; - static std::atomic<bool> m_is_first_run; - - GDBusProxy *m_proxy_connman; - - // about pkgmgr event - int m_reqid_install; - int m_reqid_uninstall; - std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> m_pc_install; - std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> m_pc_uninstall; +public: + Logic(void); + virtual ~Logic(void); + error_t setup(void); + void run(guint timeout); + bool is_running(); + virtual void clean(void); + + static void connman_callback(GDBusProxy *proxy, + gchar *sender_name, + gchar *signal_name, + GVariant *parameters, + void *logic_ptr); + +protected: + // Timer function + void job(void) override; + + virtual void process_event(const event_t &event); + virtual void app_processed() {}; // for tests + void set_should_exit(void); + void push_event(event_t event); + void set_online(bool online); + + std::list<app_t> m_buffer; + std::condition_variable m_to_process; + std::mutex m_mutex_cv; + std::thread m_thread; + +private: + error_t setup_db(); + void load_database_to_buffer(); + void add_app_to_buffer_and_database(const app_t &app); + void remove_app_from_buffer_and_database(const app_t &app); + + void set_connman_online_state(); + error_t register_dbus_signal_handler(GDBusProxy **proxy, + const char *name, + const char *object_path, + const char *interface_name, + void (*callback)(GDBusProxy *proxy, + gchar *sender_name, + gchar *signal_name, + GVariant *parameters, + void *logic_ptr)); + bool get_online(void) const; + + static int pkgmgrinfo_event_handler_static( + uid_t uid, + int reqid, + const char *pkgtype, + const char *pkgid, + const char *key, + const char *val, + const void *pmsg, + void *data); + int pkgmgrinfo_event_handler( + uid_t uid, + int reqid, + const char *pkgtype, + const char *pkgid, + const char *key, + const char *val, + const void *pmsg, + void *data); + int push_pkgmgrinfo_event(uid_t uid, const char *pkgid); + + void process_all(void); + void process_queue(void); + bool process_app(app_t &app); + void process_buffer(void); + bool get_should_exit(void) const; + + bool call_ui(const app_t &app); + + static gboolean timeout_cb(gpointer data); + + // main event loop data type + GMainLoop *m_loop; + + Queue m_queue; + Certs m_certs; + DB::SqlQuery *m_sqlquery; + bool m_was_setup_called; + + bool m_is_online; + // TODO: use m_queue for online events + bool m_is_online_enabled; + bool m_should_exit; + static std::atomic<bool> m_is_first_run; + + GDBusProxy *m_proxy_connman; + + // about pkgmgr event + int m_reqid_install; + int m_reqid_uninstall; + std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> m_pc_install; + std::unique_ptr<pkgmgrinfo_client, int(*)(pkgmgrinfo_client *)> m_pc_uninstall; }; } // namespace CCHECKER diff --git a/src/service/ocsp-service.cpp b/src/service/ocsp-service.cpp index 5d6997d..398deb2 100644 --- a/src/service/ocsp-service.cpp +++ b/src/service/ocsp-service.cpp @@ -33,7 +33,7 @@ OcspService::OcspService(const std::string &address) : OcspService::~OcspService() { - if(m_thread.joinable()) + if (m_thread.joinable()) m_thread.join(); } @@ -46,13 +46,12 @@ void OcspService::run(void) void OcspService::onMessageProcess(const ConnShPtr &connection) { LogDebug("Start to process message on ocsp service."); - auto in = connection->receive(); connection->send(this->process(connection, in)); // Run gmainloop for event listening. - if(!m_logic.is_running()) - m_thread = std::thread(&OcspService::run,this); + if (!m_logic.is_running()) + m_thread = std::thread(&OcspService::run, this); LogDebug("Finish processing message on ocsp service."); } @@ -61,11 +60,10 @@ RawBuffer OcspService::process(const ConnShPtr &, RawBuffer &data) { BinaryQueue q; q.push(data); - CommandId cid; q.Deserialize(cid); - LogInfo("Request dispatch on ocsp-service."); + switch (cid) { case CommandId::CC_OCSP_SYN: { if (m_logic.setup() != NO_ERROR) { @@ -76,6 +74,7 @@ RawBuffer OcspService::process(const ConnShPtr &, RawBuffer &data) LogDebug("Success to receive SYN and setup. reply ACK cmd."); return BinaryQueue::Serialize(CommandId::CC_OCSP_ACK).pop(); } + case CommandId::CC_OCSP_ACK: default: throw std::logic_error("Protocol error. unknown command id."); diff --git a/src/service/queue.cpp b/src/service/queue.cpp index 1ae4f1b..06f6268 100644 --- a/src/service/queue.cpp +++ b/src/service/queue.cpp @@ -27,35 +27,36 @@ namespace CCHECKER { event_t::event_t(): - event_type(event_type_t::EVENT_TYPE_UNKNOWN), - app() + event_type(event_type_t::EVENT_TYPE_UNKNOWN), + app() {} event_t::event_t(const app_t &app, event_type_t type): - event_type(type), - app(app) + event_type(type), + app(app) {} void Queue::push_event(const event_t &event) { - std::lock_guard<std::mutex> lock(m_mutex); - m_event_list.push(event); + std::lock_guard<std::mutex> lock(m_mutex); + m_event_list.push(event); } bool Queue::pop_event(event_t &event) { - std::lock_guard<std::mutex> lock(m_mutex); - if (m_event_list.empty()) - return false; + std::lock_guard<std::mutex> lock(m_mutex); - event = std::move(m_event_list.front()); - m_event_list.pop(); - return true; + if (m_event_list.empty()) + return false; + + event = std::move(m_event_list.front()); + m_event_list.pop(); + return true; } bool Queue::empty() { - return m_event_list.empty(); + return m_event_list.empty(); } } //CCHECKER diff --git a/src/service/queue.h b/src/service/queue.h index 9c3eaae..c5ec0d9 100644 --- a/src/service/queue.h +++ b/src/service/queue.h @@ -31,28 +31,28 @@ namespace CCHECKER { struct event_t { - enum class event_type_t { - APP_INSTALL, - APP_UNINSTALL, - EVENT_TYPE_UNKNOWN - }; + enum class event_type_t { + APP_INSTALL, + APP_UNINSTALL, + EVENT_TYPE_UNKNOWN + }; - event_type_t event_type; - app_t app; + event_type_t event_type; + app_t app; - event_t(); - event_t(const app_t &app, event_type_t type); + event_t(); + event_t(const app_t &app, event_type_t type); }; class Queue { - public: - void push_event(const event_t &event); - bool pop_event(event_t &event); - bool empty(); - - private: - std::mutex m_mutex; - std::queue<event_t> m_event_list; +public: + void push_event(const event_t &event); + bool pop_event(event_t &event); + bool empty(); + +private: + std::mutex m_mutex; + std::queue<event_t> m_event_list; }; } // CCHECKER diff --git a/src/ui/UIBackend.cpp b/src/ui/UIBackend.cpp index bb15e34..3bd0663 100644 --- a/src/ui/UIBackend.cpp +++ b/src/ui/UIBackend.cpp @@ -29,7 +29,7 @@ namespace CCHECKER { namespace UI { UIBackend::UIBackend(int timeout) : - m_responseTimeout(timeout) + m_responseTimeout(timeout) {} UIBackend::~UIBackend() @@ -37,34 +37,35 @@ UIBackend::~UIBackend() response_e UIBackend::run(const app_t &app) { - return run_popup(app, m_responseTimeout); + return run_popup(app, m_responseTimeout); } bool UIBackend::call_popup(const app_t &app) { - response_e resp; + response_e resp; + resp = run(app); + LogDebug(app.str() << " response: " << resp); - resp = run(app); - LogDebug(app.str() << " response: " << resp); - if (resp == response_e::RESPONSE_ERROR) { - return false; - } + if (resp == response_e::RESPONSE_ERROR) { + return false; + } else if (resp == response_e::UNINSTALL) { + app_control_h service = NULL; + int result = 0; + result = app_control_create(&service); - else if (resp == response_e::UNINSTALL) { - app_control_h service = NULL; - int result = 0; - result = app_control_create(&service); - if (!service || result != APP_CONTROL_ERROR_NONE) { - return false; - } - app_control_set_operation(service, APP_CONTROL_OPERATION_DEFAULT); - app_control_set_app_id(service, "setting-manage-applications-efl"); - app_control_add_extra_data(service, "viewtype", "application-info"); - app_control_add_extra_data(service, "pkgname", app.pkg_id.c_str()); - app_control_send_launch_request(service, NULL, NULL); - app_control_destroy(service); - } - return true; + if (!service || result != APP_CONTROL_ERROR_NONE) { + return false; + } + + app_control_set_operation(service, APP_CONTROL_OPERATION_DEFAULT); + app_control_set_app_id(service, "setting-manage-applications-efl"); + app_control_add_extra_data(service, "viewtype", "application-info"); + app_control_add_extra_data(service, "pkgname", app.pkg_id.c_str()); + app_control_send_launch_request(service, NULL, NULL); + app_control_destroy(service); + } + + return true; } } // UI diff --git a/src/ui/popup-bin/popup.cpp b/src/ui/popup-bin/popup.cpp index b9381af..b3256b1 100644 --- a/src/ui/popup-bin/popup.cpp +++ b/src/ui/popup-bin/popup.cpp @@ -41,171 +41,162 @@ using namespace CCHECKER::UI; namespace { // anonymous -void on_done(void) { - // Quit the efl-mainloop - LogDebug("elm_exit()"); - elm_exit(); +void on_done(void) +{ + // Quit the efl-mainloop + LogDebug("elm_exit()"); + elm_exit(); } -void keep_answer(void *data, Evas_Object * /* obj */, void * /* event_info */) { +void keep_answer(void *data, Evas_Object * /* obj */, void * /* event_info */) +{ + LogDebug("keep_answer"); + + if (NULL == data) { + LogError("data is NULL; return"); + return; + } - LogDebug("keep_answer"); - if(NULL == data){ - LogError("data is NULL; return"); - return; - } - struct cert_checker_popup_data *pdp = static_cast <struct cert_checker_popup_data *> (data); - pdp->result = response_e::DONT_UNINSTALL; + struct cert_checker_popup_data *pdp = static_cast <struct cert_checker_popup_data *>(data); - on_done(); + pdp->result = response_e::DONT_UNINSTALL; + + on_done(); } -void uninstall_answer(void *data, Evas_Object * /* obj */, void * /* event_info */) { +void uninstall_answer(void *data, Evas_Object * /* obj */, void * /* event_info */) +{ + LogDebug("uninstall_answer"); - LogDebug("uninstall_answer"); - if(NULL == data){ - LogError("data is NULL; return"); - return; - } - struct cert_checker_popup_data *pdp = static_cast <struct cert_checker_popup_data *> (data); - pdp->result = response_e::UNINSTALL; + if (NULL == data) { + LogError("data is NULL; return"); + return; + } - on_done(); -} + struct cert_checker_popup_data *pdp = static_cast <struct cert_checker_popup_data *>(data); -void show_popup(struct cert_checker_popup_data *pdp) { - LogDebug("show_popup()"); - - if(NULL == pdp){ - LogError("pdp is NULL; return"); - return; - } - - pdp->win = elm_win_add(NULL, - dgettext(SERVICE_NAME, "SID_TITLE_OCSP_VERIFICATION_FAILED"), - ELM_WIN_NOTIFICATION); - - elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); - elm_win_autodel_set(pdp->win, EINA_TRUE); - evas_object_show(pdp->win); - elm_win_indicator_opacity_set(pdp->win, ELM_WIN_INDICATOR_TRANSLUCENT); - - pdp->popup = elm_popup_add(pdp->win); - - pdp->box = elm_box_add(pdp->popup); - evas_object_size_hint_weight_set(pdp->box, EVAS_HINT_EXPAND, 0); - evas_object_size_hint_align_set(pdp->box, EVAS_HINT_FILL, 0.0); - - pdp->title = elm_label_add(pdp->popup); - elm_object_style_set(pdp->title, "elm.text.title"); - elm_object_text_set(pdp->title, dgettext(SERVICE_NAME, "SID_TITLE_OCSP_VERIFICATION_FAILED")); - evas_object_show(pdp->title); - elm_box_pack_end(pdp->box, pdp->title); - - pdp->content = elm_label_add(pdp->popup); - elm_object_style_set(pdp->content, "elm.swallow.content"); - elm_label_line_wrap_set(pdp->content, ELM_WRAP_MIXED); - - char *buff = NULL; - int ret; - - // Set message - // App ID may be absent, so in that case we need to use only package ID - if (pdp->app_id == std::string(CCHECKER::TEMP_APP_ID)) { - char *content = dgettext(SERVICE_NAME, "SID_CONTENT_OCSP_PACKAGE VERIFICATION_FAILED"); - ret = asprintf(&buff, content, pdp->pkg_id.c_str()); - } - else { - char *content = dgettext(SERVICE_NAME, "SID_CONTENT_OCSP_VERIFICATION_FAILED"); - ret = asprintf(&buff, content, pdp->app_id.c_str(), pdp->pkg_id.c_str()); - } - - if(-1 == ret){ - LogError("asprintf failed - returned -1"); - evas_object_del(pdp->content); - evas_object_del(pdp->popup); - evas_object_del(pdp->win); - return; - } - elm_object_text_set(pdp->content, buff); - LogDebug("Popup label: " << buff); - free(buff); - evas_object_size_hint_weight_set(pdp->content, EVAS_HINT_EXPAND, 0.0); - evas_object_size_hint_align_set(pdp->content, EVAS_HINT_FILL, EVAS_HINT_FILL); - evas_object_show(pdp->content); - elm_box_pack_end(pdp->box, pdp->content); - - elm_object_part_content_set(pdp->popup, "default", pdp->box); - - pdp->keep_button = elm_button_add(pdp->popup); - elm_object_style_set(pdp->keep_button, "elm.swallow.content.button1"); - elm_object_text_set(pdp->keep_button, dgettext(SERVICE_NAME, "SID_BTN_OCSP_KEEP_APP")); - elm_object_part_content_set(pdp->popup, "button1", pdp->keep_button); - evas_object_smart_callback_add(pdp->keep_button, "clicked", keep_answer, pdp); - - pdp->uninstall_button = elm_button_add(pdp->popup); - elm_object_style_set(pdp->uninstall_button, "elm.swallow.content.button2"); - elm_object_text_set(pdp->uninstall_button, dgettext(SERVICE_NAME, "SID_BTN_OCSP_UNINSTALL_APP")); - elm_object_part_content_set(pdp->popup, "button2 ", pdp->uninstall_button); - evas_object_smart_callback_add(pdp->uninstall_button, "clicked", uninstall_answer, pdp); - - evas_object_show(pdp->popup); - - // Showing the popup window - evas_object_show(pdp->win); - - // Run the efl mainloop - elm_run(); - - // Shutdown elementary - LogDebug("elm_shutdown()"); - elm_shutdown(); + pdp->result = response_e::UNINSTALL; + + on_done(); } -static int wait_for_parent_info (int pipe_in) +void show_popup(struct cert_checker_popup_data *pdp) { - // wait for parameters from pipe_in - // timeout is set for 10 seconds - struct timeval timeout = {10L, 0L}; - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(pipe_in, &readfds); - - int sel = select(pipe_in + 1, &readfds, NULL, NULL, &timeout); - if (sel == -1) { - int error = errno; - LogError("Cannot get info from parent. Exit popup"); - LogError("Error: " << CCHECKER::GetErrnoString(error)); - close(pipe_in); - return -1; - } - else if (sel == 0) { - LogError("Timeout reached! Exit popup - ERROR"); - close(pipe_in); - return -1; - } - return 0; + LogDebug("show_popup()"); + + if (NULL == pdp) { + LogError("pdp is NULL; return"); + return; + } + + pdp->win = elm_win_add(NULL, + dgettext(SERVICE_NAME, "SID_TITLE_OCSP_VERIFICATION_FAILED"), + ELM_WIN_NOTIFICATION); + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + elm_win_autodel_set(pdp->win, EINA_TRUE); + evas_object_show(pdp->win); + elm_win_indicator_opacity_set(pdp->win, ELM_WIN_INDICATOR_TRANSLUCENT); + pdp->popup = elm_popup_add(pdp->win); + pdp->box = elm_box_add(pdp->popup); + evas_object_size_hint_weight_set(pdp->box, EVAS_HINT_EXPAND, 0); + evas_object_size_hint_align_set(pdp->box, EVAS_HINT_FILL, 0.0); + pdp->title = elm_label_add(pdp->popup); + elm_object_style_set(pdp->title, "elm.text.title"); + elm_object_text_set(pdp->title, dgettext(SERVICE_NAME, "SID_TITLE_OCSP_VERIFICATION_FAILED")); + evas_object_show(pdp->title); + elm_box_pack_end(pdp->box, pdp->title); + pdp->content = elm_label_add(pdp->popup); + elm_object_style_set(pdp->content, "elm.swallow.content"); + elm_label_line_wrap_set(pdp->content, ELM_WRAP_MIXED); + char *buff = NULL; + int ret; + + // Set message + // App ID may be absent, so in that case we need to use only package ID + if (pdp->app_id == std::string(CCHECKER::TEMP_APP_ID)) { + char *content = dgettext(SERVICE_NAME, "SID_CONTENT_OCSP_PACKAGE VERIFICATION_FAILED"); + ret = asprintf(&buff, content, pdp->pkg_id.c_str()); + } else { + char *content = dgettext(SERVICE_NAME, "SID_CONTENT_OCSP_VERIFICATION_FAILED"); + ret = asprintf(&buff, content, pdp->app_id.c_str(), pdp->pkg_id.c_str()); + } + + if (-1 == ret) { + LogError("asprintf failed - returned -1"); + evas_object_del(pdp->content); + evas_object_del(pdp->popup); + evas_object_del(pdp->win); + return; + } + + elm_object_text_set(pdp->content, buff); + LogDebug("Popup label: " << buff); + free(buff); + evas_object_size_hint_weight_set(pdp->content, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(pdp->content, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(pdp->content); + elm_box_pack_end(pdp->box, pdp->content); + elm_object_part_content_set(pdp->popup, "default", pdp->box); + pdp->keep_button = elm_button_add(pdp->popup); + elm_object_style_set(pdp->keep_button, "elm.swallow.content.button1"); + elm_object_text_set(pdp->keep_button, dgettext(SERVICE_NAME, "SID_BTN_OCSP_KEEP_APP")); + elm_object_part_content_set(pdp->popup, "button1", pdp->keep_button); + evas_object_smart_callback_add(pdp->keep_button, "clicked", keep_answer, pdp); + pdp->uninstall_button = elm_button_add(pdp->popup); + elm_object_style_set(pdp->uninstall_button, "elm.swallow.content.button2"); + elm_object_text_set(pdp->uninstall_button, dgettext(SERVICE_NAME, "SID_BTN_OCSP_UNINSTALL_APP")); + elm_object_part_content_set(pdp->popup, "button2 ", pdp->uninstall_button); + evas_object_smart_callback_add(pdp->uninstall_button, "clicked", uninstall_answer, pdp); + evas_object_show(pdp->popup); + // Showing the popup window + evas_object_show(pdp->win); + // Run the efl mainloop + elm_run(); + // Shutdown elementary + LogDebug("elm_shutdown()"); + elm_shutdown(); } -void deserialize (cert_checker_popup_data *pdp, char *line, ssize_t line_length) +static int wait_for_parent_info(int pipe_in) { - BinaryStream stream; - stream.Write(line_length, static_cast <void *> (line)); - - std::string app_id; - std::string pkg_id; - - LogDebug("------- Deserialization -------"); - // Deserialization order: - // app_id, pkg_id - - CCHECKER::Deserialization::Deserialize(stream, app_id); - LogDebug("app_id : " << app_id.c_str()); - pdp->app_id = app_id.c_str(); + // wait for parameters from pipe_in + // timeout is set for 10 seconds + struct timeval timeout = {10L, 0L}; + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(pipe_in, &readfds); + int sel = select(pipe_in + 1, &readfds, NULL, NULL, &timeout); + + if (sel == -1) { + int error = errno; + LogError("Cannot get info from parent. Exit popup"); + LogError("Error: " << CCHECKER::GetErrnoString(error)); + close(pipe_in); + return -1; + } else if (sel == 0) { + LogError("Timeout reached! Exit popup - ERROR"); + close(pipe_in); + return -1; + } + + return 0; +} - CCHECKER::Deserialization::Deserialize(stream, pkg_id); - LogDebug("pkg_id : " << pkg_id.c_str()); - pdp->pkg_id = pkg_id.c_str(); +void deserialize(cert_checker_popup_data *pdp, char *line, ssize_t line_length) +{ + BinaryStream stream; + stream.Write(line_length, static_cast <void *>(line)); + std::string app_id; + std::string pkg_id; + LogDebug("------- Deserialization -------"); + // Deserialization order: + // app_id, pkg_id + CCHECKER::Deserialization::Deserialize(stream, app_id); + LogDebug("app_id : " << app_id.c_str()); + pdp->app_id = app_id.c_str(); + CCHECKER::Deserialization::Deserialize(stream, pkg_id); + LogDebug("pkg_id : " << pkg_id.c_str()); + pdp->pkg_id = pkg_id.c_str(); } } // anonymous @@ -213,88 +204,81 @@ void deserialize (cert_checker_popup_data *pdp, char *line, ssize_t line_length) EAPI_MAIN int elm_main(int argc, char **argv) { - // int pipe_in and int pipe_out should be passed to Popup via args. - - // These parameters should be passed to Popup via pipe_in: - // std::string app_id - // std::string pkg_id - - struct cert_checker_popup_data pd; - struct cert_checker_popup_data *pdp = &pd; - - LogDebug("############################ popup binary ################################"); - - setlocale(LC_ALL, ""); - - if(argc < 3){ - LogError("To few args passed in exec to popup-bin - should be at least 3:"); - LogError("(binary-name, pipe_in, pipe_out)"); - LogError("return ERROR"); - return popup_status::EXIT_ERROR; - } - - LogDebug("Passed args: " << argv[0] <<", " << argv[1] << ", " << argv[2]); - - int pipe_in; - int pipe_out; - - // Parsing args (pipe_in, pipe_out) - if ( 0 == sscanf(argv[1], "%d", &pipe_in) ){ - LogError("Error while parsing pipe_in; return ERROR"); - return popup_status::EXIT_ERROR; - } - if ( 0 == sscanf(argv[2], "%d", &pipe_out) ){ - LogError("Error while parsing pipe_out; return ERROR"); - return popup_status::EXIT_ERROR; - } - LogDebug("Parsed pipes: IN: " << pipe_in <<", OUT: " << pipe_out); - - if (wait_for_parent_info(pipe_in) == -1) { - close(pipe_out); - return popup_status::EXIT_ERROR; - } - - int buff_size = 1024; - char line[buff_size]; - - ssize_t count = 0; - - do { - count = TEMP_FAILURE_RETRY(read(pipe_in, line, buff_size)); - } while (0 == count); - if(count < 0){ - int error = errno; - close(pipe_in); - close(pipe_out); - LogError("read returned a negative value (" << count <<")"); - LogError("error: " << CCHECKER::GetErrnoString(error)); - LogError("Exit popup - ERROR"); - return popup_status::EXIT_ERROR; - } - LogDebug("Read bytes : " << count); - close(pipe_in); // cleanup - - deserialize(pdp, line, count); - - pdp->result = response_e::RESPONSE_ERROR; - - show_popup(pdp); // Showing popup - - // sending validation_result to popup-runner - BinaryStream stream_out; - - LogDebug("pdp->result : " << pdp->result); - CCHECKER::Serialization::Serialize(stream_out, pdp->result); - if(-1 == TEMP_FAILURE_RETRY(write(pipe_out, stream_out.char_pointer(), stream_out.size()))){ - LogError("Write to pipe failed!"); - close(pipe_out); - return popup_status::EXIT_ERROR; - } - - close(pipe_out); - - LogDebug("############################ /popup binary ################################"); - LogDebug("Return: " << popup_status::NO_ERROR); - return popup_status::NO_ERROR; + // int pipe_in and int pipe_out should be passed to Popup via args. + // These parameters should be passed to Popup via pipe_in: + // std::string app_id + // std::string pkg_id + struct cert_checker_popup_data pd; + struct cert_checker_popup_data *pdp = &pd; + LogDebug("############################ popup binary ################################"); + setlocale(LC_ALL, ""); + + if (argc < 3) { + LogError("To few args passed in exec to popup-bin - should be at least 3:"); + LogError("(binary-name, pipe_in, pipe_out)"); + LogError("return ERROR"); + return popup_status::EXIT_ERROR; + } + + LogDebug("Passed args: " << argv[0] << ", " << argv[1] << ", " << argv[2]); + int pipe_in; + int pipe_out; + + // Parsing args (pipe_in, pipe_out) + if (0 == sscanf(argv[1], "%d", &pipe_in)) { + LogError("Error while parsing pipe_in; return ERROR"); + return popup_status::EXIT_ERROR; + } + + if (0 == sscanf(argv[2], "%d", &pipe_out)) { + LogError("Error while parsing pipe_out; return ERROR"); + return popup_status::EXIT_ERROR; + } + + LogDebug("Parsed pipes: IN: " << pipe_in << ", OUT: " << pipe_out); + + if (wait_for_parent_info(pipe_in) == -1) { + close(pipe_out); + return popup_status::EXIT_ERROR; + } + + int buff_size = 1024; + char line[buff_size]; + ssize_t count = 0; + + do { + count = TEMP_FAILURE_RETRY(read(pipe_in, line, buff_size)); + } while (0 == count); + + if (count < 0) { + int error = errno; + close(pipe_in); + close(pipe_out); + LogError("read returned a negative value (" << count << ")"); + LogError("error: " << CCHECKER::GetErrnoString(error)); + LogError("Exit popup - ERROR"); + return popup_status::EXIT_ERROR; + } + + LogDebug("Read bytes : " << count); + close(pipe_in); // cleanup + deserialize(pdp, line, count); + pdp->result = response_e::RESPONSE_ERROR; + show_popup(pdp); // Showing popup + // sending validation_result to popup-runner + BinaryStream stream_out; + LogDebug("pdp->result : " << pdp->result); + CCHECKER::Serialization::Serialize(stream_out, pdp->result); + + if (-1 == TEMP_FAILURE_RETRY(write(pipe_out, stream_out.char_pointer(), stream_out.size()))) { + LogError("Write to pipe failed!"); + close(pipe_out); + return popup_status::EXIT_ERROR; + } + + close(pipe_out); + LogDebug("############################ /popup binary ################################"); + LogDebug("Return: " << popup_status::NO_ERROR); + return popup_status::NO_ERROR; } ELM_MAIN() diff --git a/src/ui/popup-bin/popup.h b/src/ui/popup-bin/popup.h index 4a5d32a..a9b88b4 100644 --- a/src/ui/popup-bin/popup.h +++ b/src/ui/popup-bin/popup.h @@ -24,15 +24,15 @@ #include <cchecker/UIBackend.h> struct cert_checker_popup_data { - std::string app_id; - std::string pkg_id; - CCHECKER::UI::response_e result; + std::string app_id; + std::string pkg_id; + CCHECKER::UI::response_e result; - Evas_Object *popup = NULL; - Evas_Object *win = NULL; - Evas_Object *box = NULL; - Evas_Object *title = NULL; - Evas_Object *content = NULL; - Evas_Object *keep_button = NULL; - Evas_Object *uninstall_button = NULL; + Evas_Object *popup = NULL; + Evas_Object *win = NULL; + Evas_Object *box = NULL; + Evas_Object *title = NULL; + Evas_Object *content = NULL; + Evas_Object *keep_button = NULL; + Evas_Object *uninstall_button = NULL; }; diff --git a/src/ui/popup-runner.cpp b/src/ui/popup-runner.cpp index 31e3e8f..7c2eb2c 100644 --- a/src/ui/popup-runner.cpp +++ b/src/ui/popup-runner.cpp @@ -39,138 +39,136 @@ namespace { // anonymous using namespace CCHECKER::UI; -const char *POPUP_EXEC = tzplatform_mkpath(TZ_SYS_BIN, "cert-checker-popup"); // check-checker-popup binary +const char *POPUP_EXEC = tzplatform_mkpath(TZ_SYS_BIN, + "cert-checker-popup"); // check-checker-popup binary -std::string response_to_str (response_e response) +std::string response_to_str(response_e response) { - switch (response) { - case response_e::DONT_UNINSTALL: - return "DONT_UNINSTALL"; - case response_e::UNINSTALL: - return "UNINSTALL"; - default: - return "RESPONSE_ERROR"; - } + switch (response) { + case response_e::DONT_UNINSTALL: + return "DONT_UNINSTALL"; + + case response_e::UNINSTALL: + return "UNINSTALL"; + + default: + return "RESPONSE_ERROR"; + } } -int wait_for_popup (int popup_pid, int timeout) +int wait_for_popup(int popup_pid, int timeout) { - int status; - int ret; - - sigset_t set; - sigemptyset(&set); - sigaddset(&set, SIGCHLD); - sigprocmask(SIG_BLOCK, &set, NULL); - siginfo_t info; - struct timespec time = {timeout, 0L}; - - if (timeout > 0) - ret = TEMP_FAILURE_RETRY(sigtimedwait(&set, &info, &time)); - else - ret = TEMP_FAILURE_RETRY(sigwaitinfo(&set, &info)); - - sigprocmask(SIG_UNBLOCK, &set, NULL); - - if (ret == -1 && errno == EAGAIN) { - LogError("POPUP TIMEOUT"); - goto err; - } - else if (ret == SIGCHLD && info.si_pid == popup_pid) { - // call waitpid on the child process to get rid of zombie process - waitpid(popup_pid, NULL, 0); - - // The proper signal has been caught and its pid matches to popup_pid - // Now check the popup exit status - status = WEXITSTATUS(info.si_status); - LogDebug("STATUS EXIT ON POPUP (CHILD: " << info.si_pid << "): " << status); - - switch (static_cast<popup_status>(status)) { - - case popup_status::NO_ERROR: - LogDebug("NO_ERROR"); - return 0; - - case popup_status::EXIT_ERROR: - LogError("ERROR"); - return -1; - - default: // Unknown exit status - LogError("UNKNOWN_ERROR"); - return -1; - } - } - else { - LogError("Some other signal has been caught (pid: " << info.si_pid << ", signal: " << info.si_signo << ")"); - goto err; - } + int status; + int ret; + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGCHLD); + sigprocmask(SIG_BLOCK, &set, NULL); + siginfo_t info; + struct timespec time = {timeout, 0L}; + + if (timeout > 0) + ret = TEMP_FAILURE_RETRY(sigtimedwait(&set, &info, &time)); + else + ret = TEMP_FAILURE_RETRY(sigwaitinfo(&set, &info)); + + sigprocmask(SIG_UNBLOCK, &set, NULL); + + if (ret == -1 && errno == EAGAIN) { + LogError("POPUP TIMEOUT"); + goto err; + } else if (ret == SIGCHLD && info.si_pid == popup_pid) { + // call waitpid on the child process to get rid of zombie process + waitpid(popup_pid, NULL, 0); + // The proper signal has been caught and its pid matches to popup_pid + // Now check the popup exit status + status = WEXITSTATUS(info.si_status); + LogDebug("STATUS EXIT ON POPUP (CHILD: " << info.si_pid << "): " << status); + + switch (static_cast<popup_status>(status)) { + case popup_status::NO_ERROR: + LogDebug("NO_ERROR"); + return 0; + + case popup_status::EXIT_ERROR: + LogError("ERROR"); + return -1; + + default: // Unknown exit status + LogError("UNKNOWN_ERROR"); + return -1; + } + } else { + LogError("Some other signal has been caught (pid: " << info.si_pid << ", signal: " << info.si_signo + << ")"); + goto err; + } err: - // kill popup process and return error - kill(popup_pid, SIGKILL); - - // call waitpid on the child process to get rid of zombie process - waitpid(popup_pid, NULL, 0); - return -1; + // kill popup process and return error + kill(popup_pid, SIGKILL); + // call waitpid on the child process to get rid of zombie process + waitpid(popup_pid, NULL, 0); + return -1; } -void child_process (int fd_send_to_child[2], int fd_send_to_parent[2]) +void child_process(int fd_send_to_child[2], int fd_send_to_parent[2]) { - LogDebug("Child"); - - // read data from parent - close(fd_send_to_child[1]); - - // send data to parent - close(fd_send_to_parent[0]); + LogDebug("Child"); + // read data from parent + close(fd_send_to_child[1]); + // send data to parent + close(fd_send_to_parent[0]); + std::stringstream pipe_in_buff; + std::stringstream pipe_out_buff; + pipe_in_buff << fd_send_to_parent[1]; + pipe_out_buff << fd_send_to_child[0]; + std::string pipe_in = pipe_in_buff.str(); + std::string pipe_out = pipe_out_buff.str(); + LogDebug("Passed file descriptors: " << fd_send_to_child[0] << ", " << fd_send_to_parent[1]); + + if (execl(POPUP_EXEC, POPUP_EXEC, pipe_out.c_str(), pipe_in.c_str(), NULL) < 0) { + LogError("execl FAILED"); + } + + LogError("This should not happen!!!"); + _exit(response_e::RESPONSE_ERROR); +} - std::stringstream pipe_in_buff; - std::stringstream pipe_out_buff; - pipe_in_buff << fd_send_to_parent[1]; - pipe_out_buff << fd_send_to_child[0]; - std::string pipe_in = pipe_in_buff.str(); - std::string pipe_out = pipe_out_buff.str(); +int send_message_to_child(const BinaryStream &stream, int fd_send_to_child) +{ + LogDebug("Sending message to popup-bin process"); + unsigned int begin = 0; + int tmp; - LogDebug("Passed file descriptors: " << fd_send_to_child[0] << ", "<< fd_send_to_parent[1]); + while (begin < stream.size()) { + tmp = TEMP_FAILURE_RETRY(write(fd_send_to_child, + stream.char_pointer() + begin, + stream.size() - begin)); - if (execl(POPUP_EXEC, POPUP_EXEC, pipe_out.c_str(), pipe_in.c_str(), NULL) < 0){ - LogError("execl FAILED"); - } + if (-1 == tmp) { + LogError("Write to pipe failed!"); + return -1; + } - LogError("This should not happen!!!"); - _exit(response_e::RESPONSE_ERROR); -} + begin += tmp; + } -int send_message_to_child(const BinaryStream &stream, int fd_send_to_child) -{ - LogDebug("Sending message to popup-bin process"); - unsigned int begin = 0; - int tmp; - while (begin < stream.size()) { - tmp = TEMP_FAILURE_RETRY(write(fd_send_to_child, - stream.char_pointer() + begin, - stream.size() - begin)); - if(-1 == tmp){ - LogError("Write to pipe failed!"); - return -1; - } - begin += tmp; - } - LogDebug("Message has been sent"); - return 0; + LogDebug("Message has been sent"); + return 0; } -response_e parse_response (int count, char *data) +response_e parse_response(int count, char *data) { - LogDebug("RESULT FROM POPUP PIPE (CHILD) : [ " << count << " ]"); - int response_int; - response_e response; - BinaryStream stream_in; - stream_in.Write(count, data); - CCHECKER::Deserialization::Deserialize(stream_in, response_int); - response = static_cast <response_e> (response_int); - LogDebug("response :" << response_to_str(response)); - return response; + LogDebug("RESULT FROM POPUP PIPE (CHILD) : [ " << count << " ]"); + int response_int; + response_e response; + BinaryStream stream_in; + stream_in.Write(count, data); + CCHECKER::Deserialization::Deserialize(stream_in, response_int); + response = static_cast <response_e>(response_int); + LogDebug("response :" << response_to_str(response)); + return response; } } // anonymous namespace @@ -179,124 +177,123 @@ namespace CCHECKER { namespace UI { // BinaryStream class implementation -void BinaryStream::Read(size_t num, void * bytes) +void BinaryStream::Read(size_t num, void *bytes) { - size_t max_size = m_data.size(); - for (size_t i = 0; i < num; ++i) { - if( i + m_readPosition >= max_size){ - return; - } - static_cast <unsigned char*> (bytes)[i] = m_data[i + m_readPosition]; - } - m_readPosition += num; + size_t max_size = m_data.size(); + + for (size_t i = 0; i < num; ++i) { + if (i + m_readPosition >= max_size) { + return; + } + + static_cast <unsigned char *>(bytes)[i] = m_data[i + m_readPosition]; + } + + m_readPosition += num; } -void BinaryStream::Write(size_t num, const void * bytes) +void BinaryStream::Write(size_t num, const void *bytes) { - for (size_t i = 0; i < num; ++i) { - m_data.push_back(static_cast <const unsigned char*> (bytes)[i]); - } + for (size_t i = 0; i < num; ++i) { + m_data.push_back(static_cast <const unsigned char *>(bytes)[i]); + } } BinaryStream::BinaryStream() : - m_readPosition(0) + m_readPosition(0) {} BinaryStream::~BinaryStream() {} -const unsigned char* BinaryStream::char_pointer() const +const unsigned char *BinaryStream::char_pointer() const { - return &m_data[0]; + return &m_data[0]; } size_t BinaryStream::size() const { - return m_data.size(); + return m_data.size(); } // BinaryStream response_e run_popup( - const app_t &app, - int timeout) + const app_t &app, + int timeout) { - LogDebug(app.str()); - - // serialization - BinaryStream stream; - CCHECKER::Serialization::Serialize(stream, app.app_id); - CCHECKER::Serialization::Serialize(stream, app.pkg_id); - - int fd_send_to_child[2]; - int fd_send_to_parent[2]; - pid_t childpid; - - if(0 != pipe(fd_send_to_child)){ - LogError("Cannot create pipes!"); - return response_e::RESPONSE_ERROR; - } - if(0 != pipe(fd_send_to_parent)){ - LogError("Cannot create pipes!"); - close(fd_send_to_child[0]); - close(fd_send_to_child[1]); - return response_e::RESPONSE_ERROR; - } - - if ((childpid = fork()) == -1) { - LogError("Fork() ERROR"); - close(fd_send_to_child[0]); - close(fd_send_to_parent[1]); - goto error; - } - - if(childpid == 0) { // Child process - child_process (fd_send_to_child, fd_send_to_parent); - } - else { // Parent process - LogDebug("Parent (child pid: " << childpid << ")"); - - // send data to child - close(fd_send_to_child[0]); - - // read data from child - close(fd_send_to_parent[1]); - - // writing to child - if (send_message_to_child(stream, fd_send_to_child[1])) - goto error; - - // wait for child - if (wait_for_popup(childpid, timeout) != 0 ) - goto error; - - // Read message from popup (child) - int buff_size = 1024; - char result[buff_size]; - int count; - count = TEMP_FAILURE_RETRY(read(fd_send_to_parent[0], result, buff_size)); - - // Parsing response from child - response_e response; - if (0 < count) - response = parse_response(count, result); - else { - LogDebug("ERROR, count = " << count);; - goto error; - } - - LogDebug("popup-runner: EXIT SUCCESS"); - // cleanup - close(fd_send_to_parent[0]); - close(fd_send_to_child[1]); - return response; - } - - LogError("This should not happen!!!"); + LogDebug(app.str()); + // serialization + BinaryStream stream; + CCHECKER::Serialization::Serialize(stream, app.app_id); + CCHECKER::Serialization::Serialize(stream, app.pkg_id); + int fd_send_to_child[2]; + int fd_send_to_parent[2]; + pid_t childpid; + + if (0 != pipe(fd_send_to_child)) { + LogError("Cannot create pipes!"); + return response_e::RESPONSE_ERROR; + } + + if (0 != pipe(fd_send_to_parent)) { + LogError("Cannot create pipes!"); + close(fd_send_to_child[0]); + close(fd_send_to_child[1]); + return response_e::RESPONSE_ERROR; + } + + if ((childpid = fork()) == -1) { + LogError("Fork() ERROR"); + close(fd_send_to_child[0]); + close(fd_send_to_parent[1]); + goto error; + } + + if (childpid == 0) { // Child process + child_process(fd_send_to_child, fd_send_to_parent); + } else { // Parent process + LogDebug("Parent (child pid: " << childpid << ")"); + // send data to child + close(fd_send_to_child[0]); + // read data from child + close(fd_send_to_parent[1]); + + // writing to child + if (send_message_to_child(stream, fd_send_to_child[1])) + goto error; + + // wait for child + if (wait_for_popup(childpid, timeout) != 0) + goto error; + + // Read message from popup (child) + int buff_size = 1024; + char result[buff_size]; + int count; + count = TEMP_FAILURE_RETRY(read(fd_send_to_parent[0], result, buff_size)); + // Parsing response from child + response_e response; + + if (0 < count) { + response = parse_response(count, result); + } else { + LogDebug("ERROR, count = " << count);; + goto error; + } + + LogDebug("popup-runner: EXIT SUCCESS"); + // cleanup + close(fd_send_to_parent[0]); + close(fd_send_to_child[1]); + return response; + } + + LogError("This should not happen!!!"); error: - // cleanup - LogDebug("popup-runner: EXIT ERROR"); - close(fd_send_to_parent[0]); - close(fd_send_to_child[1]); - return response_e::RESPONSE_ERROR; + // cleanup + LogDebug("popup-runner: EXIT ERROR"); + close(fd_send_to_parent[0]); + close(fd_send_to_child[1]); + return response_e::RESPONSE_ERROR; } } // UI diff --git a/tests/app_event_operators.cpp b/tests/app_event_operators.cpp index 131e511..e0336e8 100644 --- a/tests/app_event_operators.cpp +++ b/tests/app_event_operators.cpp @@ -29,64 +29,66 @@ namespace CCHECKER { void sort_buffer(std::list<app_t> &buff) { - for (auto &iter : buff) { - sort(iter); - } + for (auto &iter : buff) { + sort(iter); + } - buff.sort(); + buff.sort(); } void sort(app_t &app) { - app.signatures.sort(); + app.signatures.sort(); } // Needed for sort() bool operator < (const app_t &app1, const app_t &app2) { - if (app1.app_id != app2.app_id) - return app1.app_id < app2.app_id; - if (app1.pkg_id != app2.pkg_id) - return app1.pkg_id < app2.pkg_id; - if (app1.uid != app2.uid) - return app1.uid < app2.uid; - - return app1.signatures < app2.signatures; + if (app1.app_id != app2.app_id) + return app1.app_id < app2.app_id; + + if (app1.pkg_id != app2.pkg_id) + return app1.pkg_id < app2.pkg_id; + + if (app1.uid != app2.uid) + return app1.uid < app2.uid; + + return app1.signatures < app2.signatures; } bool operator ==(const app_t &app1, const app_t &app2) { - if (app1.app_id != app2.app_id || - app1.pkg_id != app2.pkg_id || - app1.uid != app2.uid || - app1.signatures.size() != app2.signatures.size() || - app1.verified != app2.verified) { - LogDebug("app_t compare error: " << app1.str() << " is different than: " << app2.str()); - return false; - } - - return app1.signatures == app2.signatures; + if (app1.app_id != app2.app_id || + app1.pkg_id != app2.pkg_id || + app1.uid != app2.uid || + app1.signatures.size() != app2.signatures.size() || + app1.verified != app2.verified) { + LogDebug("app_t compare error: " << app1.str() << " is different than: " << app2.str()); + return false; + } + + return app1.signatures == app2.signatures; } bool operator !=(const app_t &app1, const app_t &app2) { - return !(app1 == app2); + return !(app1 == app2); } bool operator ==(const event_t &event1, const event_t &event2) { - if (event1.event_type != event2.event_type) - return false; + if (event1.event_type != event2.event_type) + return false; - if (event1.app != event2.app) - return false; + if (event1.app != event2.app) + return false; - return true; + return true; } bool operator !=(const event_t &event1, const event_t &event2) { - return !(event1 == event2); + return !(event1 == event2); } } // CHCHECKER diff --git a/tests/certs_.cpp b/tests/certs_.cpp index b63c48b..b20bace 100644 --- a/tests/certs_.cpp +++ b/tests/certs_.cpp @@ -27,7 +27,7 @@ using namespace CCHECKER; Certs_::~Certs_() {} -Certs_::ocsp_response_t Certs_::check_ocsp_chain_ (const chain_t &chain) +Certs_::ocsp_response_t Certs_::check_ocsp_chain_(const chain_t &chain) { - return this->check_ocsp_chain(chain); + return this->check_ocsp_chain(chain); } diff --git a/tests/certs_.h b/tests/certs_.h index 163d299..c5478ee 100644 --- a/tests/certs_.h +++ b/tests/certs_.h @@ -28,9 +28,9 @@ using namespace CCHECKER; class Certs_ : public Certs { - public: - virtual ~Certs_(); - ocsp_response_t check_ocsp_chain_ (const chain_t &chain); +public: + virtual ~Certs_(); + ocsp_response_t check_ocsp_chain_(const chain_t &chain); }; #endif //CCHECKER_DBFIXTURE_H diff --git a/tests/colour_log_formatter.cpp b/tests/colour_log_formatter.cpp index c873724..1d185bc 100644 --- a/tests/colour_log_formatter.cpp +++ b/tests/colour_log_formatter.cpp @@ -40,19 +40,21 @@ namespace { const_string test_phase_identifier() { - return framework::is_initialized() - ? const_string( framework::current_test_case().p_name.get() ) - : BOOST_TEST_L( "Test setup" ); + return framework::is_initialized() + ? const_string(framework::current_test_case().p_name.get()) + : BOOST_TEST_L("Test setup"); } const_string -get_basename(const const_string &file_name) { - return basename(file_name.begin()); +get_basename(const const_string &file_name) +{ + return basename(file_name.begin()); } std::string -get_basename(const std::string &file_name) { - return basename(file_name.c_str()); +get_basename(const std::string &file_name) +{ + return basename(file_name.c_str()); } } // local namespace @@ -61,185 +63,191 @@ get_basename(const std::string &file_name) { void colour_log_formatter::log_start( - std::ostream& output, - counter_t test_cases_amount ) + std::ostream &output, + counter_t test_cases_amount) { - if( test_cases_amount > 0 ) - output << "Running " << test_cases_amount << " test " - << (test_cases_amount > 1 ? "cases" : "case") << "...\n"; + if (test_cases_amount > 0) + output << "Running " << test_cases_amount << " test " + << (test_cases_amount > 1 ? "cases" : "case") << "...\n"; } //____________________________________________________________________________// void -colour_log_formatter::log_finish( std::ostream& ostr ) +colour_log_formatter::log_finish(std::ostream &ostr) { - ostr.flush(); + ostr.flush(); } //____________________________________________________________________________// void -colour_log_formatter::log_build_info( std::ostream& output ) +colour_log_formatter::log_build_info(std::ostream &output) { - output << "Platform: " << BOOST_PLATFORM << '\n' - << "Compiler: " << BOOST_COMPILER << '\n' - << "STL : " << BOOST_STDLIB << '\n' - << "Boost : " << BOOST_VERSION/100000 << "." - << BOOST_VERSION/100 % 1000 << "." - << BOOST_VERSION % 100 << std::endl; + output << "Platform: " << BOOST_PLATFORM << '\n' + << "Compiler: " << BOOST_COMPILER << '\n' + << "STL : " << BOOST_STDLIB << '\n' + << "Boost : " << BOOST_VERSION / 100000 << "." + << BOOST_VERSION / 100 % 1000 << "." + << BOOST_VERSION % 100 << std::endl; } //____________________________________________________________________________// void colour_log_formatter::test_unit_start( - std::ostream& output, - test_unit const& tu ) + std::ostream &output, + test_unit const &tu) { - if (tu.p_type_name->find(const_string("suite")) == 0) { - output << "Starting test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; - } else { - output << "Running test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; - } + if (tu.p_type_name->find(const_string("suite")) == 0) { + output << "Starting test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; + } else { + output << "Running test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; + } } //____________________________________________________________________________// void colour_log_formatter::test_unit_finish( - std::ostream& output, - test_unit const& tu, - unsigned long elapsed ) + std::ostream &output, + test_unit const &tu, + unsigned long elapsed) { - if (tu.p_type_name->find(const_string("suite")) == 0) { - output << "Finished test " << tu.p_type_name << " \"" << tu.p_name << "\""<< std::endl; - return; - } - std::string color = CCHECKER::Colors::Text::GREEN_BEGIN; - std::string status = "OK"; - if (m_isTestCaseFailed) { - color = CCHECKER::Colors::Text::RED_BEGIN; - status = "FAIL"; - } - output << "\t" << "[ " << color << status << CCHECKER::Colors::Text::COLOR_END << " ]"; - - - output << ", " << CCHECKER::Colors::Text::CYAN_BEGIN << "time: "; - if( elapsed > 0 ) { - if( elapsed % 1000 == 0 ) - output << elapsed/1000 << "ms"; - else - output << elapsed << "mks"; - } else { - output << "N/A"; - } - - output << CCHECKER::Colors::Text::COLOR_END << std::endl; - m_isTestCaseFailed = false; + if (tu.p_type_name->find(const_string("suite")) == 0) { + output << "Finished test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; + return; + } + + std::string color = CCHECKER::Colors::Text::GREEN_BEGIN; + std::string status = "OK"; + + if (m_isTestCaseFailed) { + color = CCHECKER::Colors::Text::RED_BEGIN; + status = "FAIL"; + } + + output << "\t" << "[ " << color << status << CCHECKER::Colors::Text::COLOR_END << " ]"; + output << ", " << CCHECKER::Colors::Text::CYAN_BEGIN << "time: "; + + if (elapsed > 0) { + if (elapsed % 1000 == 0) + output << elapsed / 1000 << "ms"; + else + output << elapsed << "mks"; + } else { + output << "N/A"; + } + + output << CCHECKER::Colors::Text::COLOR_END << std::endl; + m_isTestCaseFailed = false; } //____________________________________________________________________________// void colour_log_formatter::test_unit_skipped( - std::ostream& output, - test_unit const& tu ) + std::ostream &output, + test_unit const &tu) { - output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl; + output << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl; } //____________________________________________________________________________// void colour_log_formatter::log_exception( - std::ostream& output, - log_checkpoint_data const& checkpoint_data, - boost::execution_exception const& ex ) + std::ostream &output, + log_checkpoint_data const &checkpoint_data, + boost::execution_exception const &ex) { - boost::execution_exception::location const& loc = ex.where(); - output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(loc.m_file_name) - << '(' << loc.m_line_num << "), "; - - output << "fatal error in \"" - << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function ) << "\": "; - - output << CCHECKER::Colors::Text::COLOR_END << ex.what(); - - if( !checkpoint_data.m_file_name.is_empty() ) { - output << '\n'; - output << "\tlast checkpoint : " << get_basename(checkpoint_data.m_file_name) - << '(' << checkpoint_data.m_line_num << ")"; - if( !checkpoint_data.m_message.empty() ) - output << ": " << checkpoint_data.m_message; - } - - output << std::endl; - m_isTestCaseFailed = true; + boost::execution_exception::location const &loc = ex.where(); + output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(loc.m_file_name) + << '(' << loc.m_line_num << "), "; + output << "fatal error in \"" + << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function) << "\": "; + output << CCHECKER::Colors::Text::COLOR_END << ex.what(); + + if (!checkpoint_data.m_file_name.is_empty()) { + output << '\n'; + output << "\tlast checkpoint : " << get_basename(checkpoint_data.m_file_name) + << '(' << checkpoint_data.m_line_num << ")"; + + if (!checkpoint_data.m_message.empty()) + output << ": " << checkpoint_data.m_message; + } + + output << std::endl; + m_isTestCaseFailed = true; } //____________________________________________________________________________// void colour_log_formatter::log_entry_start( - std::ostream& output, - log_entry_data const& entry_data, - log_entry_types let ) + std::ostream &output, + log_entry_data const &entry_data, + log_entry_types let) { - switch( let ) { - case BOOST_UTL_ET_INFO: - output << '\t' << entry_data.m_file_name << '(' << entry_data.m_line_num << "), "; - output << "info: "; - break; - case BOOST_UTL_ET_MESSAGE: - break; - case BOOST_UTL_ET_WARNING: - output << '\t' << get_basename(entry_data.m_file_name) << '(' << entry_data.m_line_num << "), "; - output << "warning in \"" << test_phase_identifier() << "\": "; - break; - case BOOST_UTL_ET_ERROR: - output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name) - << '(' << entry_data.m_line_num << "), "; - output << "error in \"" << test_phase_identifier() << "\": "; - m_isTestCaseFailed = true; - break; - case BOOST_UTL_ET_FATAL_ERROR: - output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name) - << '(' << entry_data.m_line_num << "), "; - output << " fatal error in \"" << test_phase_identifier() << "\": "; - m_isTestCaseFailed = true; - break; - } - output << CCHECKER::Colors::Text::COLOR_END; + switch (let) { + case BOOST_UTL_ET_INFO: + output << '\t' << entry_data.m_file_name << '(' << entry_data.m_line_num << "), "; + output << "info: "; + break; + + case BOOST_UTL_ET_MESSAGE: + break; + + case BOOST_UTL_ET_WARNING: + output << '\t' << get_basename(entry_data.m_file_name) << '(' << entry_data.m_line_num << "), "; + output << "warning in \"" << test_phase_identifier() << "\": "; + break; + + case BOOST_UTL_ET_ERROR: + output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name) + << '(' << entry_data.m_line_num << "), "; + output << "error in \"" << test_phase_identifier() << "\": "; + m_isTestCaseFailed = true; + break; + + case BOOST_UTL_ET_FATAL_ERROR: + output << '\t' << CCHECKER::Colors::Text::BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name) + << '(' << entry_data.m_line_num << "), "; + output << " fatal error in \"" << test_phase_identifier() << "\": "; + m_isTestCaseFailed = true; + break; + } + + output << CCHECKER::Colors::Text::COLOR_END; } //____________________________________________________________________________// void colour_log_formatter::log_entry_value( - std::ostream& output, - const_string value ) + std::ostream &output, + const_string value) { - output << value; + output << value; } //____________________________________________________________________________// void colour_log_formatter::log_entry_value( - std::ostream& output, - lazy_ostream const& value ) + std::ostream &output, + lazy_ostream const &value) { - output << value; + output << value; } //____________________________________________________________________________// void colour_log_formatter::log_entry_finish( - std::ostream& output ) + std::ostream &output) { - output << std::endl; + output << std::endl; } //____________________________________________________________________________// diff --git a/tests/colour_log_formatter.h b/tests/colour_log_formatter.h index 5e44c58..ac4b07f 100644 --- a/tests/colour_log_formatter.h +++ b/tests/colour_log_formatter.h @@ -20,43 +20,43 @@ namespace CCHECKER { class colour_log_formatter : public boost::unit_test::unit_test_log_formatter { public: - // Formatter interface - colour_log_formatter() : m_isTestCaseFailed(false) {} - void log_start( - std::ostream&, - boost::unit_test::counter_t test_cases_amount ); - void log_finish( std::ostream& ); - void log_build_info( std::ostream& ); + // Formatter interface + colour_log_formatter() : m_isTestCaseFailed(false) {} + void log_start( + std::ostream &, + boost::unit_test::counter_t test_cases_amount); + void log_finish(std::ostream &); + void log_build_info(std::ostream &); - void test_unit_start( - std::ostream&, - boost::unit_test::test_unit const& tu ); - void test_unit_finish( - std::ostream&, - boost::unit_test::test_unit const& tu, - unsigned long elapsed ); - void test_unit_skipped( - std::ostream&, - boost::unit_test::test_unit const& tu ); + void test_unit_start( + std::ostream &, + boost::unit_test::test_unit const &tu); + void test_unit_finish( + std::ostream &, + boost::unit_test::test_unit const &tu, + unsigned long elapsed); + void test_unit_skipped( + std::ostream &, + boost::unit_test::test_unit const &tu); - void log_exception( - std::ostream&, - boost::unit_test::log_checkpoint_data const&, - boost::execution_exception const& ex ); + void log_exception( + std::ostream &, + boost::unit_test::log_checkpoint_data const &, + boost::execution_exception const &ex); - void log_entry_start( - std::ostream&, - boost::unit_test::log_entry_data const&, - log_entry_types let ); - void log_entry_value( - std::ostream&, - boost::unit_test::const_string value ); - void log_entry_value( - std::ostream&, - boost::unit_test::lazy_ostream const& value ); - void log_entry_finish( std::ostream& ); + void log_entry_start( + std::ostream &, + boost::unit_test::log_entry_data const &, + log_entry_types let); + void log_entry_value( + std::ostream &, + boost::unit_test::const_string value); + void log_entry_value( + std::ostream &, + boost::unit_test::lazy_ostream const &value); + void log_entry_finish(std::ostream &); private: - bool m_isTestCaseFailed; + bool m_isTestCaseFailed; }; } // namespace CCHECKER diff --git a/tests/dbfixture.cpp b/tests/dbfixture.cpp index 4d604fe..bcbbb33 100644 --- a/tests/dbfixture.cpp +++ b/tests/dbfixture.cpp @@ -32,20 +32,18 @@ const char *TEST_DB_PATH_TEMP = DB_INSTALL_DIR"/.cert-checker-test-temp.db"; } // anonymus namespace DBFixture::DBFixture() : - DB::SqlQuery() + DB::SqlQuery() { - // Remove temporary databse - BOOST_CHECK(unlink(TEST_DB_PATH_TEMP) == 0 || errno == ENOENT); - - // Restore original database - std::ifstream f1(TEST_DB_PATH, std::fstream::binary); - std::ofstream f2(TEST_DB_PATH_TEMP, std::fstream::trunc|std::fstream::binary); - f2 << f1.rdbuf(); - f2.close(); - f1.close(); - - // Open temporary database - BOOST_REQUIRE(connect(TEST_DB_PATH_TEMP)); + // Remove temporary databse + BOOST_CHECK(unlink(TEST_DB_PATH_TEMP) == 0 || errno == ENOENT); + // Restore original database + std::ifstream f1(TEST_DB_PATH, std::fstream::binary); + std::ofstream f2(TEST_DB_PATH_TEMP, std::fstream::trunc | std::fstream::binary); + f2 << f1.rdbuf(); + f2.close(); + f1.close(); + // Open temporary database + BOOST_REQUIRE(connect(TEST_DB_PATH_TEMP)); }; DBFixture::~DBFixture() diff --git a/tests/dbfixture.h b/tests/dbfixture.h index 68c1450..d64450e 100644 --- a/tests/dbfixture.h +++ b/tests/dbfixture.h @@ -28,9 +28,9 @@ using namespace CCHECKER; class DBFixture : public DB::SqlQuery { - public: - DBFixture(); - virtual ~DBFixture(); +public: + DBFixture(); + virtual ~DBFixture(); }; #endif //CCHECKER_DBFIXTURE_H diff --git a/tests/logic_.cpp b/tests/logic_.cpp index 4384e4e..20e4a2c 100644 --- a/tests/logic_.cpp +++ b/tests/logic_.cpp @@ -35,118 +35,118 @@ namespace CCHECKER { Logic_::Logic_(void) : - Logic(), - m_installCnt(0), - m_uninstallCnt(0), - m_bufferCnt(0) + Logic(), + m_installCnt(0), + m_uninstallCnt(0), + m_bufferCnt(0) {} Logic_::~Logic_(void) { - clean(); + clean(); } void Logic_::clean(void) { - LogDebug("Cert-checker cleaning."); - - // wait and join processing thread - if (m_thread.joinable()) { - LogDebug("Waiting for join processing thread"); - { - std::lock_guard < std::mutex > lock(m_mutex_cv); - set_should_exit(); - m_to_process.notify_one(); - } - m_thread.join(); - LogDebug("Processing thread joined"); - } else - LogDebug("No thread to join"); + LogDebug("Cert-checker cleaning."); + + // wait and join processing thread + if (m_thread.joinable()) { + LogDebug("Waiting for join processing thread"); + { + std::lock_guard <std::mutex> lock(m_mutex_cv); + set_should_exit(); + m_to_process.notify_one(); + } + m_thread.join(); + LogDebug("Processing thread joined"); + } else { + LogDebug("No thread to join"); + } } void Logic_::job() { - LogDebug("Test timer job"); - m_installCnt++; - - _m_wait_for_process.notify_one(); + LogDebug("Test timer job"); + m_installCnt++; + _m_wait_for_process.notify_one(); } void Logic_::connman_callback_manual_(bool state) { - Logic::set_online(state); + Logic::set_online(state); } void Logic_::pkgmgr_install_manual_(const app_t &app) { - push_event(event_t(app, event_t::event_type_t::APP_INSTALL)); + push_event(event_t(app, event_t::event_type_t::APP_INSTALL)); } void Logic_::pkgmgr_uninstall_manual_(const app_t &app) { - push_event(event_t(app, event_t::event_type_t::APP_UNINSTALL)); + push_event(event_t(app, event_t::event_type_t::APP_UNINSTALL)); } void Logic_::process_event(const event_t &event) { - Logic::process_event(event); - - std::lock_guard<std::mutex> lock(_m_mutex_wait_cv); - switch(event.event_type) - { - case event_t::event_type_t::APP_INSTALL: - m_installCnt++; - LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); - break; - case event_t::event_type_t::APP_UNINSTALL: - m_uninstallCnt++; - LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); - break; - default: - return; - } - // notify caller - _m_wait_for_process.notify_one(); + Logic::process_event(event); + std::lock_guard<std::mutex> lock(_m_mutex_wait_cv); + + switch (event.event_type) { + case event_t::event_type_t::APP_INSTALL: + m_installCnt++; + LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); + break; + + case event_t::event_type_t::APP_UNINSTALL: + m_uninstallCnt++; + LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); + break; + + default: + return; + } + + // notify caller + _m_wait_for_process.notify_one(); } void Logic_::app_processed() { - std::lock_guard<std::mutex> lock(_m_mutex_wait_cv); - m_bufferCnt++; - LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); - - // notify caller - _m_wait_for_process.notify_one(); + std::lock_guard<std::mutex> lock(_m_mutex_wait_cv); + m_bufferCnt++; + LogDebug(m_installCnt << " " << m_uninstallCnt << " " << m_bufferCnt); + // notify caller + _m_wait_for_process.notify_one(); } void Logic_::reset_cnt() { - m_installCnt = 0; - m_uninstallCnt = 0; - m_bufferCnt = 0; + m_installCnt = 0; + m_uninstallCnt = 0; + m_bufferCnt = 0; } void Logic_::wait_for_worker(int installCnt, int uninstallCnt, int bufferCnt) { - LogDebug("Wait for: " << installCnt << " " << uninstallCnt << " " << bufferCnt); - std::unique_lock<std::mutex> lock(_m_mutex_wait_cv); - bool timeout = !_m_wait_for_process.wait_for( - lock, - std::chrono::seconds(10), - [this, installCnt, uninstallCnt, bufferCnt]{ - return m_installCnt == installCnt && - m_uninstallCnt == uninstallCnt && - m_bufferCnt == bufferCnt; - } - ); - reset_cnt(); - _m_mutex_wait_cv.unlock(); - BOOST_REQUIRE(!timeout); + LogDebug("Wait for: " << installCnt << " " << uninstallCnt << " " << bufferCnt); + std::unique_lock<std::mutex> lock(_m_mutex_wait_cv); + bool timeout = !_m_wait_for_process.wait_for( + lock, + std::chrono::seconds(10), + [this, installCnt, uninstallCnt, bufferCnt] { + return m_installCnt == installCnt && + m_uninstallCnt == uninstallCnt && + m_bufferCnt == bufferCnt; + }); + reset_cnt(); + _m_mutex_wait_cv.unlock(); + BOOST_REQUIRE(!timeout); } -const std::list<app_t>& Logic_::get_buffer_() +const std::list<app_t> &Logic_::get_buffer_() { - return m_buffer; + return m_buffer; } } // CCHECKER diff --git a/tests/logic_.h b/tests/logic_.h index f8dcf95..e5e3934 100644 --- a/tests/logic_.h +++ b/tests/logic_.h @@ -34,72 +34,94 @@ namespace CCHECKER { class Logic_ : public Logic { - public: - Logic_(void); - virtual ~Logic_(void); - virtual void clean(void); - - // For tests only - void connman_callback_manual_(bool state); - void pkgmgr_install_manual_(const app_t &app); - void pkgmgr_uninstall_manual_(const app_t &app); - const std::list<app_t>& get_buffer_(); - - void reset_cnt(); - void wait_for_worker(int installCnt, int uninstallCnt, int bufferCnt); - - protected: - void job(void) override; - - private: - int m_installCnt; - int m_uninstallCnt; - int m_bufferCnt; - - void process_event(const event_t &event); - void app_processed() override; - std::condition_variable _m_wait_for_process; - std::mutex _m_mutex_wait_cv; +public: + Logic_(void); + virtual ~Logic_(void); + virtual void clean(void); + + // For tests only + void connman_callback_manual_(bool state); + void pkgmgr_install_manual_(const app_t &app); + void pkgmgr_uninstall_manual_(const app_t &app); + const std::list<app_t> &get_buffer_(); + + void reset_cnt(); + void wait_for_worker(int installCnt, int uninstallCnt, int bufferCnt); + +protected: + void job(void) override; + +private: + int m_installCnt; + int m_uninstallCnt; + int m_bufferCnt; + + void process_event(const event_t &event); + void app_processed() override; + std::condition_variable _m_wait_for_process; + std::mutex _m_mutex_wait_cv; }; class LogicWrapper { public: - LogicWrapper() {} - ~LogicWrapper() { m_logic.clean(); } - - error_t setup() { return m_logic.setup(); } - void clean() { m_logic.clean(); } - void connman_callback_manual_(bool state) { m_logic.connman_callback_manual_(state); } - void pkgmgr_install_manual_(const app_t &app) { m_logic.pkgmgr_install_manual_(app); } - void pkgmgr_uninstall_manual_(const app_t &app) { m_logic.pkgmgr_uninstall_manual_(app); } - const std::list<app_t>& get_buffer_() { return m_logic.get_buffer_(); } - - void wait_for_worker(int installCnt = 0, int uninstallCnt = 0, int bufferCnt = 0) { - m_logic.wait_for_worker(installCnt, uninstallCnt, bufferCnt); - } - - // timer operation - void timerStart(int interval) - { - m_logic.timerStart(interval); - } - void timerStop() - { - m_logic.timerStop(); - } - - // gio operation - void run(guint timeout) - { - m_logic.run(timeout); - } - bool is_running() - { - return m_logic.is_running(); - } + LogicWrapper() {} + ~LogicWrapper() + { + m_logic.clean(); + } + + error_t setup() + { + return m_logic.setup(); + } + void clean() + { + m_logic.clean(); + } + void connman_callback_manual_(bool state) + { + m_logic.connman_callback_manual_(state); + } + void pkgmgr_install_manual_(const app_t &app) + { + m_logic.pkgmgr_install_manual_(app); + } + void pkgmgr_uninstall_manual_(const app_t &app) + { + m_logic.pkgmgr_uninstall_manual_(app); + } + const std::list<app_t> &get_buffer_() + { + return m_logic.get_buffer_(); + } + + void wait_for_worker(int installCnt = 0, int uninstallCnt = 0, int bufferCnt = 0) + { + m_logic.wait_for_worker(installCnt, uninstallCnt, bufferCnt); + } + + // timer operation + void timerStart(int interval) + { + m_logic.timerStart(interval); + } + void timerStop() + { + m_logic.timerStop(); + } + + // gio operation + void run(guint timeout) + { + m_logic.run(timeout); + } + bool is_running() + { + return m_logic.is_running(); + } private: - Logic_ m_logic; + Logic_ m_logic; }; } // CCHECKER diff --git a/tests/main.cpp b/tests/main.cpp index 8fe6733..59e8df2 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -29,11 +29,12 @@ #include "common/log.h" struct TestConfig { - TestConfig() { - boost::unit_test::unit_test_log.set_threshold_level( boost::unit_test::log_test_units); - boost::unit_test::results_reporter::set_level(boost::unit_test::SHORT_REPORT); - boost::unit_test::unit_test_log.set_formatter(new CCHECKER::colour_log_formatter); - } + TestConfig() + { + boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_test_units); + boost::unit_test::results_reporter::set_level(boost::unit_test::SHORT_REPORT); + boost::unit_test::unit_test_log.set_formatter(new CCHECKER::colour_log_formatter); + } }; BOOST_GLOBAL_FIXTURE(TestConfig) diff --git a/tests/popup_test.cpp b/tests/popup_test.cpp index 3f6676d..8bdff76 100644 --- a/tests/popup_test.cpp +++ b/tests/popup_test.cpp @@ -26,27 +26,23 @@ using namespace CCHECKER; -int main(int argc, char** argv) +int main(int argc, char **argv) { - LogDebug("Cert-checker popup-test start!"); - - int timeout = 60; - if (argc > 1) { - timeout = atoi(argv[1]); - } - LogDebug("popup-test timeout: " << timeout); - - setlocale(LC_ALL, ""); - - UI::UIBackend ui(timeout); - - app_t app(std::string("test_APP_ID"), - std::string("test PKG ID"), - 5005, - {}); - - ui.call_popup(app); - - LogDebug("Cert-checker popup-test exit!"); - return 0; + LogDebug("Cert-checker popup-test start!"); + int timeout = 60; + + if (argc > 1) { + timeout = atoi(argv[1]); + } + + LogDebug("popup-test timeout: " << timeout); + setlocale(LC_ALL, ""); + UI::UIBackend ui(timeout); + app_t app(std::string("test_APP_ID"), + std::string("test PKG ID"), + 5005, + {}); + ui.call_popup(app); + LogDebug("Cert-checker popup-test exit!"); + return 0; } diff --git a/tests/queue_test_thread.cpp b/tests/queue_test_thread.cpp index b98ddc1..b20f10c 100644 --- a/tests/queue_test_thread.cpp +++ b/tests/queue_test_thread.cpp @@ -34,78 +34,80 @@ namespace CCHECKER { #define APPS_COUNT 10 app_t app[APPS_COUNT] = { - app_t ("app_id0", "###", 0, {}), - app_t ("app_id1", "pkg_id1", 1, {}), - app_t ("app_id2", "pkg_id2", 2, {}), - app_t ("app_id3", "###", 3, {}), - app_t ("app_id4", "###", 4, {}), - app_t ("app_id5", "###", 5, {}), - app_t ("app_id6", "###", 6, {}), - app_t ("app_id7", "###", 7, {}), - app_t ("app_id8", "###", 8, {}), - app_t ("app_id9", "###", 9, {}) + app_t("app_id0", "###", 0, {}), + app_t("app_id1", "pkg_id1", 1, {}), + app_t("app_id2", "pkg_id2", 2, {}), + app_t("app_id3", "###", 3, {}), + app_t("app_id4", "###", 4, {}), + app_t("app_id5", "###", 5, {}), + app_t("app_id6", "###", 6, {}), + app_t("app_id7", "###", 7, {}), + app_t("app_id8", "###", 8, {}), + app_t("app_id9", "###", 9, {}) }; void TestQueue::add_events_th(int number_of_threads) { - if (number_of_threads < 1) { - LogDebug("Too few threads, at least 1 should be used"); - number_of_threads = 1; - } + if (number_of_threads < 1) { + LogDebug("Too few threads, at least 1 should be used"); + number_of_threads = 1; + } - m_sent = 0; - m_max_events = number_of_threads * 2 * APPS_COUNT; + m_sent = 0; + m_max_events = number_of_threads * 2 * APPS_COUNT; + LogDebug("Running threads"); - LogDebug("Running threads"); - for (int i=0; i<number_of_threads; i++) - std::thread(&TestQueue::add_events, this).detach(); + for (int i = 0; i < number_of_threads; i++) + std::thread(&TestQueue::add_events, this).detach(); - LogDebug("Running threads done"); + LogDebug("Running threads done"); } void TestQueue::add_events() { - for (int i = 0; i < APPS_COUNT; i++) { - m_queue.push_event(event_t(app[i], event_t::event_type_t::APP_INSTALL)); - m_sent++; - LogDebug("Add event : " << i); - } - - for (int i = 0; i < APPS_COUNT; i++) { - m_queue.push_event(event_t(app[i], event_t::event_type_t::APP_UNINSTALL)); - m_sent++; - LogDebug("Add event : " << i); - } + for (int i = 0; i < APPS_COUNT; i++) { + m_queue.push_event(event_t(app[i], event_t::event_type_t::APP_INSTALL)); + m_sent++; + LogDebug("Add event : " << i); + } + + for (int i = 0; i < APPS_COUNT; i++) { + m_queue.push_event(event_t(app[i], event_t::event_type_t::APP_UNINSTALL)); + m_sent++; + LogDebug("Add event : " << i); + } } bool TestQueue::pop_events() { - int i_install = 0; - int i_uninstall = 0; - event_t ev; - - LogDebug("Looking events..."); - do { - while(m_queue.pop_event(ev)) { - if (ev.event_type == event_t::event_type_t::APP_INSTALL) - i_install++; - else if (ev.event_type == event_t::event_type_t::APP_UNINSTALL) - i_uninstall++; - } - } while (m_sent < m_max_events); - - // Read all events once again - just for case - while(m_queue.pop_event(ev)) { - if (ev.event_type == event_t::event_type_t::APP_INSTALL) - i_install++; - else if (ev.event_type == event_t::event_type_t::APP_UNINSTALL) - i_uninstall++; - } - LogDebug("Found " << i_install + i_uninstall << " events."); - - if (i_install != m_max_events/2 || i_uninstall != m_max_events/2) - return false; - return true; + int i_install = 0; + int i_uninstall = 0; + event_t ev; + LogDebug("Looking events..."); + + do { + while (m_queue.pop_event(ev)) { + if (ev.event_type == event_t::event_type_t::APP_INSTALL) + i_install++; + else if (ev.event_type == event_t::event_type_t::APP_UNINSTALL) + i_uninstall++; + } + } while (m_sent < m_max_events); + + // Read all events once again - just for case + while (m_queue.pop_event(ev)) { + if (ev.event_type == event_t::event_type_t::APP_INSTALL) + i_install++; + else if (ev.event_type == event_t::event_type_t::APP_UNINSTALL) + i_uninstall++; + } + + LogDebug("Found " << i_install + i_uninstall << " events."); + + if (i_install != m_max_events / 2 || i_uninstall != m_max_events / 2) + return false; + + return true; } } // CCHECKER diff --git a/tests/queue_test_thread.h b/tests/queue_test_thread.h index 2c2989e..329a29c 100644 --- a/tests/queue_test_thread.h +++ b/tests/queue_test_thread.h @@ -25,19 +25,19 @@ namespace CCHECKER { class TestQueue { - public: - TestQueue(): - m_sent(0), - m_max_events(0) - {}; - void add_events_th (int number_of_threads); - bool pop_events (); +public: + TestQueue(): + m_sent(0), + m_max_events(0) + {}; + void add_events_th(int number_of_threads); + bool pop_events(); - private: - Queue m_queue; - int m_sent; - int m_max_events; - void add_events(); +private: + Queue m_queue; + int m_sent; + int m_max_events; + void add_events(); }; } // CCHECKER diff --git a/tests/stubs_.cpp b/tests/stubs_.cpp index 1360986..2f46fb1 100644 --- a/tests/stubs_.cpp +++ b/tests/stubs_.cpp @@ -38,37 +38,38 @@ Certs::~Certs() void Certs::get_certificates(app_t &app) { - (void)app; + (void)app; } // Only the public functions need to be stubbed for testing all possibilities Certs::ocsp_response_t Certs::check_ocsp(const app_t &app) { - if (app.signatures.empty()) - return ocsp_response_t::OCSP_APP_OK; + if (app.signatures.empty()) + return ocsp_response_t::OCSP_APP_OK; - if (app.signatures.front().empty()) - return ocsp_response_t::OCSP_APP_OK; + if (app.signatures.front().empty()) + return ocsp_response_t::OCSP_APP_OK; - std::string ret = app.signatures.front().front(); + std::string ret = app.signatures.front().front(); - if ("OCSP_APP_REVOKED" == ret) - return ocsp_response_t::OCSP_APP_REVOKED; - if ("OCSP_CHECK_AGAIN" == ret) - return ocsp_response_t::OCSP_CHECK_AGAIN; - if ("OCSP_CERT_ERROR" == ret) - return ocsp_response_t::OCSP_CERT_ERROR; + if ("OCSP_APP_REVOKED" == ret) + return ocsp_response_t::OCSP_APP_REVOKED; - return ocsp_response_t::OCSP_APP_OK; + if ("OCSP_CHECK_AGAIN" == ret) + return ocsp_response_t::OCSP_CHECK_AGAIN; + + if ("OCSP_CERT_ERROR" == ret) + return ocsp_response_t::OCSP_CERT_ERROR; + + return ocsp_response_t::OCSP_APP_OK; } // DB DB::SqlQuery::SqlQuery(const std::string &path) { - m_connection = NULL; - m_inUserTransaction = false; - - (void)path; + m_connection = NULL; + m_inUserTransaction = false; + (void)path; } DB::SqlQuery::~SqlQuery() @@ -76,29 +77,29 @@ DB::SqlQuery::~SqlQuery() bool DB::SqlQuery::add_app_to_check_list(const app_t &app) { - (void)app; - return true; // Success + (void)app; + return true; // Success } void DB::SqlQuery::remove_app_from_check_list(const app_t &app) { - (void)app; + (void)app; } void DB::SqlQuery::mark_as_verified(const app_t &app, const app_t::verified_t &verified) { - (void)app; - (void)verified; + (void)app; + (void)verified; } void DB::SqlQuery::get_app_list(std::list<app_t> &apps_buffer) { - (void)apps_buffer; + (void)apps_buffer; } // UI UI::UIBackend::UIBackend(int timeout) : - m_responseTimeout(timeout) + m_responseTimeout(timeout) {} UI::UIBackend::~UIBackend() @@ -106,10 +107,10 @@ UI::UIBackend::~UIBackend() bool UI::UIBackend::call_popup(const app_t &app) { - if (app.uid > 5000) - return true; + if (app.uid > 5000) + return true; - return false; + return false; } } //CCHECKER diff --git a/tests/test_app.cpp b/tests/test_app.cpp index c32d571..8035dfa 100644 --- a/tests/test_app.cpp +++ b/tests/test_app.cpp @@ -30,111 +30,98 @@ using namespace CCHECKER; BOOST_FIXTURE_TEST_SUITE(APP_TEST, app_t) -BOOST_AUTO_TEST_CASE(App_positive) { - - app_t app1("app_1", "pkg_1", 5001, {{"aaaaaa"}}); - app_t app2("app_1", "pkg_1", 5001, {{"aaaaaa"}}); - - app_t app3("app_2", "pkg_1", 5002, {{"aaa", "bbbb"}, {"ccccc"}}); - app_t app4("app_2", "pkg_1", 5002, {{"ccccc"}, {"aaa", "bbbb"}}); - - chain_t chain411 = {"cert_4.1", "cert 4.2"}; - chain_t chain421 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; - chain_t chain43 = {"cert_4.3.1"}; - - app_t app5("app_3", "pkg_1", 5003, {chain411, chain421, chain43}); - app_t app6("app_3", "pkg_1", 5003, {chain421, chain411, chain43}); - app_t app7("app_3", "pkg_1", 5003, {chain411, chain43, chain421}); - app_t app8("app_3", "pkg_1", 5003, {chain421, chain43, chain411}); - app_t app9("app_3", "pkg_1", 5003, {chain43, chain411, chain421}); - app_t app10("app_3", "pkg_1", 5003, {chain43, chain421, chain411}); - - sort(app1); - sort(app2); - sort(app3); - sort(app4); - sort(app5); - sort(app6); - sort(app7); - sort(app8); - sort(app9); - sort(app10); - - BOOST_REQUIRE(app1 == app2); - - BOOST_REQUIRE(app3 == app4); - - BOOST_REQUIRE(app5 == app6); - BOOST_REQUIRE(app6 == app7); - BOOST_REQUIRE(app7 == app8); - BOOST_REQUIRE(app8 == app9); - BOOST_REQUIRE(app9 == app10); +BOOST_AUTO_TEST_CASE(App_positive) +{ + app_t app1("app_1", "pkg_1", 5001, {{"aaaaaa"}}); + app_t app2("app_1", "pkg_1", 5001, {{"aaaaaa"}}); + app_t app3("app_2", "pkg_1", 5002, {{"aaa", "bbbb"}, {"ccccc"}}); + app_t app4("app_2", "pkg_1", 5002, {{"ccccc"}, {"aaa", "bbbb"}}); + chain_t chain411 = {"cert_4.1", "cert 4.2"}; + chain_t chain421 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; + chain_t chain43 = {"cert_4.3.1"}; + app_t app5("app_3", "pkg_1", 5003, {chain411, chain421, chain43}); + app_t app6("app_3", "pkg_1", 5003, {chain421, chain411, chain43}); + app_t app7("app_3", "pkg_1", 5003, {chain411, chain43, chain421}); + app_t app8("app_3", "pkg_1", 5003, {chain421, chain43, chain411}); + app_t app9("app_3", "pkg_1", 5003, {chain43, chain411, chain421}); + app_t app10("app_3", "pkg_1", 5003, {chain43, chain421, chain411}); + sort(app1); + sort(app2); + sort(app3); + sort(app4); + sort(app5); + sort(app6); + sort(app7); + sort(app8); + sort(app9); + sort(app10); + BOOST_REQUIRE(app1 == app2); + BOOST_REQUIRE(app3 == app4); + BOOST_REQUIRE(app5 == app6); + BOOST_REQUIRE(app6 == app7); + BOOST_REQUIRE(app7 == app8); + BOOST_REQUIRE(app8 == app9); + BOOST_REQUIRE(app9 == app10); } -BOOST_AUTO_TEST_CASE(App_negative) { - - app_t app1("app_1", "pkg_1", 5001, {{"aaaaaa"}}); - app_t app2("app_2", "pkg_1", 5001, {{"aaaaaa"}}); - app_t app3("app_2", "pkg_2", 5001, {{"aaaaaa"}}); - app_t app4("app_2", "pkg_2", 5002, {{"aaaaaa"}}); - - chain_t chain411 = {"cert_4.1", "cert 4.2"}; - chain_t chain412 = {"cert 4.2", "cert_4.1"}; - - chain_t chain421 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; - chain_t chain422 = {"cert_4.2.1", "cert 4.2.3", "cert_4.2.2"}; - chain_t chain423 = {"cert_4.2.3", "cert 4.2.1", "cert_4.2.2"}; - chain_t chain424 = {"cert_4.2.3", "cert 4.2.2", "cert_4.2.1"}; - chain_t chain425 = {"cert_4.2.2", "cert 4.2.1", "cert_4.2.3"}; - chain_t chain426 = {"cert_4.2.2", "cert 4.2.3", "cert_4.2.1"}; - - chain_t chain427 = {"cert", "cert_4.2.1", "cert 4.2.2"}; - chain_t chain428 = {"cert_4.2.1", " ", "cert 4.2.2"}; - chain_t chain429 = {"cert 4.2.3", "cert 4.2.2"}; - chain_t chain420 = {"cert 4.2" , "cert_4.2" , "cert 4.2" }; - - chain_t chain43 = {"cert_4.3.1"}; - - app_t app5("app_3", "pkg_1", 5003, {chain411, chain421, chain43}); - app_t app6("app_3", "pkg_1", 5003, {chain411, chain422, chain43}); - app_t app7("app_3", "pkg_1", 5003, {chain411, chain423, chain43}); - app_t app8("app_3", "pkg_1", 5003, {chain411, chain424, chain43}); - app_t app9("app_3", "pkg_1", 5003, {chain411, chain425, chain43}); - app_t app10("app_3", "pkg_1", 5003, {chain411, chain426, chain43}); - app_t app11("app_3", "pkg_1", 5003, {chain412, chain421, chain43}); - app_t app12("app_3", "pkg_1", 5003, {chain412, chain422, chain43}); - app_t app13("app_3", "pkg_1", 5003, {chain412, chain423, chain43}); - app_t app14("app_3", "pkg_1", 5003, {chain412, chain424, chain43}); - app_t app15("app_3", "pkg_1", 5003, {chain412, chain425, chain43}); - app_t app16("app_3", "pkg_1", 5003, {chain412, chain426, chain43}); - - app_t app17("app_3", "pkg_1", 5003, {chain421}); - app_t app18("app_3", "pkg_1", 5003, {chain422}); - app_t app19("app_3", "pkg_1", 5003, {chain423}); - app_t app20("app_3", "pkg_1", 5003, {chain424}); - app_t app21("app_3", "pkg_1", 5003, {chain425}); - app_t app22("app_3", "pkg_1", 5003, {chain426}); - app_t app23("app_3", "pkg_1", 5003, {chain427}); - app_t app24("app_3", "pkg_1", 5003, {chain428}); - app_t app25("app_3", "pkg_1", 5003, {chain429}); - app_t app26("app_3", "pkg_1", 5003, {chain420}); - - app_t apps[26] = {app1, app2, app3, app4, app5, app6, app7, app8, - app9, app10, app11, app12, app13, app14, app15, app16, app17, - app18, app19, app20, app21, app22, app23, app24, app25, app26}; - - for (int i=0; i<26; i++) { - sort(apps[i]); - } - - for (int i=0; i<26; i++) { - for (int j=0; j<26; j++) { - if (i != j) - BOOST_REQUIRE(apps[i] != apps[j]); - else - BOOST_REQUIRE(apps[i] == apps[j]); - } - } +BOOST_AUTO_TEST_CASE(App_negative) +{ + app_t app1("app_1", "pkg_1", 5001, {{"aaaaaa"}}); + app_t app2("app_2", "pkg_1", 5001, {{"aaaaaa"}}); + app_t app3("app_2", "pkg_2", 5001, {{"aaaaaa"}}); + app_t app4("app_2", "pkg_2", 5002, {{"aaaaaa"}}); + chain_t chain411 = {"cert_4.1", "cert 4.2"}; + chain_t chain412 = {"cert 4.2", "cert_4.1"}; + chain_t chain421 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; + chain_t chain422 = {"cert_4.2.1", "cert 4.2.3", "cert_4.2.2"}; + chain_t chain423 = {"cert_4.2.3", "cert 4.2.1", "cert_4.2.2"}; + chain_t chain424 = {"cert_4.2.3", "cert 4.2.2", "cert_4.2.1"}; + chain_t chain425 = {"cert_4.2.2", "cert 4.2.1", "cert_4.2.3"}; + chain_t chain426 = {"cert_4.2.2", "cert 4.2.3", "cert_4.2.1"}; + chain_t chain427 = {"cert", "cert_4.2.1", "cert 4.2.2"}; + chain_t chain428 = {"cert_4.2.1", " ", "cert 4.2.2"}; + chain_t chain429 = {"cert 4.2.3", "cert 4.2.2"}; + chain_t chain420 = {"cert 4.2" , "cert_4.2" , "cert 4.2" }; + chain_t chain43 = {"cert_4.3.1"}; + app_t app5("app_3", "pkg_1", 5003, {chain411, chain421, chain43}); + app_t app6("app_3", "pkg_1", 5003, {chain411, chain422, chain43}); + app_t app7("app_3", "pkg_1", 5003, {chain411, chain423, chain43}); + app_t app8("app_3", "pkg_1", 5003, {chain411, chain424, chain43}); + app_t app9("app_3", "pkg_1", 5003, {chain411, chain425, chain43}); + app_t app10("app_3", "pkg_1", 5003, {chain411, chain426, chain43}); + app_t app11("app_3", "pkg_1", 5003, {chain412, chain421, chain43}); + app_t app12("app_3", "pkg_1", 5003, {chain412, chain422, chain43}); + app_t app13("app_3", "pkg_1", 5003, {chain412, chain423, chain43}); + app_t app14("app_3", "pkg_1", 5003, {chain412, chain424, chain43}); + app_t app15("app_3", "pkg_1", 5003, {chain412, chain425, chain43}); + app_t app16("app_3", "pkg_1", 5003, {chain412, chain426, chain43}); + app_t app17("app_3", "pkg_1", 5003, {chain421}); + app_t app18("app_3", "pkg_1", 5003, {chain422}); + app_t app19("app_3", "pkg_1", 5003, {chain423}); + app_t app20("app_3", "pkg_1", 5003, {chain424}); + app_t app21("app_3", "pkg_1", 5003, {chain425}); + app_t app22("app_3", "pkg_1", 5003, {chain426}); + app_t app23("app_3", "pkg_1", 5003, {chain427}); + app_t app24("app_3", "pkg_1", 5003, {chain428}); + app_t app25("app_3", "pkg_1", 5003, {chain429}); + app_t app26("app_3", "pkg_1", 5003, {chain420}); + app_t apps[26] = {app1, app2, app3, app4, app5, app6, app7, app8, + app9, app10, app11, app12, app13, app14, app15, app16, app17, + app18, app19, app20, app21, app22, app23, app24, app25, app26 + }; + + for (int i = 0; i < 26; i++) { + sort(apps[i]); + } + + for (int i = 0; i < 26; i++) { + for (int j = 0; j < 26; j++) { + if (i != j) + BOOST_REQUIRE(apps[i] != apps[j]); + else + BOOST_REQUIRE(apps[i] == apps[j]); + } + } } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_certs.cpp b/tests/test_certs.cpp index e9f5b34..e51dbdd 100644 --- a/tests/test_certs.cpp +++ b/tests/test_certs.cpp @@ -32,11 +32,11 @@ using namespace CCHECKER; BOOST_FIXTURE_TEST_SUITE(CERT_TEST, Certs_) -BOOST_AUTO_TEST_CASE(Certs_OCSP_positive) { - - //*.wikipedia.com: - chain_t chain = { - "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ +BOOST_AUTO_TEST_CASE(Certs_OCSP_positive) +{ + //*.wikipedia.com: + chain_t chain = { + "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ MGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMTwwOgYD\ VQQDEzNHbG9iYWxTaWduIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIENBIC0gU0hB\ MjU2IC0gRzIwHhcNMTQxMjE2MjEyNDAzWhcNMTcwMjE5MTIwMDAwWjB5MQswCQYD\ @@ -79,7 +79,7 @@ gOk/sO6ilkOun/u5QBigxne1/P4g2SYkISqRqA0Z9FloEd6odDb6dbIHhhz270rH\ 4V9POUs5kH7d1OJs9d5Fv9y3t/Yt1pGaHyK/DTUbYVhMyn0EaLxd3FLJ9ABKpQJ+\ OUcTfe55U2Ox1H/87b6Ca04DDl3u2i87jPbhgshWSNwU8+llHCst0sbG", -"MIIEaTCCA1GgAwIBAgILBAAAAAABRE7wQkcwDQYJKoZIhvcNAQELBQAwVzELMAkG\ + "MIIEaTCCA1GgAwIBAgILBAAAAAABRE7wQkcwDQYJKoZIhvcNAQELBQAwVzELMAkG\ A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\ b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xNDAyMjAxMDAw\ MDBaFw0yNDAyMjAxMDAwMDBaMGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\ @@ -104,7 +104,7 @@ XN0cvfNVlg/UBsD84iOKJHDTu/B5GqdhcIOKrwbFINihY9Bsrk8y1658GEV1BSl3\ SOlCdjSXVWkkDoPWoC209fN5ikkodBpBocLTJIg1MGCUF7ThBCIxPTsvFwayuJ2G\ K1pp74P1S8SqtCr4fKGxhZSM9AyHDPSsQPhZSZg=", -"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\ + "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\ A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\ b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\ MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\ @@ -122,19 +122,19 @@ yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\ 38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\ AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\ DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\ -HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A=="}; - - Certs::ocsp_response_t resp = check_ocsp_chain_ (chain); - LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); - BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CHECK_AGAIN); +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==" + }; + Certs::ocsp_response_t resp = check_ocsp_chain_(chain); + LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); + BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CHECK_AGAIN); } -BOOST_AUTO_TEST_CASE(Certs_OCSP_negative_1) { - // Broken chain of certificates - - //*.wikipedia.com: - chain_t chain = { - "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ +BOOST_AUTO_TEST_CASE(Certs_OCSP_negative_1) +{ + // Broken chain of certificates + //*.wikipedia.com: + chain_t chain = { + "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ MGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMTwwOgYD\ VQQDEzNHbG9iYWxTaWduIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIENBIC0gU0hB\ MjU2IC0gRzIwHhcNMTQxMjE2MjEyNDAzWhcNMTcwMjE5MTIwMDAwWjB5MQswCQYD\ @@ -175,18 +175,18 @@ gwBA5hp8MA0GCSqGSIb3DQEBCwUAA4IBAQC45+nGVISGOZctc9mxhil3EDmlBIzY\ gOk/sO6ilkOun/u5QBigxne1/P4g2SYkISqRqA0Z9FloEd6odDb6dbIHhhz270rH\ 3pjewMLq6OA09eklPav4f3NiBL/VcqG53TRTJW6eHxZuEsGAgBmwk6jKf8e+BjmZ\ 4V9POUs5kH7d1OJs9d5Fv9y3t/Yt1pGaHyK/DTUbYVhMyn0EaLxd3FLJ9ABKpQJ+\ -OUcTfe55U2Ox1H/87b6Ca04DDl3u2i87jPbhgshWSNwU8+llHCst0sbG"}; - - Certs::ocsp_response_t resp = check_ocsp_chain_ (chain); - LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); - BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CERT_ERROR); +OUcTfe55U2Ox1H/87b6Ca04DDl3u2i87jPbhgshWSNwU8+llHCst0sbG" + }; + Certs::ocsp_response_t resp = check_ocsp_chain_(chain); + LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); + BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CERT_ERROR); } -BOOST_AUTO_TEST_CASE(Certs_OCSP_negative_2) { - // Last Certificate is corrupted - - chain_t chain = { - "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ +BOOST_AUTO_TEST_CASE(Certs_OCSP_negative_2) +{ + // Last Certificate is corrupted + chain_t chain = { + "MIIH1jCCBr6gAwIBAgISESGXLjKl5bLinUct/tty1iduMA0GCSqGSIb3DQEBCwUA\ MGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMTwwOgYD\ VQQDEzNHbG9iYWxTaWduIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIENBIC0gU0hB\ MjU2IC0gRzIwHhcNMTQxMjE2MjEyNDAzWhcNMTcwMjE5MTIwMDAwWjB5MQswCQYD\ @@ -229,7 +229,7 @@ gOk/sO6ilkOun/u5QBigxne1/P4g2SYkISqRqA0Z9FloEd6odDb6dbIHhhz270rH\ 4V9POUs5kH7d1OJs9d5Fv9y3t/Yt1pGaHyK/DTUbYVhMyn0EaLxd3FLJ9ABKpQJ+\ OUcTfe55U2Ox1H/87b6Ca04DDl3u2i87jPbhgshWSNwU8+llHCst0sbG", -"MIIEaTCCA1GgAwIBAgILBAAAAAABRE7wQkcwDQYJKoZIhvcNAQELBQAwVzELMAkG\ + "MIIEaTCCA1GgAwIBAgILBAAAAAABRE7wQkcwDQYJKoZIhvcNAQELBQAwVzELMAkG\ A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\ b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xNDAyMjAxMDAw\ MDBaFw0yNDAyMjAxMDAwMDBaMGYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\ @@ -254,7 +254,7 @@ XN0cvfNVlg/UBsD84iOKJHDTu/B5GqdhcIOKrwbFINihY9Bsrk8y1658GEV1BSl3\ SOlCdjSXVWkkDoPWoC209fN5ikkodBpBocLTJIg1MGCUF7ThBCIxPTsvFwayuJ2G\ K1pp74P1S8SqtCr4fKGxhZSM9AyHDPSsQPhZSZg=", -"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\ + "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\ A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\ b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\ MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\ @@ -272,18 +272,18 @@ yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\ 38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\ AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\ DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\ -HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4"}; - - Certs::ocsp_response_t resp = check_ocsp_chain_ (chain); - LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); - BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CERT_ERROR); +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4" + }; + Certs::ocsp_response_t resp = check_ocsp_chain_(chain); + LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); + BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_CERT_ERROR); } -BOOST_AUTO_TEST_CASE(Certs_OCSP_positive_1) { - - chain_t chain = { - // MBANK, signed by SYMANTEC, expires 04 Feb 2016 - "MIIGXDCCBUSgAwIBAgIQKJK70TuBw91HAA0BqZSPETANBgkqhkiG9w0BAQsFADB3\ +BOOST_AUTO_TEST_CASE(Certs_OCSP_positive_1) +{ + chain_t chain = { + // MBANK, signed by SYMANTEC, expires 04 Feb 2016 + "MIIGXDCCBUSgAwIBAgIQKJK70TuBw91HAA0BqZSPETANBgkqhkiG9w0BAQsFADB3\ MQswCQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAd\ BgNVBAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxKDAmBgNVBAMTH1N5bWFudGVj\ IENsYXNzIDMgRVYgU1NMIENBIC0gRzMwHhcNMTUwMTE1MDAwMDAwWhcNMTYwMjA0\ @@ -318,8 +318,8 @@ SReh+urkTFGUdSPCsD4mQk3zI1wNhE7Amb2mUTIaSLzabnN89hn9jlvQwLH2Wkf2\ aFmUlsB1C6YFMqVPRfHuxyPUb2zjw+ll7UStQxuSSTpwBmW1g/dIhtle9+o8i3z2\ WJAT38TP3mPw8SUWLbgGyih6bsB6eBxFEM5awP60XXjZfVAmoVLlj9oWYNQrZLwk", - // SYMANTEC, signed by VERISIGN, expires 30 Oct 2023 - "MIIFKzCCBBOgAwIBAgIQfuFKb2/v8tN/P61lTTratDANBgkqhkiG9w0BAQsFADCB\ + // SYMANTEC, signed by VERISIGN, expires 30 Oct 2023 + "MIIFKzCCBBOgAwIBAgIQfuFKb2/v8tN/P61lTTratDANBgkqhkiG9w0BAQsFADCB\ yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL\ ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp\ U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW\ @@ -347,11 +347,10 @@ qLuSLRtzsMarNvSWbCAI7woeZiRFT2cAQMgHVHQzO6atuyOfZu2iRHA0+w7qAf3P\ eHTfp61Vt19N9tY/4IbOJMdCqRMURDVLtt/JYKwMf9mTIUvunORJApjTYHtcvNUw\ LwfORELEC5n+5p/8sHiGUW3RLJ3GlvuFgrsEL/digO9i2n/2DqyQuFa9eT/ygG6j\ 2bkPXToHHZGThkspTOHcteHgM52zyzaRS/6htO7w+Q==" - }; - - Certs::ocsp_response_t resp = check_ocsp_chain_ (chain); - LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); - BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_APP_OK); + }; + Certs::ocsp_response_t resp = check_ocsp_chain_(chain); + LogDebug("Certs_::check_ocsp_chain_ response : " << (int) resp); + BOOST_REQUIRE(resp == Certs::ocsp_response_t::OCSP_APP_OK); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_client.cpp b/tests/test_client.cpp index a0fc0c2..83661f4 100644 --- a/tests/test_client.cpp +++ b/tests/test_client.cpp @@ -27,11 +27,10 @@ BOOST_AUTO_TEST_SUITE(CLIENT_TEST) -BOOST_AUTO_TEST_CASE(client_api) { - +BOOST_AUTO_TEST_CASE(client_api) +{ auto ret = cchecker_ocsp_request(); BOOST_REQUIRE(ret == 0); - } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_db.cpp b/tests/test_db.cpp index 9649087..1f6541d 100644 --- a/tests/test_db.cpp +++ b/tests/test_db.cpp @@ -31,93 +31,70 @@ BOOST_FIXTURE_TEST_SUITE(DB_TEST, DBFixture) -BOOST_AUTO_TEST_CASE(DB_app_positive) { - - std::list<app_t> buffer; - app_t app1("app_1", "pkg_1", 5001, {}); - - chain_t chain2 = {"cert2"}; - app_t app2("app_2", "pkg 2", 5002, {chain2}); - - chain_t chain2r = {"cert2r"}; - app_t app2r("app_2_remove", "pkg 2", 5002, {chain2, chain2r}); - - chain_t chain31 = {"cert_3.1", "cert 3.2"}; - chain_t chain32 = {"cert_3.1"}; - app_t app3("app 3", "pkg 3", 5003, {chain31, chain32}); - - chain_t chain41 = {"cert_4.1", "cert 4.2"}; - chain_t chain42 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; - chain_t chain43 = {"cert_4.3.1"}; - - app_t app4("app 4", "pkg 4", 5004, {chain41, chain42, chain43}); - - BOOST_REQUIRE(add_app_to_check_list(app1)==true); - BOOST_REQUIRE(add_app_to_check_list(app2)==true); - BOOST_REQUIRE(add_app_to_check_list(app2r)==true); - BOOST_REQUIRE(add_app_to_check_list(app3)==true); - BOOST_REQUIRE(add_app_to_check_list(app4)==true); - - mark_as_verified(app2, app_t::verified_t::NO); - mark_as_verified(app3, app_t::verified_t::YES); - remove_app_from_check_list(app2r); - - app2.verified = app_t::verified_t::NO; - app3.verified = app_t::verified_t::YES; - - std::list<app_t> buffer_ok = {app1, app2, app3, app4}; - - get_app_list(buffer); - - // Need to sort buffer - sort_buffer(buffer); - sort_buffer(buffer_ok); - - BOOST_REQUIRE(buffer_ok == buffer); +BOOST_AUTO_TEST_CASE(DB_app_positive) +{ + std::list<app_t> buffer; + app_t app1("app_1", "pkg_1", 5001, {}); + chain_t chain2 = {"cert2"}; + app_t app2("app_2", "pkg 2", 5002, {chain2}); + chain_t chain2r = {"cert2r"}; + app_t app2r("app_2_remove", "pkg 2", 5002, {chain2, chain2r}); + chain_t chain31 = {"cert_3.1", "cert 3.2"}; + chain_t chain32 = {"cert_3.1"}; + app_t app3("app 3", "pkg 3", 5003, {chain31, chain32}); + chain_t chain41 = {"cert_4.1", "cert 4.2"}; + chain_t chain42 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; + chain_t chain43 = {"cert_4.3.1"}; + app_t app4("app 4", "pkg 4", 5004, {chain41, chain42, chain43}); + BOOST_REQUIRE(add_app_to_check_list(app1) == true); + BOOST_REQUIRE(add_app_to_check_list(app2) == true); + BOOST_REQUIRE(add_app_to_check_list(app2r) == true); + BOOST_REQUIRE(add_app_to_check_list(app3) == true); + BOOST_REQUIRE(add_app_to_check_list(app4) == true); + mark_as_verified(app2, app_t::verified_t::NO); + mark_as_verified(app3, app_t::verified_t::YES); + remove_app_from_check_list(app2r); + app2.verified = app_t::verified_t::NO; + app3.verified = app_t::verified_t::YES; + std::list<app_t> buffer_ok = {app1, app2, app3, app4}; + get_app_list(buffer); + // Need to sort buffer + sort_buffer(buffer); + sort_buffer(buffer_ok); + BOOST_REQUIRE(buffer_ok == buffer); } -BOOST_AUTO_TEST_CASE(DB_app_negative) { - - std::list<app_t> buffer; - app_t app1("app_1", "pkg_1", 5001, {}); - - chain_t chain2 = {"cert2"}; - app_t app2("app_2", "pkg 2", 5002, {chain2}); - - chain_t chain2r = {"cert2r"}; - app_t app2r("app_2_remove", "pkg 2", 5002, {chain2, chain2r}); - - chain_t chain31 = {"cert_3.1", "cert 3.2"}; - chain_t chain32 = {"cert_3.1"}; - app_t app3("app 3", "pkg 3", 5003, {chain31, chain32}); - - chain_t chain41 = {"cert_4.1", "cert 4.2"}; - chain_t chain42 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; - chain_t chain43 = {"cert_4.3.1"}; - - app_t app4("app 4", "pkg 4", 5004, {chain41, chain42, chain43}); - - BOOST_REQUIRE(add_app_to_check_list(app1)==true); - BOOST_REQUIRE(add_app_to_check_list(app2)==true); - BOOST_REQUIRE(add_app_to_check_list(app2r)==true); - // Skipp adding app3 to database - BOOST_REQUIRE(add_app_to_check_list(app4)==true); - - mark_as_verified(app2, app_t::verified_t::NO); - mark_as_verified(app3, app_t::verified_t::YES); - remove_app_from_check_list(app2r); - - app2.verified = app_t::verified_t::NO; - app3.verified = app_t::verified_t::YES; - - std::list<app_t> buffer_ok = {app1, app2, app3, app4}; - - get_app_list(buffer); - - // list has to be sorted before comparison. - sort_buffer(buffer); - sort_buffer(buffer_ok); - BOOST_REQUIRE(buffer_ok != buffer); +BOOST_AUTO_TEST_CASE(DB_app_negative) +{ + std::list<app_t> buffer; + app_t app1("app_1", "pkg_1", 5001, {}); + chain_t chain2 = {"cert2"}; + app_t app2("app_2", "pkg 2", 5002, {chain2}); + chain_t chain2r = {"cert2r"}; + app_t app2r("app_2_remove", "pkg 2", 5002, {chain2, chain2r}); + chain_t chain31 = {"cert_3.1", "cert 3.2"}; + chain_t chain32 = {"cert_3.1"}; + app_t app3("app 3", "pkg 3", 5003, {chain31, chain32}); + chain_t chain41 = {"cert_4.1", "cert 4.2"}; + chain_t chain42 = {"cert_4.2.1", "cert 4.2.2", "cert 4.2.3"}; + chain_t chain43 = {"cert_4.3.1"}; + app_t app4("app 4", "pkg 4", 5004, {chain41, chain42, chain43}); + BOOST_REQUIRE(add_app_to_check_list(app1) == true); + BOOST_REQUIRE(add_app_to_check_list(app2) == true); + BOOST_REQUIRE(add_app_to_check_list(app2r) == true); + // Skipp adding app3 to database + BOOST_REQUIRE(add_app_to_check_list(app4) == true); + mark_as_verified(app2, app_t::verified_t::NO); + mark_as_verified(app3, app_t::verified_t::YES); + remove_app_from_check_list(app2r); + app2.verified = app_t::verified_t::NO; + app3.verified = app_t::verified_t::YES; + std::list<app_t> buffer_ok = {app1, app2, app3, app4}; + get_app_list(buffer); + // list has to be sorted before comparison. + sort_buffer(buffer); + sort_buffer(buffer_ok); + BOOST_REQUIRE(buffer_ok != buffer); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_logic.cpp b/tests/test_logic.cpp index 56c8290..2b80aff 100644 --- a/tests/test_logic.cpp +++ b/tests/test_logic.cpp @@ -37,436 +37,315 @@ namespace { std::string log_apps(std::list<app_t> &apps, std::list<app_t> buff) { - std::string ret = "\nApps:\n"; + std::string ret = "\nApps:\n"; - for (const auto &iter : apps) { - ret += iter.str() + "\n"; - } + for (const auto &iter : apps) { + ret += iter.str() + "\n"; + } - ret += "Buff:\n"; - for (const auto &iter : buff) { - ret+= iter.str() + "\n"; - } + ret += "Buff:\n"; - return ret; + for (const auto &iter : buff) { + ret += iter.str() + "\n"; + } + + return ret; } } // anonymous namespace BOOST_FIXTURE_TEST_SUITE(LOGIC_TEST, LogicWrapper) -BOOST_AUTO_TEST_CASE(logic_setup) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - // double setup - BOOST_REQUIRE(setup() == NO_ERROR); - - // double setup - BOOST_REQUIRE(setup() == NO_ERROR); +BOOST_AUTO_TEST_CASE(logic_setup) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + // double setup + BOOST_REQUIRE(setup() == NO_ERROR); + // double setup + BOOST_REQUIRE(setup() == NO_ERROR); } -BOOST_AUTO_TEST_CASE(logic_workflow_mixed) { - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_1", 5001, {}); - pkgmgr_install_manual_(app2); - - app_t app3("app_2", "pkg_2", 5001, {}); - pkgmgr_install_manual_(app3); - - // remove app 2 - pkgmgr_uninstall_manual_(app2); - - wait_for_worker(3, 1); - - std::list<app_t> buff = get_buffer_(); - std::list<app_t> apps = {app1, app2, app3}; - BOOST_REQUIRE(buff != apps); - - apps = {app1, app3}; - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - // Add other apps - pkgmgr_install_manual_(app2); - - // install the same app again - // it should never happen in real workflow - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5002, {}); - pkgmgr_install_manual_(app4); - - wait_for_worker(3); - - buff = get_buffer_(); - BOOST_REQUIRE(buff != apps); - - apps = {app1, app3, app2, app4}; - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - // turn on the Internet - buffer should be processed - connman_callback_manual_(true); - - wait_for_worker(0, 0, 4); - buff = get_buffer_(); - BOOST_CHECK(buff.empty()); +BOOST_AUTO_TEST_CASE(logic_workflow_mixed) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_1", 5001, {}); + pkgmgr_install_manual_(app2); + app_t app3("app_2", "pkg_2", 5001, {}); + pkgmgr_install_manual_(app3); + // remove app 2 + pkgmgr_uninstall_manual_(app2); + wait_for_worker(3, 1); + std::list<app_t> buff = get_buffer_(); + std::list<app_t> apps = {app1, app2, app3}; + BOOST_REQUIRE(buff != apps); + apps = {app1, app3}; + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + // Add other apps + pkgmgr_install_manual_(app2); + // install the same app again + // it should never happen in real workflow + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5002, {}); + pkgmgr_install_manual_(app4); + wait_for_worker(3); + buff = get_buffer_(); + BOOST_REQUIRE(buff != apps); + apps = {app1, app3, app2, app4}; + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + // turn on the Internet - buffer should be processed + connman_callback_manual_(true); + wait_for_worker(0, 0, 4); + buff = get_buffer_(); + BOOST_CHECK(buff.empty()); } -BOOST_AUTO_TEST_CASE(logic_workflow_mixed_2) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app2); - - app_t app3("app_3", "pkg_3", 5003, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed - pkgmgr_install_manual_(app4); - - app_t app5("app_5", "pkg_5", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail - pkgmgr_install_manual_(app5); - - // turn on the Internet - buffer should be processed - connman_callback_manual_(true); - - wait_for_worker(5, 0, 5); - std::list<app_t> buff = get_buffer_(); +BOOST_AUTO_TEST_CASE(logic_workflow_mixed_2) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 5003, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed + pkgmgr_install_manual_(app4); + app_t app5("app_5", "pkg_5", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail + pkgmgr_install_manual_(app5); + // turn on the Internet - buffer should be processed + connman_callback_manual_(true); + wait_for_worker(5, 0, 5); + std::list<app_t> buff = get_buffer_(); #if POPUP - std::list<app_t> apps = {app3, app5}; + std::list<app_t> apps = {app3, app5}; #else - std::list<app_t> apps = {app3}; // only if popup is disabled + std::list<app_t> apps = {app3}; // only if popup is disabled #endif - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); } -BOOST_AUTO_TEST_CASE(logic_workflow_mixed_3) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app2); - - app_t app3("app_3", "pkg_3", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed - pkgmgr_install_manual_(app4); - - app_t app5("app_5", "pkg_5", 5005, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app5); - - app_t app6("app_6", "pkg_6", 101, {{"OCSP_APP_REVOKED"}}); // popup will fail - pkgmgr_install_manual_(app6); - - wait_for_worker(6); - - std::list<app_t> buff = get_buffer_(); - std::list<app_t> apps = {app1, app2, app3, app4, app5, app6}; - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - connman_callback_manual_(true); - wait_for_worker(0, 0, 6); - buff = get_buffer_(); +BOOST_AUTO_TEST_CASE(logic_workflow_mixed_3) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed + pkgmgr_install_manual_(app4); + app_t app5("app_5", "pkg_5", 5005, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app5); + app_t app6("app_6", "pkg_6", 101, {{"OCSP_APP_REVOKED"}}); // popup will fail + pkgmgr_install_manual_(app6); + wait_for_worker(6); + std::list<app_t> buff = get_buffer_(); + std::list<app_t> apps = {app1, app2, app3, app4, app5, app6}; + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + connman_callback_manual_(true); + wait_for_worker(0, 0, 6); + buff = get_buffer_(); #if POPUP - apps = {app1, app3, app6}; + apps = {app1, app3, app6}; #else - apps = {app1}; // only if popup is disabled + apps = {app1}; // only if popup is disabled #endif - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); } -BOOST_AUTO_TEST_CASE(logic_workflow_mixed_4) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {}); - pkgmgr_install_manual_(app1); - - wait_for_worker(1); - - std::list<app_t> apps = {app1}; - std::list<app_t> buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app2); - - wait_for_worker(1); - - apps = {app1, app2}; - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - app_t app3("app_3", "pkg_3", 5003, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app3); - - wait_for_worker(1); - - apps = {app1, app2, app3}; - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed - pkgmgr_install_manual_(app4); - - wait_for_worker(1); - - apps = {app1, app2, app3, app4}; - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - app_t app5("app_5", "pkg_5", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail - pkgmgr_install_manual_(app5); - - wait_for_worker(1); - - apps = {app1, app2, app3, app4, app5}; - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); +BOOST_AUTO_TEST_CASE(logic_workflow_mixed_4) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {}); + pkgmgr_install_manual_(app1); + wait_for_worker(1); + std::list<app_t> apps = {app1}; + std::list<app_t> buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app2); + wait_for_worker(1); + apps = {app1, app2}; + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + app_t app3("app_3", "pkg_3", 5003, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app3); + wait_for_worker(1); + apps = {app1, app2, app3}; + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); // popup will succeed + pkgmgr_install_manual_(app4); + wait_for_worker(1); + apps = {app1, app2, app3, app4}; + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + app_t app5("app_5", "pkg_5", 100, {{"OCSP_APP_REVOKED"}}); // popup will fail + pkgmgr_install_manual_(app5); + wait_for_worker(1); + apps = {app1, app2, app3, app4, app5}; + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); } // OCSP_CHECK_AGAIN - apps should stay in buffer -BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_CHECK_AGAIN) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app2); - - app_t app3("app_3", "pkg_3", 100, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_CHECK_AGAIN"}}); - pkgmgr_install_manual_(app4); - - connman_callback_manual_(true); - - wait_for_worker(4, 0, 4); - - std::list<app_t> buff = get_buffer_(); - std::list<app_t> apps = {app1, app2, app3, app4}; - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - connman_callback_manual_(true); - - wait_for_worker(0, 0, 4); - - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); +BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_CHECK_AGAIN) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 100, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_CHECK_AGAIN"}}); + pkgmgr_install_manual_(app4); + connman_callback_manual_(true); + wait_for_worker(4, 0, 4); + std::list<app_t> buff = get_buffer_(); + std::list<app_t> apps = {app1, app2, app3, app4}; + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + connman_callback_manual_(true); + wait_for_worker(0, 0, 4); + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); } // OCSP_CERT_ERROR - apps should be removed from buffer // OCSP_APP_OK should have the same effect -BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_CERT_ERROR) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app2); - - - app_t app3("app_3", "pkg_3", 100, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_CERT_ERROR"}}); - pkgmgr_install_manual_(app4); - - connman_callback_manual_(true); - wait_for_worker(4, 0, 4); - std::list<app_t> buff = get_buffer_(); - - BOOST_REQUIRE(buff.empty()); - - connman_callback_manual_(true); - - wait_for_worker(); - - buff = get_buffer_(); - BOOST_REQUIRE(buff.empty()); - - connman_callback_manual_(true); - - wait_for_worker(); - - buff = get_buffer_(); - BOOST_REQUIRE(buff.empty()); +BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_CERT_ERROR) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 100, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_CERT_ERROR"}}); + pkgmgr_install_manual_(app4); + connman_callback_manual_(true); + wait_for_worker(4, 0, 4); + std::list<app_t> buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); + connman_callback_manual_(true); + wait_for_worker(); + buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); + connman_callback_manual_(true); + wait_for_worker(); + buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); } // OCSP_APP_REVOKED - popup OK - apps should be removed from buffer -BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_APP_REVOKED) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 5001, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 5002, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app2); - - app_t app3("app_3", "pkg_3", 5003, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app4); - - connman_callback_manual_(true); - wait_for_worker(4, 0, 4); - - std::list<app_t> buff = get_buffer_(); - - BOOST_REQUIRE(buff.empty()); - - connman_callback_manual_(true); - - wait_for_worker(); - - buff = get_buffer_(); - BOOST_REQUIRE(buff.empty()); - - connman_callback_manual_(true); - - wait_for_worker(); - - buff = get_buffer_(); - BOOST_REQUIRE(buff.empty()); +BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_APP_REVOKED) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 5001, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 5002, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 5003, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 5004, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app4); + connman_callback_manual_(true); + wait_for_worker(4, 0, 4); + std::list<app_t> buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); + connman_callback_manual_(true); + wait_for_worker(); + buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); + connman_callback_manual_(true); + wait_for_worker(); + buff = get_buffer_(); + BOOST_REQUIRE(buff.empty()); } // OCSP_APP_REVOKED - popup fail - apps should stay in buffer -BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_APP_REVOKED_2) { - - BOOST_REQUIRE(setup() == NO_ERROR); - - wait_for_worker(); - - // turn off the network - connman_callback_manual_(false); - - // add applications: - app_t app1("app_1", "pkg_1", 1001, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app1); - - app_t app2("app_2", "pkg_2", 1002, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app2); - - app_t app3("app_3", "pkg_3", 1003, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app3); - - app_t app4("app_4", "pkg_4", 1004, {{"OCSP_APP_REVOKED"}}); - pkgmgr_install_manual_(app4); - - connman_callback_manual_(true); - - wait_for_worker(4, 0, 4); - - std::list<app_t> buff = get_buffer_(); - std::list<app_t> apps = {app1, app2, app3, app4}; - - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - connman_callback_manual_(true); - - wait_for_worker(0, 0, 4); - - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); - - connman_callback_manual_(true); - - wait_for_worker(0, 0, 4); - - buff = get_buffer_(); - BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); +BOOST_AUTO_TEST_CASE(logic_workflow_OCSP_APP_REVOKED_2) +{ + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // turn off the network + connman_callback_manual_(false); + // add applications: + app_t app1("app_1", "pkg_1", 1001, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app1); + app_t app2("app_2", "pkg_2", 1002, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app2); + app_t app3("app_3", "pkg_3", 1003, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app3); + app_t app4("app_4", "pkg_4", 1004, {{"OCSP_APP_REVOKED"}}); + pkgmgr_install_manual_(app4); + connman_callback_manual_(true); + wait_for_worker(4, 0, 4); + std::list<app_t> buff = get_buffer_(); + std::list<app_t> apps = {app1, app2, app3, app4}; + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + connman_callback_manual_(true); + wait_for_worker(0, 0, 4); + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); + connman_callback_manual_(true); + wait_for_worker(0, 0, 4); + buff = get_buffer_(); + BOOST_CHECK_MESSAGE(buff == apps, log_apps(apps, buff)); } -BOOST_AUTO_TEST_CASE(logic_workflow_timer) { - - // Wait for setup. - BOOST_REQUIRE(setup() == NO_ERROR); - wait_for_worker(); - - // Job() will run. Install process. - timerStart(1); - wait_for_worker(5); - timerStop(); - - // If Timer is not work, wait_for_worker throw exception. - BOOST_REQUIRE(true); +BOOST_AUTO_TEST_CASE(logic_workflow_timer) +{ + // Wait for setup. + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // Job() will run. Install process. + timerStart(1); + wait_for_worker(5); + timerStop(); + // If Timer is not work, wait_for_worker throw exception. + BOOST_REQUIRE(true); } -BOOST_AUTO_TEST_CASE(logic_workflow_gio_timeout) { - - // Wait for setup. - BOOST_REQUIRE(setup() == NO_ERROR); - wait_for_worker(); - - // Run gmainloop. - run(3); - - BOOST_REQUIRE(is_running() == false); +BOOST_AUTO_TEST_CASE(logic_workflow_gio_timeout) +{ + // Wait for setup. + BOOST_REQUIRE(setup() == NO_ERROR); + wait_for_worker(); + // Run gmainloop. + run(3); + BOOST_REQUIRE(is_running() == false); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/test_queue.cpp b/tests/test_queue.cpp index dd1f51e..fbf7000 100644 --- a/tests/test_queue.cpp +++ b/tests/test_queue.cpp @@ -33,98 +33,77 @@ using namespace CCHECKER; BOOST_FIXTURE_TEST_SUITE(QUEUE_TEST, Queue) -BOOST_AUTO_TEST_CASE(Queue_operators) { - app_t app1("app_id1", "pkg_id1", 1, {}); - app_t app2("app_id2", "pkg_id2", 2, {}); - app_t app3("app_id@", "###", 3, {}); - - event_t ev1(app1, event_t::event_type_t::APP_INSTALL); - event_t ev2(app1, event_t::event_type_t::APP_UNINSTALL); - - BOOST_REQUIRE(ev1 == ev1); - BOOST_REQUIRE(ev1 != ev2); - BOOST_REQUIRE(ev2 != ev1); - BOOST_REQUIRE(ev2 == ev2); +BOOST_AUTO_TEST_CASE(Queue_operators) +{ + app_t app1("app_id1", "pkg_id1", 1, {}); + app_t app2("app_id2", "pkg_id2", 2, {}); + app_t app3("app_id@", "###", 3, {}); + event_t ev1(app1, event_t::event_type_t::APP_INSTALL); + event_t ev2(app1, event_t::event_type_t::APP_UNINSTALL); + BOOST_REQUIRE(ev1 == ev1); + BOOST_REQUIRE(ev1 != ev2); + BOOST_REQUIRE(ev2 != ev1); + BOOST_REQUIRE(ev2 == ev2); } -BOOST_AUTO_TEST_CASE(Queue) { - - app_t app1("app_id1", "pkg_id1", 1, {}); - app_t app2("app_id2", "pkg_id2", 2, {}); - app_t app3("app_id@", "###", 3, {}); - - event_t ev1(app1, event_t::event_type_t::APP_INSTALL); - event_t ev2(app1, event_t::event_type_t::APP_UNINSTALL); - - event_t ev3(app2, event_t::event_type_t::APP_INSTALL); - event_t ev4(app2, event_t::event_type_t::APP_UNINSTALL); - - event_t ev; - - BOOST_REQUIRE(empty() == true); - BOOST_REQUIRE(pop_event(ev) == false); - BOOST_REQUIRE(empty() == true); - push_event(ev1); - BOOST_REQUIRE(empty() == false); - - BOOST_REQUIRE(pop_event(ev) == true); - BOOST_REQUIRE(ev1 == ev); - - BOOST_REQUIRE(empty() == true); - - push_event(ev2); - push_event(ev3); - BOOST_REQUIRE(empty() == false); - - BOOST_REQUIRE(pop_event(ev) == true); - BOOST_REQUIRE(ev2 == ev); - - BOOST_REQUIRE(pop_event(ev) == true); - BOOST_REQUIRE(ev3 == ev); - - - BOOST_REQUIRE(empty() == true); - BOOST_REQUIRE(pop_event(ev) == false); - push_event(ev4); - BOOST_REQUIRE(empty() == false); - BOOST_REQUIRE(pop_event(ev) == true); - BOOST_REQUIRE(pop_event(ev) == false); - BOOST_REQUIRE(pop_event(ev) == false); - BOOST_REQUIRE(empty() == true); - - push_event(ev4); - - BOOST_REQUIRE(pop_event(ev) == true); - BOOST_REQUIRE(ev4 == ev); - - - BOOST_REQUIRE(pop_event(ev) == false); - BOOST_REQUIRE(empty() == true); +BOOST_AUTO_TEST_CASE(Queue) +{ + app_t app1("app_id1", "pkg_id1", 1, {}); + app_t app2("app_id2", "pkg_id2", 2, {}); + app_t app3("app_id@", "###", 3, {}); + event_t ev1(app1, event_t::event_type_t::APP_INSTALL); + event_t ev2(app1, event_t::event_type_t::APP_UNINSTALL); + event_t ev3(app2, event_t::event_type_t::APP_INSTALL); + event_t ev4(app2, event_t::event_type_t::APP_UNINSTALL); + event_t ev; + BOOST_REQUIRE(empty() == true); + BOOST_REQUIRE(pop_event(ev) == false); + BOOST_REQUIRE(empty() == true); + push_event(ev1); + BOOST_REQUIRE(empty() == false); + BOOST_REQUIRE(pop_event(ev) == true); + BOOST_REQUIRE(ev1 == ev); + BOOST_REQUIRE(empty() == true); + push_event(ev2); + push_event(ev3); + BOOST_REQUIRE(empty() == false); + BOOST_REQUIRE(pop_event(ev) == true); + BOOST_REQUIRE(ev2 == ev); + BOOST_REQUIRE(pop_event(ev) == true); + BOOST_REQUIRE(ev3 == ev); + BOOST_REQUIRE(empty() == true); + BOOST_REQUIRE(pop_event(ev) == false); + push_event(ev4); + BOOST_REQUIRE(empty() == false); + BOOST_REQUIRE(pop_event(ev) == true); + BOOST_REQUIRE(pop_event(ev) == false); + BOOST_REQUIRE(pop_event(ev) == false); + BOOST_REQUIRE(empty() == true); + push_event(ev4); + BOOST_REQUIRE(pop_event(ev) == true); + BOOST_REQUIRE(ev4 == ev); + BOOST_REQUIRE(pop_event(ev) == false); + BOOST_REQUIRE(empty() == true); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(QUEUE_MULTI_THREAD_TEST, TestQueue) -BOOST_AUTO_TEST_CASE(TestQueue) { - - add_events_th (1); - BOOST_REQUIRE(pop_events() == true); - - add_events_th (2); - BOOST_REQUIRE(pop_events() == true); - - add_events_th (3); - BOOST_REQUIRE(pop_events() == true); - - add_events_th (5); - BOOST_REQUIRE(pop_events() == true); - - add_events_th (10); - BOOST_REQUIRE(pop_events() == true); - - add_events_th (20); - BOOST_REQUIRE(pop_events() == true); +BOOST_AUTO_TEST_CASE(TestQueue) +{ + add_events_th(1); + BOOST_REQUIRE(pop_events() == true); + add_events_th(2); + BOOST_REQUIRE(pop_events() == true); + add_events_th(3); + BOOST_REQUIRE(pop_events() == true); + add_events_th(5); + BOOST_REQUIRE(pop_events() == true); + add_events_th(10); + BOOST_REQUIRE(pop_events() == true); + add_events_th(20); + BOOST_REQUIRE(pop_events() == true); } BOOST_AUTO_TEST_SUITE_END() |