common/connection.cpp
common/cs-context.cpp
common/cs-detected.cpp
+ common/exception.cpp
common/wp-context.cpp
common/wp-result.cpp
common/kvp-container.cpp
#include "client/utils.h"
#include "common/dispatcher.h"
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
namespace Client {
DEBUG("Worker map traversing to erase! current iter tid: " << it->first);
if (!it->second.t.joinable())
- throw std::logic_error(FORMAT("All workers should be joinable "
- "but it isn't. tid: " << it->first));
+ ThrowExc(InternalError, "All workers should be joinable but it isn't. "
+ "tid: " << it->first);
if (!pred(*it)) {
++it;
auto it = m_workerMap.find(std::this_thread::get_id());
if (it == m_workerMap.end())
- throw std::logic_error(FORMAT("worker done but it's not registered in map. "
- "tid: " << std::this_thread::get_id()));
+ ThrowExc(InternalError, "worker done but it's not registered in map. "
+ "tid: " << std::this_thread::get_id());
it->second.isDone = true;
}
*/
#include "client/handle.h"
-#include <stdexcept>
#include <utility>
+#include "common/exception.h"
+
namespace Csr {
namespace Client {
m_ctx(std::forward<ContextShPtr>(context))
{
if (!m_ctx)
- throw std::logic_error("context shouldn't be null");
+ ThrowExc(InvalidParam, "context shouldn't be null");
}
Handle::~Handle()
#include <exception>
#include "common/audit/logger.h"
+#include "common/exception.h"
#include "csr/error.h"
__attribute__((constructor))
{
try {
return func();
+ } catch (const Exception &e) {
+ ERROR("Exception caught. code: " << e.error() << " message: " << e.what());
+ return e.error();
} catch (const std::bad_alloc &e) {
ERROR("memory allocation failed.");
return CSR_ERROR_OUT_OF_MEMORY;
#include <stdexcept>
#include <new>
+#include "common/exception.h"
+
namespace Csr {
BinaryQueue::BinaryQueue() : m_size(0)
return;
if (size > m_size)
- throw std::logic_error("protocol broken. no more binary to flatten in queue");
+ ThrowExc(SocketError, "protocol broken. no more binary to flatten in queue");
void *cur = bytes;
while (size > 0) {
if (m_buckets.empty())
- throw std::logic_error("protocol broken. no more buckets to extract");
+ ThrowExc(SocketError, "protocol broken. no more buckets to extract");
size_t count = std::min(size, m_buckets.front()->left);
cur = m_buckets.front()->extractTo(cur, count);
left(_size)
{
if (_data == nullptr || _size == 0)
- throw std::invalid_argument("Bucket construct failed.");
+ ThrowExc(InternalError, "Bucket construct failed.");
}
BinaryQueue::Bucket::~Bucket()
void *BinaryQueue::Bucket::extractTo(void *dest, size_t size)
{
if (dest == nullptr || size == 0)
- throw std::logic_error("logic error. invalid input to Bucket::extractTo.");
+ ThrowExc(InternalError, "logic error. invalid input to Bucket::extractTo.");
memcpy(dest, cur, size);
*/
#include "common/cs-context.h"
-#include <stdexcept>
-
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as int."));
+ ThrowExc(InternalError, "Invalid key[" << key << "] comes in to set as int.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as string."));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as string.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as string."));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as string.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as bool."));
+ ThrowExc(InternalError, "Invalid key[" << key << "] comes in to set as bool.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to get as int."));
+ ThrowExc(InternalError, "Invalid key[" << key << "] comes in to get as int.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to get as string."));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to get as string.");
}
}
void CsContext::get(int key, const char **value) const
{
if (value == nullptr)
- throw std::logic_error("invalud argument. output storage pointer is null.");
+ ThrowExc(InvalidParam, "output storage pointer is null.");
switch (static_cast<Key>(key)) {
case Key::PopupMessage:
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to get as string."));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to get as string.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to get as bool."));
+ ThrowExc(InternalError, "Invalid key[" << key << "] comes in to get as bool.");
}
}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+/*
+ * @file exception.h
+ * @author Kyungwook Tak (k.tak@samsung.com)
+ * @version 1.0
+ * @brief custom exception derived from std
+ */
+#include "common/exception.h"
+
+#include "common/audit/logger.h"
+
+namespace Csr {
+
+Exception::Exception(const char *file, const char *function, unsigned int line,
+ const std::string &message) :
+ m_message(FORMAT("[" << file << ":" << line << " " << function << "()]" <<
+ message))
+{
+}
+
+Exception::~Exception() noexcept
+{
+}
+
+const char *Exception::what() const noexcept
+{
+ return m_message.c_str();
+}
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+/*
+ * @file exception.h
+ * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * Kyungwook Tak (k.tak@samsung.com)
+ * @version 1.0
+ * @brief custom exception derived from std
+ */
+#pragma once
+
+#include <exception>
+#include <string>
+
+#include "common/audit/logger.h"
+#include "csr/error.h"
+
+namespace Csr {
+
+class Exception : public std::exception {
+public:
+ Exception(const char *file, const char *function, unsigned int line,
+ const std::string &message);
+ virtual ~Exception() noexcept;
+ virtual const char *what() const noexcept override;
+
+ virtual int error(void) const = 0;
+
+protected:
+ std::string m_message;
+};
+
+template <int Error = 0, Audit::LogLevel level = Audit::LogLevel::Error>
+class DerivedException : public Exception {
+public:
+ DerivedException(const char *file, const char *function, unsigned int line,
+ const std::string &message) :
+ Exception(file, function, line, message)
+ {
+ switch (level) {
+ case Audit::LogLevel::Error:
+ ERROR(message);
+ break;
+
+ case Audit::LogLevel::Warning:
+ WARN(message);
+ break;
+
+ case Audit::LogLevel::Info:
+ INFO(message);
+ break;
+
+ default:
+ DEBUG(message);
+ break;
+ }
+ }
+
+ virtual ~DerivedException() noexcept {}
+
+ virtual int error(void) const
+ {
+ return Error;
+ }
+};
+
+using DbFailed = DerivedException<CSR_ERROR_DB>;
+using InvalidParam = DerivedException<CSR_ERROR_INVALID_PARAMETER>;
+using InternalError = DerivedException<CSR_ERROR_SERVER>;
+using EngineError = DerivedException<CSR_ERROR_ENGINE_INTERNAL>;
+using SocketError = DerivedException<CSR_ERROR_SOCKET>;
+
+} // namespace Csr
+
+#define ThrowExc(name, MESSAGE) \
+ throw name(__FILE__, __FUNCTION__, __LINE__, FORMAT(MESSAGE))
*/
#include "common/kvp-container.h"
-#include <stdexcept>
+#include "common/exception.h"
namespace Csr {
void KvpContainer::set(int, int)
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::set(int, bool)
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::set(int, const std::string &)
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::set(int, const char *)
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::set(int, time_t)
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::get(int, int &) const
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::get(int, bool &) const
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::get(int, std::string &) const
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::get(int, const char **) const
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
void KvpContainer::get(int, time_t &) const
{
- throw std::logic_error("Not implemented key-value pair interface used!");
+ ThrowExc(InternalError, "Not implemented key-value pair interface used!");
}
-
}
*/
#include "common/mainloop.h"
-#include <exception>
-#include <stdexcept>
#include <system_error>
#include <sys/epoll.h>
#include <unistd.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
Mainloop::~Mainloop()
{
if (!m_isTimedOut && !m_callbacks.empty())
- throw std::logic_error("mainloop registered callbacks should be empty "
- "except timed out case");
+ ThrowExc(InternalError, "mainloop registered callbacks should be empty "
+ "except timed out case");
::close(m_pollfd);
}
{
/* TODO: use scoped-lock to thread safe on member variables */
if (m_callbacks.count(fd) != 0)
- throw std::logic_error(FORMAT("event source on fd[" << fd <<
- "] already added!"));
+ ThrowExc(InternalError, "event source on fd[" << fd << "] already added!");
DEBUG("Add event[" << event << "] source on fd[" << fd << "]");
{
/* TODO: use scoped-lock to thread safe on member variables */
if (m_callbacks.count(fd) == 0)
- throw std::logic_error(FORMAT("event source on fd[" << fd <<
- "] isn't added at all"));
+ ThrowExc(InternalError, "event source on fd[" << fd << "] isn't added at all");
DEBUG("Remove event source on fd[" << fd << "]");
- do {
+ {
m_callbacks.erase(fd);
if (::epoll_ctl(m_pollfd, EPOLL_CTL_DEL, fd, nullptr) == -1) {
if (errno == ENOENT)
- throw std::logic_error("Tried to delete epoll item which wasn't added");
+ ThrowExc(InternalError, "Tried to delete epoll item which wasn't added");
else
throw std::system_error(
std::error_code(errno, std::generic_category()),
"epoll_ctl failed to EPOLL_CTL_DEL.");
}
- } while (false);
+ }
}
void Mainloop::dispatch(int timeout)
int fd = event[i].data.fd;
if (m_callbacks.count(fd) == 0)
- throw std::logic_error(FORMAT(
- "event in on fd[" << fd << "] but associated callback isn't exist!"));
+ ThrowExc(InternalError, "event in on fd[" << fd <<
+ "] but associated callback isn't exist!");
if (event[i].events & (EPOLLHUP | EPOLLRDHUP)) {
INFO("peer connection closed on fd[" << fd << "]");
#include <sys/epoll.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
/* TODO: scoped-lock */
m_onNewConnection = [&](const ConnShPtr & connection) {
if (!connection)
- throw std::logic_error("onNewConnection called but ConnShPtr is nullptr.");
+ ThrowExc(InternalError, "onNewConnection called but ConnShPtr is nullptr.");
int fd = connection->getFd();
DEBUG("read event comes in to fd[" << fd << "]");
if (m_connectionRegistry.count(fd) == 0)
- throw std::logic_error(FORMAT("get event on fd[" << fd
- << "] but no associated connection exist"));
+ ThrowExc(InternalError, "get event on fd[" << fd <<
+ "] but no associated connection exist");
auto &conn = m_connectionRegistry[fd];
/* TODO: scoped-lock */
m_onCloseConnection = [&](const ConnShPtr & connection) {
if (!connection)
- throw std::logic_error("no connection to close");
+ ThrowExc(InternalError, "no connection to close");
int fd = connection->getFd();
if (m_connectionRegistry.count(fd) == 0)
- throw std::logic_error(FORMAT("no connection in registry to remove "
- "associated to fd[" << fd << "]"));
+ ThrowExc(InternalError, "no connection in registry to remove "
+ "associated to fd[" << fd << "]");
INFO("good-bye! close socket fd[" << fd << "]");
*/
#include "common/socket.h"
-#include <exception>
-#include <system_error>
-
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <systemd/sd-daemon.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
+
+namespace Csr {
namespace {
int n = ::sd_listen_fds(-1);
if (n < 0)
- throw std::system_error(std::error_code(), "failed to sd_listen_fds");
+ ThrowExc(SocketError, "failed to sd_listen_fds");
for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) {
if (::sd_is_socket_unix(fd, SOCK_STREAM, 1, path.c_str(), 0) > 0) {
}
}
- throw std::system_error(std::error_code(), "get systemd socket failed!");
-}
-
+ ThrowExc(SocketError, "get systemd socket failed!");
}
-namespace Csr {
+} // namespace anonymous
Socket::Socket(int fd) : m_fd(fd)
{
if (m_fd < 0)
- throw std::logic_error("Socket fd from constructor is invalid!!");
+ ThrowExc(SocketError, "Socket fd from constructor is invalid!!");
}
Socket::Socket(const std::string &path) : m_fd(createSystemdSocket(path))
Socket::Socket(Socket &&other)
{
- if (other.m_fd < 0)
- throw std::logic_error("Socket fd from move constructor is invalid!!");
-
m_fd = other.m_fd;
other.m_fd = 0;
}
if (this == &other)
return *this;
- if (other.m_fd < 0)
- throw std::logic_error("Socket fd from move assignment is invalid!!");
-
m_fd = other.m_fd;
other.m_fd = 0;
int fd = ::accept(m_fd, nullptr, nullptr);
if (fd < 0)
- throw std::system_error(
- std::error_code(errno, std::generic_category()),
- "socket accept failed!");
+ ThrowExc(SocketError, "socket accept failed with errno: " << errno);
INFO("Accept client success with fd: " << fd);
Socket Socket::connect(const std::string &path)
{
if (path.size() >= sizeof(sockaddr_un::sun_path))
- throw std::invalid_argument("socket path size too long!");
+ ThrowExc(InternalError, "socket path size too long!");
int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
- throw std::system_error(
- std::error_code(errno, std::generic_category()),
- "socket create failed!");
+ ThrowExc(SocketError, "Socket create failed with errno: " << errno);
sockaddr_un addr;
addr.sun_family = AF_UNIX;
if (::connect(fd, reinterpret_cast<sockaddr *>(&addr),
sizeof(sockaddr_un)) == -1)
- throw std::system_error(
- std::error_code(errno, std::generic_category()),
- "socket connect failed!");
+ ThrowExc(SocketError, "Socket connect failed with errno: " << errno);
INFO("Connect to CSR server success with fd:" << fd);
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
else
- throw std::system_error(
- std::error_code(errno, std::generic_category()),
- "socket read failed!");
+ ThrowExc(SocketError, "Socket read failed with errno: " << errno);
}
/* TODO: handle the case of more bytes in stream to read than buffer size */
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
else
- throw std::system_error(
- std::error_code(errno, std::generic_category()),
- "socket write failed!");
+ ThrowExc(SocketError, "Socket write failed with errno: " << errno);
}
total += bytes;
*/
#include "common/wp-context.h"
-#include <stdexcept>
-
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as int. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as int. value=" << value);
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as std::string. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as std::string. value=" << value);
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as char*. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as char*. value=" << value);
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as int. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as int. value=" << value);
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as std::string. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as std::string. value=" << value);
}
}
void WpContext::get(int key, const char **value) const
{
if (value == nullptr)
- throw std::logic_error("invalud argument. output storage pointer is null.");
+ ThrowExc(InvalidParam, "output storage pointer is null.");
switch (static_cast<Key>(key)) {
case Key::PopupMessage:
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key <<
- "] comes in to set as char*. value=" << value));
+ ThrowExc(InternalError, "Invalid key[" << key <<
+ "] comes in to set as char*. value=" << value);
}
}
*/
#include "common/wp-result.h"
-#include <stdexcept>
-
-#include "common/audit/logger.h"
-
namespace Csr {
WpResult::WpResult() :
* limitations under the License
*/
#include <iostream>
-#include <stdexcept>
#include "db/connection.h"
+#include "common/exception.h"
namespace Csr {
namespace Db {
m_filename(name)
{
if (::sqlite3_open_v2(m_filename.c_str(), &m_handle, flags, nullptr))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, "db connection ctor failed: " << getErrorMessage());
}
Connection::~Connection()
{
if (::sqlite3_exec(m_handle, query.c_str(), nullptr, nullptr,
nullptr) != SQLITE_OK)
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, "db connection exec failed: " << getErrorMessage());
return sqlite3_changes(m_handle);
}
#include <fstream>
#include <iostream>
-#include <stdexcept>
#include "db/query.h"
#include "db/statement.h"
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
namespace Db {
std::ifstream is(scriptPath);
if (is.fail())
- throw std::runtime_error(FORMAT("Cannot open script: " << scriptPath));
+ ThrowExc(DbFailed, "Cannot open script: " << scriptPath);
std::istreambuf_iterator<char> begin(is), end;
auto str = std::string(begin, end);
if (str.empty())
- throw std::runtime_error(FORMAT("Script file empty: " << scriptPath));
+ ThrowExc(DbFailed, "Script file empty: " << scriptPath);
return str;
}
{
if (!isTableExist(SCHEMA_INFO_TABLE)) {
WARN("Schema table doesn't exist. This case would be the first time of "
- "db manager instantiated in target");
+ "db manager instantiated in target");
return SchemaVersion::NOT_EXIST;
}
stmt.bind(DB_VERSION_STR);
if (!stmt.step())
- throw std::logic_error(FORMAT("schema info table should exist!"));
+ ThrowExc(DbFailed, "schema info table should exist!");
return stmt.getInt();
}
stmt.bind(sv);
if (stmt.exec() == 0)
- throw std::runtime_error(FORMAT("Failed to set schema version!"));
+ ThrowExc(DbFailed, "Failed to set schema version to: " << sv);
}
//===========================================================================
// ENGINE_STATE table
//===========================================================================
-int Manager::getEngineState(int engineId) noexcept
+int Manager::getEngineState(int engineId)
{
- try {
- Statement stmt(m_conn, Query::SEL_ENGINE_STATE);
+ Statement stmt(m_conn, Query::SEL_ENGINE_STATE);
- stmt.bind(engineId);
+ stmt.bind(engineId);
- return stmt.step() ? stmt.getInt() : -1;
- } catch (const std::exception &e) {
- ERROR("getEngineState failed. error_msg=" << e.what());
- return -1;
- }
+ return stmt.step() ? stmt.getInt() : -1;
}
-bool Manager::setEngineState(int engineId, int state) noexcept
+void Manager::setEngineState(int engineId, int state)
{
- try {
- Statement stmt(m_conn, Query::INS_ENGINE_STATE);
+ Statement stmt(m_conn, Query::INS_ENGINE_STATE);
- stmt.bind(engineId);
- stmt.bind(state);
+ stmt.bind(engineId);
+ stmt.bind(state);
- return stmt.exec() != 0;
- } catch (const std::exception &e) {
- ERROR("setEngineState failed. error_msg=" << e.what());
- return false;
- }
+ stmt.exec();
}
//===========================================================================
// SCAN_REQUEST table
//===========================================================================
-long Manager::getLastScanTime(const std::string &dir,
- const std::string &dataVersion) noexcept
+time_t Manager::getLastScanTime(const std::string &dir,
+ const std::string &dataVersion)
{
- try {
- Statement stmt(m_conn, Query::SEL_SCAN_REQUEST);
+ Statement stmt(m_conn, Query::SEL_SCAN_REQUEST);
- stmt.bind(dir);
- stmt.bind(dataVersion);
+ stmt.bind(dir);
+ stmt.bind(dataVersion);
- return stmt.step() ? static_cast<time_t>(stmt.getInt64()) : -1;
- } catch (const std::exception &e) {
- ERROR("getLastScanTime failed. error_msg=" << e.what());
- return -1;
- }
+ return stmt.step() ? static_cast<time_t>(stmt.getInt64()) : -1;
}
-bool Manager::insertLastScanTime(const std::string &dir, long scanTime,
- const std::string &dataVersion) noexcept
+void Manager::insertLastScanTime(const std::string &dir, long scanTime,
+ const std::string &dataVersion)
{
- try {
- Statement stmt(m_conn, Query::INS_SCAN_REQUEST);
+ Statement stmt(m_conn, Query::INS_SCAN_REQUEST);
- stmt.bind(dir);
- stmt.bind(static_cast<sqlite3_int64>(scanTime));
- stmt.bind(dataVersion);
-
- return stmt.exec() != 0;
- } catch (const std::exception &e) {
- ERROR("insertLastScanTime failed. error_msg=" << e.what());
- return false;
- }
+ stmt.bind(dir);
+ stmt.bind(static_cast<sqlite3_int64>(scanTime));
+ stmt.bind(dataVersion);
+ stmt.exec();
}
-bool Manager::deleteLastScanTime(const std::string &dir) noexcept
+void Manager::deleteLastScanTime(const std::string &dir)
{
- try {
- Statement stmt(m_conn, Query::DEL_SCAN_REQUEST_BY_DIR);
+ Statement stmt(m_conn, Query::DEL_SCAN_REQUEST_BY_DIR);
- stmt.bind(dir);
-
- stmt.exec();
- return true; // even if no rows are deleted
- } catch (const std::exception &e) {
- ERROR("deleteLastScanTime failed. error_msg=" << e.what());
- return false;
- }
+ stmt.bind(dir);
+ stmt.exec();
}
-bool Manager::cleanLastScanTime() noexcept
+void Manager::cleanLastScanTime()
{
- try {
- Statement stmt(m_conn, Query::DEL_SCAN_REQUEST);
+ Statement stmt(m_conn, Query::DEL_SCAN_REQUEST);
- stmt.exec();
-
- return true; // even if no rows are deleted
- } catch (const std::exception &e) {
- ERROR("cleanLastScanTime failed. error_msg=" << e.what());
- return false;
- }
+ stmt.exec();
}
//===========================================================================
// DETECTED_MALWARE_FILE table
//===========================================================================
-RowsShPtr Manager::getDetectedMalwares(const std::string &dir) noexcept
+RowsShPtr Manager::getDetectedMalwares(const std::string &dir)
{
- try {
- Statement stmt(m_conn, Query::SEL_DETECTED_BY_DIR);
- stmt.bind(dir);
-
- RowsShPtr rows = std::make_shared<std::vector<RowShPtr>>();
-
- while (stmt.step()) {
- RowShPtr row = std::make_shared<Row>();
-
- row->targetName = stmt.getText();
- row->dataVersion = stmt.getText();
- row->severity = static_cast<csr_cs_severity_level_e>(stmt.getInt());
- row->threat = static_cast<csr_cs_threat_type_e>(stmt.getInt());
- row->malwareName = stmt.getText();
- row->detailedUrl = stmt.getText();
- row->ts = static_cast<time_t>(stmt.getInt64());
- row->isIgnored = static_cast<bool>(stmt.getInt());
-
- rows->emplace_back(std::move(row));
- }
-
- return rows;
- } catch (const std::exception &e) {
- ERROR("getDetectedMalwares failed. error_msg=" << e.what());
- return nullptr;
- }
-}
-
-RowShPtr Manager::getDetectedMalware(const std::string &path) noexcept
-{
- try {
- Statement stmt(m_conn, Query::SEL_DETECTED_BY_PATH);
- stmt.bind(path);
+ Statement stmt(m_conn, Query::SEL_DETECTED_BY_DIR);
+ stmt.bind(dir);
- if (!stmt.step())
- return nullptr;
+ RowsShPtr rows = std::make_shared<std::vector<RowShPtr>>();
+ while (stmt.step()) {
RowShPtr row = std::make_shared<Row>();
+
row->targetName = stmt.getText();
row->dataVersion = stmt.getText();
row->severity = static_cast<csr_cs_severity_level_e>(stmt.getInt());
row->ts = static_cast<time_t>(stmt.getInt64());
row->isIgnored = static_cast<bool>(stmt.getInt());
- return row;
- } catch (const std::exception &e) {
- ERROR("getDetectedMalware failed. error_msg=" << e.what());
- return nullptr;
+ rows->emplace_back(std::move(row));
}
-}
-bool Manager::insertDetectedMalware(const CsDetected &d,
- const std::string &dataVersion,
- bool isIgnored) noexcept
-{
- try {
- Statement stmt(m_conn, Query::INS_DETECTED);
-
- stmt.bind(d.targetName);
- stmt.bind(dataVersion);
- stmt.bind(static_cast<int>(d.severity));
- stmt.bind(static_cast<int>(d.threat));
- stmt.bind(d.malwareName);
- stmt.bind(d.detailedUrl);
- stmt.bind(static_cast<sqlite3_int64>(d.ts));
- stmt.bind(static_cast<int>(isIgnored));
-
- return stmt.exec() == 1;
- } catch (const std::exception &e) {
- ERROR("insertDetectedMalware failed. error_msg=" << e.what());
- return false;
- }
+ return rows;
}
-bool Manager::setDetectedMalwareIgnored(const std::string &path,
- bool flag) noexcept
+RowShPtr Manager::getDetectedMalware(const std::string &path)
{
- try {
- Statement stmt(m_conn, Query::UPD_DETECTED_INGNORED);
+ Statement stmt(m_conn, Query::SEL_DETECTED_BY_PATH);
+ stmt.bind(path);
- stmt.bind(flag);
- stmt.bind(path);
+ if (!stmt.step())
+ return nullptr;
- return stmt.exec() == 1;
- } catch (const std::exception &e) {
- ERROR("setDetectedMalwareIgnored failed. error_msg=" << e.what());
- return false;
- }
+ RowShPtr row = std::make_shared<Row>();
+
+ row->targetName = stmt.getText();
+ row->dataVersion = stmt.getText();
+ row->severity = static_cast<csr_cs_severity_level_e>(stmt.getInt());
+ row->threat = static_cast<csr_cs_threat_type_e>(stmt.getInt());
+ row->malwareName = stmt.getText();
+ row->detailedUrl = stmt.getText();
+ row->ts = static_cast<time_t>(stmt.getInt64());
+ row->isIgnored = static_cast<bool>(stmt.getInt());
+
+ return row;
}
-bool Manager::deleteDetectedMalware(const std::string &path) noexcept
+void Manager::insertDetectedMalware(const CsDetected &d,
+ const std::string &dataVersion,
+ bool isIgnored)
{
- try {
- Statement stmt(m_conn, Query::DEL_DETECTED_BY_PATH);
-
- stmt.bind(path);
+ Statement stmt(m_conn, Query::INS_DETECTED);
+
+ stmt.bind(d.targetName);
+ stmt.bind(dataVersion);
+ stmt.bind(static_cast<int>(d.severity));
+ stmt.bind(static_cast<int>(d.threat));
+ stmt.bind(d.malwareName);
+ stmt.bind(d.detailedUrl);
+ stmt.bind(static_cast<sqlite3_int64>(d.ts));
+ stmt.bind(static_cast<int>(isIgnored));
+ stmt.exec();
+}
- stmt.exec();
+void Manager::setDetectedMalwareIgnored(const std::string &path,
+ bool flag)
+{
+ Statement stmt(m_conn, Query::UPD_DETECTED_INGNORED);
- return true; // even if no rows are deleted
- } catch (const std::exception &e) {
- ERROR("deleteDetectedMalware failed.error_msg=" << e.what());
- return false;
- }
+ stmt.bind(flag);
+ stmt.bind(path);
+ stmt.exec();
}
-bool Manager::deleteDeprecatedDetectedMalwares(const std::string &dir,
- const std::string &dataVersion) noexcept
+void Manager::deleteDetectedMalware(const std::string &path)
{
- try {
- Statement stmt(m_conn, Query::DEL_DETECTED_DEPRECATED);
+ Statement stmt(m_conn, Query::DEL_DETECTED_BY_PATH);
- stmt.bind(dir);
- stmt.bind(dataVersion);
+ stmt.bind(path);
+ stmt.exec();
+}
+
+void Manager::deleteDeprecatedDetectedMalwares(const std::string &dir,
+ const std::string &dataVersion)
+{
+ Statement stmt(m_conn, Query::DEL_DETECTED_DEPRECATED);
- stmt.exec();
+ stmt.bind(dir);
+ stmt.bind(dataVersion);
- return true; // even if no rows are deleted
- } catch (const std::exception &e) {
- ERROR("deleteDeprecatedDetectedMalwares failed.error_msg=" << e.what());
- return false;
- }
+ stmt.exec();
}
} // namespace Db
int getSchemaVersion();
// ENGINE_STATE
- int getEngineState(int engineId) noexcept;
- bool setEngineState(int engineId, int state) noexcept;
+ int getEngineState(int engineId);
+ void setEngineState(int engineId, int state);
// SCAN_REQUEST
- long getLastScanTime(const std::string &dir,
- const std::string &dataVersion) noexcept;
- bool insertLastScanTime(const std::string &dir, long scanTime,
- const std::string &dataVersion) noexcept;
- bool deleteLastScanTime(const std::string &dir) noexcept;
- bool cleanLastScanTime() noexcept;
+ time_t getLastScanTime(const std::string &dir, const std::string &dataVersion);
+ void insertLastScanTime(const std::string &dir, long scanTime,
+ const std::string &dataVersion);
+ void deleteLastScanTime(const std::string &dir);
+ void cleanLastScanTime();
// DETECTED_MALWARE_FILE & USER_RESPONSE
- RowsShPtr getDetectedMalwares(const std::string &dirpath) noexcept;
- RowShPtr getDetectedMalware(const std::string &filepath) noexcept;
- bool insertDetectedMalware(const CsDetected &, const std::string &dataVersion,
- bool isIgnored) noexcept;
- bool setDetectedMalwareIgnored(const std::string &path, bool flag) noexcept;
- bool deleteDetectedMalware(const std::string &path) noexcept;
- bool deleteDeprecatedDetectedMalwares(const std::string &dir,
- const std::string &dataVersion) noexcept;
+ RowsShPtr getDetectedMalwares(const std::string &dirpath);
+ RowShPtr getDetectedMalware(const std::string &filepath);
+ void insertDetectedMalware(const CsDetected &, const std::string &dataVersion,
+ bool isIgnored);
+ void setDetectedMalwareIgnored(const std::string &path, bool flag);
+ void deleteDetectedMalware(const std::string &path);
+ void deleteDeprecatedDetectedMalwares(const std::string &dir,
+ const std::string &dataVersion);
private:
void resetDatabase();
#include "db/statement.h"
#include <string>
-#include <stdexcept>
#include "db/connection.h"
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
namespace Db {
Statement::Statement(const Connection &db, const std::string &query) :
m_stmt(nullptr), m_bindingIndex(BindingStartIndex)
{
- switch (sqlite3_prepare_v2(db.get(), query.c_str(), query.size(), &m_stmt, nullptr)) {
+ switch (sqlite3_prepare_v2(db.get(), query.c_str(), query.size(), &m_stmt,
+ nullptr)) {
case SQLITE_OK:
m_bindParamCount = ::sqlite3_bind_parameter_count(m_stmt);
m_columnCount = ::sqlite3_column_count(m_stmt);
break;
default:
- throw std::runtime_error(db.getErrorMessage());
+ ThrowExc(DbFailed, db.getErrorMessage());
}
}
Statement::~Statement()
{
if (SQLITE_OK != ::sqlite3_finalize(m_stmt))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
void Statement::reset()
clearBindings();
if (::sqlite3_reset(m_stmt) != SQLITE_OK)
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
m_columnIndex = m_columnCount + 1;
}
void Statement::clearBindings() const
{
if (::sqlite3_clear_bindings(m_stmt) != SQLITE_OK)
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
m_bindingIndex = BindingStartIndex;
}
return false;
default:
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
}
int Statement::exec()
{
if (::sqlite3_step(m_stmt) != SQLITE_DONE)
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
// column cannot be 'get' after sqlite done, so make index overflow.
m_columnIndex = m_columnCount + 1;
void Statement::bind(int value) const
{
if (!isBindingIndexValid())
- throw std::logic_error("index overflowed when binding int to stmt.");
+ ThrowExc(DbFailed, "index overflowed when binding int to stmt.");
if (SQLITE_OK != ::sqlite3_bind_int(m_stmt, ++m_bindingIndex, value))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
void Statement::bind(sqlite3_int64 value) const
{
if (!isBindingIndexValid())
- throw std::logic_error("index overflowed when binding int64 to stmt.");
+ ThrowExc(DbFailed, "index overflowed when binding int64 to stmt.");
if (SQLITE_OK != ::sqlite3_bind_int64(m_stmt, ++m_bindingIndex, value))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
void Statement::bind(const std::string &value) const
{
if (!isBindingIndexValid())
- throw std::logic_error("index overflowed when binding string to stmt.");
+ ThrowExc(DbFailed, "index overflowed when binding string to stmt.");
- if (SQLITE_OK != ::sqlite3_bind_text(m_stmt, ++m_bindingIndex, value.c_str(), -1,
+ if (SQLITE_OK != ::sqlite3_bind_text(m_stmt, ++m_bindingIndex, value.c_str(),
+ -1,
SQLITE_STATIC))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
void Statement::bind(void) const
{
if (!isBindingIndexValid())
- throw std::logic_error("index overflowed when binding fields from row");
+ ThrowExc(DbFailed, "index overflowed when binding fields from row");
if (SQLITE_OK != ::sqlite3_bind_null(m_stmt, ++m_bindingIndex))
- throw std::runtime_error(getErrorMessage());
+ ThrowExc(DbFailed, getErrorMessage());
}
bool Statement::isNullColumn() const
{
if (!isColumnIndexValid())
- throw std::runtime_error(FORMAT("column isn't valud for index: " <<
- m_columnIndex));
+ ThrowExc(DbFailed, "column isn't valud for index: " << m_columnIndex);
return SQLITE_NULL == sqlite3_column_type(m_stmt, (m_columnIndex + 1));
}
int Statement::getInt() const
{
if (!isColumnIndexValid())
- throw std::logic_error("index overflowed when getting fields from row");
+ ThrowExc(DbFailed, "index overflowed when getting fields from row");
return sqlite3_column_int(m_stmt, ++m_columnIndex);
}
sqlite3_int64 Statement::getInt64() const
{
if (!isColumnIndexValid())
- throw std::logic_error("index overflowed when getting fields from row");
+ ThrowExc(DbFailed, "index overflowed when getting fields from row");
return sqlite3_column_int64(m_stmt, ++m_columnIndex);
}
const char *Statement::getText() const
{
if (!isColumnIndexValid())
- throw std::logic_error("index overflowed when getting fields from row");
+ ThrowExc(DbFailed, "index overflowed when getting fields from row");
- return reinterpret_cast<const char *>(sqlite3_column_text(m_stmt, ++m_columnIndex));
+ return reinterpret_cast<const char *>(sqlite3_column_text(m_stmt,
+ ++m_columnIndex));
}
} // namespace Db
#include "service/app-deleter.h"
#include <memory>
-#include <stdexcept>
#include <cstring>
#include <glib.h>
#include <package-manager.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
#define MAX_WAIT_SEC 10
bool AppDeleter::remove(const std::string &pkgid)
{
if (pkgid.empty())
- throw std::logic_error("pkgid shouldn't be empty in AppDeleter");
+ ThrowExc(InternalError, "pkgid shouldn't be empty in AppDeleter");
std::unique_ptr<pkgmgr_client, int(*)(pkgmgr_client *)> client(
pkgmgr_client_new(PC_REQUEST), pkgmgr_client_free);
* @version 1.0
* @brief
*/
+#include "service/core-usage.h"
-#include <stdexcept>
#include <sched.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
-#include "service/core-usage.h"
-
+#include "common/exception.h"
namespace Csr {
bool CpuUsageManager::setThreadCoreUsage(int percent)
{
if (percent > 100 || percent <= 0)
- throw std::runtime_error("invalid core usage percent.");
+ ThrowExc(InternalError, "invalid core usage percent: " << percent);
cpu_set_t set;
CPU_ZERO(&set);
CPU_ZERO(&usedCore);
if (sched_getaffinity(0, sizeof(cpu_set_t), &usedCore) != 0)
- throw std::runtime_error("sched_getaffinity failed.");
+ ThrowExc(InternalError, "sched_getaffinity failed.");
return CPU_COUNT(&usedCore);
}
*/
#include "service/cs-loader.h"
-#include <stdexcept>
#include <dlfcn.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
const std::string &rw_working_dir)
{
if (ro_res_dir.empty() || rw_working_dir.empty())
- throw std::invalid_argument("cs loader global init");
+ ThrowExc(InvalidParam, "cs loader global init");
return m_pc.fpGlobalInit(ro_res_dir.c_str(), rw_working_dir.c_str());
}
int CsLoader::contextDestroy(csre_cs_context_h c)
{
if (c == nullptr)
- throw std::invalid_argument("cs loader context destroy");
+ ThrowExc(InvalidParam, "cs loader context destroy");
return m_pc.fpContextDestroy(c);
}
csre_cs_detected_h *pdetected)
{
if (c == nullptr || data.empty() || pdetected == nullptr)
- throw std::invalid_argument("cs loader scan data");
+ ThrowExc(InvalidParam, "cs loader scan data");
return m_pc.fpScanData(c, data.data(), data.size(), pdetected);
}
csre_cs_detected_h *pdetected)
{
if (c == nullptr || filepath.empty() || pdetected == nullptr)
- throw std::invalid_argument("cs loader scan file");
+ ThrowExc(InvalidParam, "cs loader scan file");
return m_pc.fpScanFile(c, filepath.c_str(), pdetected);
}
csre_cs_detected_h *pdetected)
{
if (c == nullptr || appdir.empty() || pdetected == nullptr)
- throw std::invalid_argument("cs loader scan app on cloud");
+ ThrowExc(InvalidParam, "cs loader scan app on cloud");
return m_pc.fpScanAppOnCloud(c, appdir.c_str(), pdetected);
}
csre_cs_severity_level_e *pseverity)
{
if (d == nullptr || pseverity == nullptr)
- throw std::invalid_argument("cs loader get severity");
+ ThrowExc(InvalidParam, "cs loader get severity");
return m_pc.fpGetSeverity(d, pseverity);
}
csre_cs_threat_type_e *pthreat)
{
if (d == nullptr || pthreat == nullptr)
- throw std::invalid_argument("cs loader get threat type");
+ ThrowExc(InvalidParam, "cs loader get threat type");
return m_pc.fpGetThreatType(d, pthreat);
}
int CsLoader::getMalwareName(csre_cs_detected_h d, std::string &value)
{
if (d == nullptr)
- throw std::invalid_argument("cs loader get malware name");
+ ThrowExc(InvalidParam, "cs loader get malware name");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetMalwareName(d, cvalue);
int CsLoader::getDetailedUrl(csre_cs_detected_h d, std::string &value)
{
if (d == nullptr)
- throw std::invalid_argument("cs loader get detailed url");
+ ThrowExc(InvalidParam, "cs loader get detailed url");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetDetailedUrl(d, cvalue);
int CsLoader::getTimestamp(csre_cs_detected_h d, time_t *timestamp)
{
if (d == nullptr || timestamp == nullptr)
- throw std::invalid_argument("cs loader get time stamp");
+ ThrowExc(InvalidParam, "cs loader get time stamp");
return m_pc.fpGetTimestamp(d, timestamp);
}
int CsLoader::getEngineApiVersion(csre_cs_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get error string");
+ ThrowExc(InvalidParam, "cs loader get error string");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineApiVersion(e, cvalue);
int CsLoader::getEngineVendor(csre_cs_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get engine vendor");
+ ThrowExc(InvalidParam, "cs loader get engine vendor");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineVendor(e, cvalue);
int CsLoader::getEngineName(csre_cs_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get engine name");
+ ThrowExc(InvalidParam, "cs loader get engine name");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineName(e, cvalue);
int CsLoader::getEngineVersion(csre_cs_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get engine version");
+ ThrowExc(InvalidParam, "cs loader get engine version");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineName(e, cvalue);
int CsLoader::getEngineDataVersion(csre_cs_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get engine version");
+ ThrowExc(InvalidParam, "cs loader get engine version");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineDataVersion(e, cvalue);
int CsLoader::getEngineLatestUpdateTime(csre_cs_engine_h e, time_t *ptime)
{
if (e == nullptr || ptime == nullptr)
- throw std::invalid_argument("cs loader get latest update time");
+ ThrowExc(InvalidParam, "cs loader get latest update time");
return m_pc.fpGetEngineLatestUpdateTime(e, ptime);
}
csre_cs_activated_e *pactivated)
{
if (e == nullptr || pactivated == nullptr)
- throw std::invalid_argument("cs loader get engine activated");
+ ThrowExc(InvalidParam, "cs loader get engine activated");
return m_pc.fpGetEngineActivated(e, pactivated);
}
std::vector<unsigned char> &value)
{
if (e == nullptr)
- throw std::invalid_argument("cs loader get engine vendor logo");
+ ThrowExc(InvalidParam, "cs loader get engine vendor logo");
unsigned char *cvalue = nullptr;
unsigned int size = 0;
void *handle = dlopen(enginePath.c_str(), RTLD_LAZY);
if (handle == nullptr)
- throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath <<
- " errno: " << errno));
+ ThrowExc(InternalError, "engine dlopen error. path: " << enginePath <<
+ " errno: " << errno);
m_pc.dlhandle = handle;
m_pc.fpGetEngineLatestUpdateTime == nullptr ||
m_pc.fpGetEngineActivated == nullptr || m_pc.fpGetEngineVendorLogo == nullptr) {
dlclose(handle);
- throw std::runtime_error(FORMAT("Failed to load funcs from engine library. "
- "engine path: " << enginePath << "errno: " <<
- errno));
+ ThrowExc(EngineError, "Failed to load funcs from engine library. "
+ "engine path: " << enginePath << "errno: " << errno);
}
}
m_loader(loader), m_context(nullptr)
{
if (m_loader == nullptr)
- throw std::logic_error("invalid argument. shouldn't be null.");
+ ThrowExc(InvalidParam, "loader shouldn't be null.");
auto ret = m_loader->contextCreate(m_context);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get engine context by loader. ret: " << ret));
+ ThrowExc(EngineError, "get engine context by loader. ret: " << ret);
}
CsEngineContext::~CsEngineContext()
auto ret = m_loader->contextDestroy(m_context);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " <<
- ret));
+ ThrowExc(EngineError, "destroy engine context by loader. ret: " << ret);
}
csre_cs_context_h &CsEngineContext::get(void)
m_loader(loader), m_info(nullptr)
{
if (m_loader == nullptr)
- throw std::logic_error("invalid argument. shouldn't be null.");
+ ThrowExc(InvalidParam, "loader shouldn't be null.");
auto ret = m_loader->getEngineInfo(m_info);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get engine info by loader. ret: " << ret));
+ ThrowExc(EngineError, "get engine info by loader. ret: " << ret);
}
CsEngineInfo::~CsEngineInfo()
auto ret = m_loader->destroyEngine(m_info);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("destroy engine info by loader. ret: " << ret));
+ ThrowExc(EngineError, "destroy engine info by loader. ret: " << ret);
}
csre_cs_engine_h &CsEngineInfo::get(void)
*/
#include "service/file-system.h"
-#include <stdexcept>
+#include <system_error>
#include <stdio.h>
#include <string.h>
#include <errno.h>
while (true) {
if (readdir_r(m_currDir.get(), m_currEntry.get(), &result) != 0)
- throw std::runtime_error("exception occurred. reading dir = " + m_dirs.front());
+ throw std::system_error(std::error_code(),
+ FORMAT("reading dir = " << m_dirs.front()));
if (result == nullptr) { // end of dir stream
DEBUG("DirVisitor: end visiting. dir=" << m_dirs.front());
#include <string>
#include <utility>
#include <algorithm>
-#include <stdexcept>
#include "common/audit/logger.h"
+#include "common/exception.h"
#include "service/type-converter.h"
#include "service/file-system.h"
#include "ui/askuser.h"
SAMPLE_ENGINE_RW_WORKING_DIR);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("global init cs engine. ret: " << ret));
+ ThrowExc(EngineError, "global init cs engine. ret: " << ret);
CsEngineInfo csEngineInfo(m_cs);
ret = m_cs->getEngineDataVersion(csEngineInfo.get(), m_csDataVersion);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get cs engine data version. ret: " << ret));
+ ThrowExc(EngineError, "get cs engine data version. ret: " << ret);
ret = m_wp->globalInit(SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("global init wp engine. ret: " << ret));
+ ThrowExc(EngineError, "global init wp engine. ret: " << ret);
WpEngineInfo wpEngineInfo(m_wp);
ret = m_wp->getEngineDataVersion(wpEngineInfo.get(), m_wpDataVersion);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get wp engine data version. ret: " << ret));
+ ThrowExc(EngineError, "get wp engine data version. ret: " << ret);
DEBUG("Service logic ctor done");
}
int ret = m_cs->globalDeinit();
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("global deinit cs engine. ret: " << ret));
+ ThrowExc(EngineError, "global deinit cs engine. ret: " << ret);
ret = m_wp->globalDeinit();
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("global deinit wp engine. ret: " << ret));
+ ThrowExc(EngineError, "global deinit wp engine. ret: " << ret);
}
RawBuffer Logic::dispatch(const RawBuffer &in)
}
default:
- throw std::range_error(FORMAT("Command id[" << static_cast<int>(info.first) <<
- "] isn't in range."));
+ ThrowExc(InternalError, "Command id[" << static_cast<int>(info.first) <<
+ "] isn't in range.");
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid severity: " <<
- static_cast<int>(d.severity)));
+ ThrowExc(InternalError, "Invalid severity: " << static_cast<int>(d.severity));
}
return BinaryQueue::Serialize(ret, d).pop();
break;
default:
- throw std::logic_error(FORMAT("Invalid severity: " <<
- static_cast<int>(d.severity)));
+ ThrowExc(InternalError, "Invalid severity: " << static_cast<int>(d.severity));
}
m_db->insertDetectedMalware(d, m_csDataVersion, d.response == CSR_CS_IGNORE);
break;
default:
- throw std::logic_error(FORMAT("Invalid level: " <<
- static_cast<int>(wr.riskLevel)));
+ ThrowExc(InternalError, "Invalid level: " << static_cast<int>(wr.riskLevel));
}
return BinaryQueue::Serialize(ret, wr).pop();
int eret = m_cs->getSeverity(result, &eseverity);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting cs detected[seveirty]. "
- "ret: " << eret));
+ ThrowExc(EngineError, "getting severity of cs detected. ret: " << eret);
d.severity = Csr::convert(eseverity);
eret = m_cs->getThreatType(result, ðreat);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting cs detected[threat]. "
- "ret: " << eret));
+ ThrowExc(EngineError, "getting threat of cs detected. ret: " << eret);
d.threat = Csr::convert(ethreat);
eret = m_cs->getMalwareName(result, d.malwareName);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting cs detected[name]. "
- "ret: " << eret));
+ ThrowExc(EngineError, "getting malware name of cs detected. ret: " << eret);
// getting detailed url
eret = m_cs->getDetailedUrl(result, d.detailedUrl);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting cs detected[detailed url]. "
- "ret: " << eret));
+ ThrowExc(EngineError, "getting detailed url of cs detected. ret: " << eret);
// getting time stamp
eret = m_cs->getTimestamp(result, &d.ts);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting cs detected[timestamp]. "
- "ret: " << eret));
+ ThrowExc(EngineError, "getting time stamp of cs detected. ret: " << eret);
return d;
}
int eret = m_wp->getRiskLevel(r, &elevel);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret));
+ ThrowExc(EngineError, "getting risk level of wp result. ret: " << eret);
wr.riskLevel = Csr::convert(elevel);
eret = m_wp->getDetailedUrl(r, wr.detailedUrl);
if (eret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret));
+ ThrowExc(EngineError, "getting detailed url of wp result. ret: " << eret);
return wr;
}
*/
#include "service/thread-pool.h"
-#include <stdexcept>
#include <utility>
#include "common/audit/logger.h"
+#include "common/exception.h"
#define __BEGIN_CRITICAL__ { std::lock_guard<std::mutex> lock(this->m_mutex);
#define __END_CRITICAL__ }
m_stop(false)
{
if (m_min > m_max)
- throw std::logic_error("thread pool MIN shouldn't be bigger than MAX");
+ ThrowExc(InvalidParam, "thread pool MIN shouldn't be bigger than MAX");
for (size_t i = 0; i < m_min; i++)
add();
*/
#include "service/type-converter.h"
-#include <stdexcept>
-
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
return CSR_CS_SEVERITY_HIGH;
default:
- throw std::logic_error(FORMAT("Invalid eseverity: " << static_cast<int>(e)));
+ ThrowExc(InternalError, "Invalid eseverity: " << static_cast<int>(e));
}
}
return CSR_CS_THREAT_GENERIC;
default:
- throw std::logic_error(FORMAT("Invalid ethreat: " << static_cast<int>(e)));
+ ThrowExc(InternalError, "Invalid ethreat: " << static_cast<int>(e));
}
}
return CSR_WP_RISK_HIGH;
default:
- throw std::logic_error(FORMAT("Invalid elevel: " << static_cast<int>(e)));
+ ThrowExc(InternalError, "Invalid elevel: " << static_cast<int>(e));
}
}
*/
#include "service/wp-loader.h"
-#include <stdexcept>
#include <dlfcn.h>
#include "common/audit/logger.h"
+#include "common/exception.h"
namespace Csr {
int WpLoader::contextDestroy(csre_wp_context_h c)
{
if (c == nullptr)
- throw std::invalid_argument("wp loader context destroy");
+ ThrowExc(InvalidParam, "wp loader context destroy");
return m_pc.fpContextDestroy(c);
}
csre_wp_check_result_h *presult)
{
if (c == nullptr || url.empty() || presult == nullptr)
- throw std::invalid_argument("wp loader check url error");
+ ThrowExc(InvalidParam, "wp loader check url error");
return m_pc.fpCheckUrl(c, (const char *)url.c_str(), presult);
}
csre_wp_risk_level_e *plevel)
{
if (r == nullptr || plevel == nullptr)
- throw std::invalid_argument("wp loader Get Risk Level error");
+ ThrowExc(InvalidParam, "wp loader Get Risk Level error");
return m_pc.fpGetRiskLevel(r, plevel);
}
int WpLoader::getDetailedUrl(csre_wp_check_result_h r, std::string &value)
{
if (r == nullptr)
- throw std::invalid_argument("wp loader get detailed url error");
+ ThrowExc(InvalidParam, "wp loader get detailed url error");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetDetailedUrl(r, cvalue);
int WpLoader::getEngineApiVersion(csre_wp_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get error string");
+ ThrowExc(InvalidParam, "wp loader get error string");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineApiVersion(e, cvalue);
int WpLoader::getEngineVendor(csre_wp_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get engine vendor");
+ ThrowExc(InvalidParam, "wp loader get engine vendor");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineVendor(e, cvalue);
int WpLoader::getEngineName(csre_wp_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get engine name");
+ ThrowExc(InvalidParam, "wp loader get engine name");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineName(e, cvalue);
int WpLoader::getEngineVersion(csre_wp_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get engine version");
+ ThrowExc(InvalidParam, "wp loader get engine version");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineName(e, cvalue);
int WpLoader::getEngineDataVersion(csre_wp_engine_h e, std::string &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get engine version");
+ ThrowExc(InvalidParam, "wp loader get engine version");
return getValueCstr(value, [&](const char **cvalue) {
return m_pc.fpGetEngineDataVersion(e, cvalue);
int WpLoader::getEngineLatestUpdateTime(csre_wp_engine_h e, time_t *ptime)
{
if (e == nullptr || ptime == nullptr)
- throw std::invalid_argument("wp loader get latest update time");
+ ThrowExc(InvalidParam, "wp loader get latest update time");
return m_pc.fpGetEngineLatestUpdateTime(e, ptime);
}
csre_wp_activated_e *pactivated)
{
if (e == nullptr || pactivated == nullptr)
- throw std::invalid_argument("wp loader get engine activated");
+ ThrowExc(InvalidParam, "wp loader get engine activated");
return m_pc.fpGetEngineActivated(e, pactivated);
}
std::vector<unsigned char> &value)
{
if (e == nullptr)
- throw std::invalid_argument("wp loader get engine vendor logo");
+ ThrowExc(InvalidParam, "wp loader get engine vendor logo");
unsigned char *cvalue = nullptr;
unsigned int size = 0;
void *handle = dlopen(enginePath.c_str(), RTLD_LAZY);
if (handle == nullptr)
- throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath <<
- " errno: " << errno));
+ ThrowExc(InternalError, "engine dlopen error. path: " << enginePath <<
+ " errno: " << errno);
m_pc.dlhandle = handle;
m_pc.fpGetEngineLatestUpdateTime == nullptr ||
m_pc.fpGetEngineActivated == nullptr || m_pc.fpGetEngineVendorLogo == nullptr) {
dlclose(handle);
- throw std::runtime_error(FORMAT("Failed to load funcs from engine library. "
- "engine path: " << enginePath << "errno: " <<
- errno));
+ ThrowExc(EngineError, "Failed to load funcs from engine library. "
+ "engine path: " << enginePath << "errno: " << errno);
}
}
m_loader(loader), m_context(nullptr)
{
if (m_loader == nullptr)
- throw std::logic_error("invalid argument. shouldn't be null.");
+ ThrowExc(InvalidParam, "loader shouldn't be null.");
auto ret = m_loader->contextCreate(m_context);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get engine context by loader. ret: " << ret));
+ ThrowExc(EngineError, "get engine context by loader. ret: " << ret);
}
WpEngineContext::~WpEngineContext()
auto ret = m_loader->contextDestroy(m_context);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " <<
- ret));
+ ThrowExc(EngineError, "destroy engine context by loader. ret: " << ret);
}
csre_wp_context_h &WpEngineContext::get(void)
m_loader(loader), m_info(nullptr)
{
if (m_loader == nullptr)
- throw std::logic_error("invalid argument. shouldn't be null.");
+ ThrowExc(InvalidParam, "loader shouldn't be null.");
auto ret = m_loader->getEngineInfo(m_info);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("get engine info by loader. ret: " << ret));
+ ThrowExc(EngineError, "get engine info by loader. ret: " << ret);
}
WpEngineInfo::~WpEngineInfo()
auto ret = m_loader->destroyEngine(m_info);
if (ret != CSRE_ERROR_NONE)
- throw std::runtime_error(FORMAT("destroy engine info by loader. ret: " << ret));
+ ThrowExc(EngineError, "destroy engine info by loader. ret: " << ret);
}
csre_wp_engine_h &WpEngineInfo::get(void)
*/
#include "logic.h"
-#include <stdexcept>
#include <functional>
#include <unordered_map>
#include <Elementary.h>
#include "common/binary-queue.h"
#include "common/audit/logger.h"
+#include "common/exception.h"
#include "ui/common.h"
#include "csr/content-screening-types.h"
return false;
default:
- throw std::logic_error("Protocol error. unknown popup-service command id.");
+ ThrowExc(InternalError, "Protocol error. unknown popup-service command id.");
}
}
return csNotifyFile(message, d);
default:
- throw std::logic_error("Cannot be happened.");
+ ThrowExc(InternalError, "protocol error. invalid ui command id.");
}
} else {
std::string message;
return wpNotify(message, item);
default:
- throw std::logic_error("Cannot be happened.");
+ ThrowExc(InternalError, "protocol error. invalid ui command id.");
}
}
}
CSR_ERROR_INVALID_HANDLE = TIZEN_ERROR_CSR | 0x02, /**< The given handle is invalid */
CSR_ERROR_SERVER = TIZEN_ERROR_CSR | 0x03, /**< Server has been failed for some reason */
CSR_ERROR_NO_TASK = TIZEN_ERROR_CSR | 0x04, /**< No Task exists*/
+ CSR_ERROR_DB = TIZEN_ERROR_CSR | 0x05, /**< DB transaction error */
CSR_ERROR_ENGINE_PERMISSION = TIZEN_ERROR_CSR | 0x11, /**< Insufficient permission of engine */
CSR_ERROR_ENGINE_NOT_EXIST = TIZEN_ERROR_CSR | 0x12, /**< No engine exists*/
CSR_ERROR_ENGINE_DIASABLED = TIZEN_ERROR_CSR | 0x13, /**< Engine is in disabled state*/
try {
f();
} catch (const std::exception &e) {
- BOOST_REQUIRE_MESSAGE(0, "std::exception catched: " << e.what());
+ BOOST_REQUIRE_MESSAGE(0, "std::exception caught: " << e.what());
} catch (...) {
- BOOST_REQUIRE_MESSAGE(0, "Unknown exception catched");
+ BOOST_REQUIRE_MESSAGE(0, "Unknown exception caught");
}
}
Db::Manager db(TEST_DB_FILE, TEST_DB_SCRIPTS);
- ASSERT_IF(db.setEngineState(1, 1), true);
- ASSERT_IF(db.setEngineState(2, 2), true);
+ db.setEngineState(1, 1);
+ db.setEngineState(2, 2);
ASSERT_IF(db.getEngineState(1), 1);
ASSERT_IF(db.getEngineState(2), 2);
- ASSERT_IF(db.setEngineState(1, 2), true);
+ db.setEngineState(1, 2);
ASSERT_IF(db.getEngineState(1), 2);
EXCEPTION_GUARD_END
long scantime = 100;
std::string dataVersion = "1.0.0";
- ASSERT_IF(db.cleanLastScanTime(), true);
+ db.cleanLastScanTime();
ASSERT_IF(db.getLastScanTime(dir, dataVersion), -1);
- ASSERT_IF(db.insertLastScanTime(dir, scantime, dataVersion), true);
+ db.insertLastScanTime(dir, scantime, dataVersion);
- ASSERT_IF(db.insertLastScanTime("/opt/data", scantime + 100, dataVersion),
- true);
- ASSERT_IF(db.insertLastScanTime("/opt/data/etc", scantime + 200, dataVersion),
- true);
+ db.insertLastScanTime("/opt/data", scantime + 100, dataVersion);
+ db.insertLastScanTime("/opt/data/etc", scantime + 200, dataVersion);
ASSERT_IF(db.getLastScanTime(dir, dataVersion), scantime);
- ASSERT_IF(db.cleanLastScanTime(), true);
+ db.cleanLastScanTime();
EXCEPTION_GUARD_END
}
auto detectedList = db.getDetectedMalwares("/opt");
ASSERT_IF(detectedList->empty(), true);
- ASSERT_IF(db.insertDetectedMalware(malware1, initDataVersion, false), true);
+ db.insertDetectedMalware(malware1, initDataVersion, false);
detected = db.getDetectedMalware(malware1.targetName);
checkSameMalware(malware1, *detected);
ASSERT_IF(detected->dataVersion, initDataVersion);
ASSERT_IF(detected->isIgnored, false);
- ASSERT_IF(db.insertDetectedMalware(malware2, initDataVersion, true), true);
+ db.insertDetectedMalware(malware2, initDataVersion, true);
detected = db.getDetectedMalware(malware2.targetName);
checkSameMalware(malware2, *detected);
ASSERT_IF(detected->dataVersion, initDataVersion);
}
// setDetectedMalwareIgnored test
- ASSERT_IF(db.setDetectedMalwareIgnored(malware1.targetName, true), true);
+ db.setDetectedMalwareIgnored(malware1.targetName, true);
detected = db.getDetectedMalware(malware1.targetName);
checkSameMalware(malware1, *detected);
ASSERT_IF(detected->isIgnored, true);
// deleteDeprecatedDetectedMalwares test
- ASSERT_IF(db.insertDetectedMalware(malware3, changedDataVersion, false), true);
- ASSERT_IF(db.deleteDeprecatedDetectedMalwares("/opt", changedDataVersion), true);
+ db.insertDetectedMalware(malware3, changedDataVersion, false);
+ db.deleteDeprecatedDetectedMalwares("/opt", changedDataVersion);
detected = db.getDetectedMalware(malware3.targetName);
checkSameMalware(malware3, *detected);
ASSERT_IF(detected->dataVersion, changedDataVersion);
CHECK_IS_NULL(db.getDetectedMalware(malware2.targetName));
// deleteDetectedMalware test
- ASSERT_IF(db.deleteDetectedMalware(malware3.targetName), true);
+ db.deleteDetectedMalware(malware3.targetName);
CHECK_IS_NULL(db.getDetectedMalware(malware3.targetName));
EXCEPTION_GUARD_END