//==============================================================================
// Utilities functions
//==============================================================================
-std::string csret_cs_extract_value(const std::string &line, const std::string &key)
+std::string csret_cs_extract_value(const std::string &line,
+ const std::string &key)
{
if (line.empty() || key.empty())
return std::string();
auto pos = line.find(key);
+
if (pos == std::string::npos || pos != 0)
return std::string();
// detailed_url=http://medium.malware.com
// signature=RISKY_MALWARE
std::ifstream f(path.c_str());
+
if (!f.is_open())
return CSRET_CS_ERROR_NO_SIGNATURE_FILE;
std::string line;
csret_cs_malware_s node;
+
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#')
continue;
auto value = csret_cs_extract_value(line, "name=");
+
if (!value.empty()) {
if (!node.name.empty()) {
g_virus_sig.push_back(node);
}
value = csret_cs_extract_value(line, "severity=");
+
if (!value.empty()) {
if (value.compare("LOW") == 0)
node.severity = CSRE_CS_SEVERITY_LOW;
}
value = csret_cs_extract_value(line, "threat_type=");
+
if (!value.empty()) {
if (value.compare("MALWARE") == 0)
node.threat_type = CSRE_CS_THREAT_MALWARE;
}
value = csret_cs_extract_value(line, "detailed_url=");
+
if (!value.empty()) {
node.detailed_url = std::move(value);
continue;
}
value = csret_cs_extract_value(line, "signature=");
+
if (!value.empty())
node.signature = std::move(value);
}
ptr->engineVersion = ENGINE_VERSION;
ptr->dataVersion = ENGINE_VERSION;
- int ret = csret_cs_read_binary(g_resdir + "/" PRIVATE_LOGO_FILE, ptr->logoImage);
+ int ret = csret_cs_read_binary(g_resdir + "/" PRIVATE_LOGO_FILE,
+ ptr->logoImage);
+
if (ret != CSRE_ERROR_NONE) {
delete ptr;
return nullptr;
}
struct stat attrib;
+
stat(PRIVATE_DB_NAME, &attrib);
+
ptr->latestUpdate = attrib.st_mtime;
return ptr;
for (size_t i = 0; i < data.size() - needle.length(); i++) {
bool isMatched = true;
+
for (size_t j = 0; j < needle.length(); j++) {
if (data[i + j] != static_cast<unsigned char>(needle[j])) {
isMatched = false;
}
int csret_cs_detect_malware(csret_cs_context_s *context, const RawBuffer &data,
- csret_cs_detected_s **pdetected)
+ csret_cs_detected_s **pdetected)
{
if (context == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
// Main function related
//==============================================================================
API
-int csre_cs_global_initialize(const char *ro_res_dir, const char *rw_working_dir)
+int csre_cs_global_initialize(const char *ro_res_dir,
+ const char *rw_working_dir)
{
if (ro_res_dir == nullptr || rw_working_dir == nullptr)
return CSRE_ERROR_INVALID_PARAMETER;
RawBuffer vec(data, data + length);
csret_cs_detected_s *detected = nullptr;
int ret = csret_cs_detect_malware(context, vec, &detected);
+
if (ret != CSRE_ERROR_NONE)
return ret;
return CSRE_ERROR_INVALID_PARAMETER;
int fd = open(file_path, O_RDONLY);
+
if (fd < 0)
return CSRE_ERROR_FILE_NOT_FOUND;
RawBuffer vec;
int ret = csret_cs_read_binary(file_path, vec);
+
if (ret != CSRE_ERROR_NONE)
return ret;
csret_cs_detected_s *detected = nullptr;
ret = csret_cs_detect_malware(context, vec, &detected);
+
if (ret != CSRE_ERROR_NONE)
return ret;
csre_cs_detected_h most_detected = nullptr;
csre_cs_severity_level_e most = CSRE_CS_SEVERITY_LOW;
- std::unique_ptr<DIR, std::function<int(DIR *)>> dirp(opendir(app_root_dir), closedir);
+ std::unique_ptr<DIR, std::function<int(DIR *)>> dirp(opendir(app_root_dir),
+ closedir);
+
if (!dirp)
return CSRE_ERROR_FILE_NOT_FOUND;
struct dirent entry;
struct dirent *result;
+
while (readdir_r(dirp.get(), &entry, &result) == 0 && result != nullptr) {
std::string fullpath(app_root_dir);
std::string filename(entry.d_name);
if (entry.d_type & (DT_REG | DT_LNK))
ret = csre_cs_scan_file(handle, fullpath.c_str(), &detected);
else if ((entry.d_type & DT_DIR)
- && filename.compare("..") != 0
- && filename.compare(".") != 0)
+ && filename.compare("..") != 0
+ && filename.compare(".") != 0)
ret = csre_cs_scan_app_on_cloud(handle, fullpath.c_str(), &detected);
else
continue;
csre_cs_severity_level_e s = CSRE_CS_SEVERITY_LOW;
ret = csre_cs_detected_get_severity(detected, &s);
+
if (ret != CSRE_ERROR_NONE)
return ret;
// Result related
//==============================================================================
API
-int csre_cs_detected_get_severity(csre_cs_detected_h detected, csre_cs_severity_level_e *pseverity)
+int csre_cs_detected_get_severity(csre_cs_detected_h detected,
+ csre_cs_severity_level_e *pseverity)
{
if (detected == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_cs_detected_get_malware_name(csre_cs_detected_h detected, const char **malware_name)
+int csre_cs_detected_get_malware_name(csre_cs_detected_h detected,
+ const char **malware_name)
{
if (detected == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_cs_detected_get_detailed_url(csre_cs_detected_h detected, const char **detailed_url)
+int csre_cs_detected_get_detailed_url(csre_cs_detected_h detected,
+ const char **detailed_url)
{
if (detected == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_cs_detected_get_timestamp(csre_cs_detected_h detected, time_t *timestamp)
+int csre_cs_detected_get_timestamp(csre_cs_detected_h detected,
+ time_t *timestamp)
{
if (detected == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_cs_engine_get_vendor_logo(csre_cs_engine_h engine, unsigned char **logo_image,
+int csre_cs_engine_get_vendor_logo(csre_cs_engine_h engine,
+ unsigned char **logo_image,
unsigned int *image_size)
{
auto eng = reinterpret_cast<csret_cs_engine_s *>(engine);
return CSRE_ERROR_INVALID_PARAMETER;
auto s = eng->logoImage.size();
+
if (s > UINT_MAX - 1)
return CSRET_CS_ERROR_FILE_IO;
}
API
-int csre_cs_engine_get_data_version(csre_cs_engine_h engine, const char **version)
+int csre_cs_engine_get_data_version(csre_cs_engine_h engine,
+ const char **version)
{
auto eng = reinterpret_cast<csret_cs_engine_s *>(engine);
}
API
-int csre_cs_engine_get_activated(csre_cs_engine_h engine, csre_cs_activated_e *pactivated)
+int csre_cs_engine_get_activated(csre_cs_engine_h engine,
+ csre_cs_activated_e *pactivated)
{
auto eng = reinterpret_cast<csret_cs_engine_s *>(engine);
}
API
-int csre_cs_engine_get_api_version(csre_cs_engine_h engine, const char **version)
+int csre_cs_engine_get_api_version(csre_cs_engine_h engine,
+ const char **version)
{
auto eng = reinterpret_cast<csret_cs_engine_s *>(engine);
//==============================================================================
// Utilities functions
//==============================================================================
-std::string csret_wp_extract_value(const std::string &line, const std::string &key)
+std::string csret_wp_extract_value(const std::string &line,
+ const std::string &key)
{
if (line.empty() || key.empty())
return std::string();
auto pos = line.find(key);
+
if (pos == std::string::npos || pos != 0)
return std::string();
// risk_level=MEDIUM
// detailed_url=http://medium.risky.com
std::ifstream f(path.c_str());
+
if (!f.is_open())
return CSRET_WP_ERROR_NO_RISKY_URL_FILE;
std::string line;
csret_wp_risky_url_s node;
+
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#')
continue;
auto value = csret_wp_extract_value(line, "url=");
+
if (!value.empty()) {
if (!node.url.empty()) {
g_risky_urls.push_back(node);
}
value = csret_wp_extract_value(line, "risk_level=");
+
if (!value.empty()) {
if (value.compare("LOW") == 0)
node.risk_level = CSRE_WP_RISK_LOW;
}
value = csret_wp_extract_value(line, "detailed_url=");
+
if (!value.empty())
node.detailed_url = std::move(value);
}
ptr->engineVersion = ENGINE_VERSION;
ptr->dataVersion = ENGINE_VERSION;
- int ret = csret_wp_read_binary(g_resdir + "/" PRIVATE_LOGO_FILE, ptr->logoImage);
+ int ret = csret_wp_read_binary(g_resdir + "/" PRIVATE_LOGO_FILE,
+ ptr->logoImage);
+
if (ret != CSRE_ERROR_NONE) {
delete ptr;
return nullptr;
}
struct stat attrib;
+
stat(PRIVATE_DB_NAME, &attrib);
+
ptr->latestUpdate = attrib.st_mtime;
return ptr;
// Main function related
//==============================================================================
API
-int csre_wp_global_initialize(const char *ro_res_dir, const char *rw_working_dir)
+int csre_wp_global_initialize(const char *ro_res_dir,
+ const char *rw_working_dir)
{
if (ro_res_dir == nullptr || rw_working_dir == nullptr)
return CSRE_ERROR_INVALID_PARAMETER;
g_risky_urls.clear();
int ret = csret_wp_read_risky_urls(g_workingdir + "/" PRIVATE_DB_NAME);
+
if (ret != CSRE_ERROR_NONE && ret != CSRET_WP_ERROR_NO_RISKY_URL_FILE)
return ret;
}
API
-int csre_wp_check_url(csre_wp_context_h handle, const char *url, csre_wp_check_result_h *presult)
+int csre_wp_check_url(csre_wp_context_h handle, const char *url,
+ csre_wp_check_result_h *presult)
{
auto context = reinterpret_cast<csret_wp_context_s *>(handle);
csret_wp_risky_url_s detected;
detected.url = in_url;
+
// check url from static risky urls list
for (auto &item : g_risky_urls) {
if (in_url.find(item.url) == std::string::npos)
}
context->detected_list.push_back(detected);
- *presult = reinterpret_cast<csre_wp_check_result_h>(&context->detected_list.back());
+ *presult = reinterpret_cast<csre_wp_check_result_h>
+ (&context->detected_list.back());
return CSRE_ERROR_NONE;
}
// Result related
//==============================================================================
API
-int csre_wp_result_get_risk_level(csre_wp_check_result_h result, csre_wp_risk_level_e *plevel)
+int csre_wp_result_get_risk_level(csre_wp_check_result_h result,
+ csre_wp_risk_level_e *plevel)
{
if (result == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_wp_result_get_detailed_url(csre_wp_check_result_h result, const char** detailed_url)
+int csre_wp_result_get_detailed_url(csre_wp_check_result_h result,
+ const char **detailed_url)
{
if (result == nullptr)
return CSRE_ERROR_INVALID_HANDLE;
}
API
-int csre_wp_engine_get_vendor_logo(csre_wp_engine_h engine, unsigned char **vendor_logo_image,
+int csre_wp_engine_get_vendor_logo(csre_wp_engine_h engine,
+ unsigned char **vendor_logo_image,
unsigned int *image_size)
{
auto eng = reinterpret_cast<csret_wp_engine_s *>(engine);
return CSRE_ERROR_INVALID_PARAMETER;
auto s = eng->logoImage.size();
+
if (s > UINT_MAX - 1)
return CSRET_WP_ERROR_FILE_IO;
}
API
-int csre_wp_engine_get_data_version(csre_wp_engine_h engine, const char **version)
+int csre_wp_engine_get_data_version(csre_wp_engine_h engine,
+ const char **version)
{
auto eng = reinterpret_cast<csret_wp_engine_s *>(engine);
API
-int csre_wp_engine_get_activated(csre_wp_engine_h engine, csre_wp_activated_e *pactivated)
+int csre_wp_engine_get_activated(csre_wp_engine_h engine,
+ csre_wp_activated_e *pactivated)
{
auto eng = reinterpret_cast<csret_wp_engine_s *>(engine);
}
API
-int csre_wp_engine_get_api_version(csre_wp_engine_h engine, const char **version)
+int csre_wp_engine_get_api_version(csre_wp_engine_h engine,
+ const char **version)
{
auto eng = reinterpret_cast<csret_wp_engine_s *>(engine);
class AsyncLogic {
public:
- AsyncLogic(std::shared_ptr<Context> &context, const Callback &cb, void *userdata,
+ AsyncLogic(std::shared_ptr<Context> &context, const Callback &cb,
+ void *userdata,
const std::function<bool()> &isStopped);
virtual ~AsyncLogic();
void add(Result *);
std::shared_ptr<Context> &m_origCtx; // for registering results for auto-release
- std::unique_ptr<Context> m_ctx; // TODO: append it to handle context when destroyed
+
+ // TODO: append it to handle context when destroyed
+ std::unique_ptr<Context> m_ctx;
+
Callback m_cb;
void *m_userdata;
std::function<bool()> m_isStopped;
std::unique_ptr<Dispatcher> m_dispatcher;
-
};
template<typename T>
API
-int csr_get_error_string(int error_code, char** string)
+int csr_get_error_string(int error_code, char **string)
{
(void) error_code;
(void) string;
}
API
-int csr_wp_check_url(csr_wp_context_h handle, const char *url, csr_wp_check_result_h *presult)
+int csr_wp_check_url(csr_wp_context_h handle, const char *url,
+ csr_wp_check_result_h *presult)
{
EXCEPTION_SAFE_START
}
API
-int csr_wp_result_get_risk_level(csr_wp_check_result_h result, csr_wp_risk_level_e *plevel)
+int csr_wp_result_get_risk_level(csr_wp_check_result_h result,
+ csr_wp_risk_level_e *plevel)
{
EXCEPTION_SAFE_START
}
API
-int csr_wp_result_get_detailed_url(csr_wp_check_result_h result, const char **pdetailed_url)
+int csr_wp_result_get_detailed_url(csr_wp_check_result_h result,
+ const char **pdetailed_url)
{
EXCEPTION_SAFE_START
API
-int csr_wp_result_get_user_response(csr_wp_check_result_h result, csr_wp_user_response_e *presponse)
+int csr_wp_result_get_user_response(csr_wp_check_result_h result,
+ csr_wp_user_response_e *presponse)
{
EXCEPTION_SAFE_START
class ConsoleLogSink : public LogSink {
public:
- void sink(LogLevel level, const std::string &tag, const std::string &message) override;
+ void sink(LogLevel level, const std::string &tag,
+ const std::string &message) override;
};
}
namespace Csr {
namespace Audit {
-void DlogLogSink::sink(LogLevel level, const std::string &tag, const std::string &message)
+void DlogLogSink::sink(LogLevel level, const std::string &tag,
+ const std::string &message)
{
switch (level) {
case LogLevel::Error:
SLOG(LOG_ERROR, tag.c_str(), "%s", message.c_str());
return;
+
case LogLevel::Warning:
SLOG(LOG_WARN, tag.c_str(), "%s", message.c_str());
return;
+
case LogLevel::Debug:
SLOG(LOG_DEBUG, tag.c_str(), "%s", message.c_str());
return;
+
case LogLevel::Info:
SLOG(LOG_INFO, tag.c_str(), "%s", message.c_str());
return;
+
case LogLevel::Trace:
SLOG(LOG_VERBOSE, tag.c_str(), "%s", message.c_str());
return;
+
default:
SLOG(LOG_SILENT, tag.c_str(), "%s", message.c_str());
return;
class DlogLogSink : public LogSink {
public:
- void sink(LogLevel level, const std::string &tag, const std::string &message) override;
+ void sink(LogLevel level, const std::string &tag,
+ const std::string &message) override;
};
}
LogSink() {}
virtual ~LogSink() {}
virtual void sink(
- LogLevel level,
- const std::string &tag,
- const std::string &message) = 0;
+ LogLevel level,
+ const std::string &tag,
+ const std::string &message) = 0;
};
}
std::string toString(LogLevel level)
{
switch (level) {
- case LogLevel::Error: return "ERROR";
- case LogLevel::Warning: return "WARN";
- case LogLevel::Debug: return "DEBUG";
- case LogLevel::Info: return "INFO";
- case LogLevel::Trace: return "TRACE";
- default: return "UNKNOWN";
+ case LogLevel::Error:
+ return "ERROR";
+
+ case LogLevel::Warning:
+ return "WARN";
+
+ case LogLevel::Debug:
+ return "DEBUG";
+
+ case LogLevel::Info:
+ return "INFO";
+
+ case LogLevel::Trace:
+ return "TRACE";
+
+ default:
+ return "UNKNOWN";
}
}
} // namespace anonymous
void Logger::log(LogLevel level,
- const std::string &file,
- unsigned int line,
- const std::string &func,
- const std::string &message)
+ const std::string &file,
+ unsigned int line,
+ const std::string &func,
+ const std::string &message)
{
std::ostringstream buffer;
buffer << toString(level)
- << "<" << ::getpid() << ">:"
- << "[" << file << ":" << line << "]"
- << " " << func << "() " << message
- << std::endl;
+ << "<" << ::getpid() << ">:"
+ << "[" << file << ":" << line << "]"
+ << " " << func << "() " << message
+ << std::endl;
g_backend->sink(level, g_tag, buffer.str());
}
#define __FILENAME__ (::strrchr(__FILE__, '/') ? ::strrchr(__FILE__, '/') + 1 : __FILE__)
#endif
-#define FORMAT(ITEMS) \
- ((dynamic_cast<std::ostringstream &>( \
- std::ostringstream().seekp(0, std::ios_base::cur) << ITEMS) \
- ).str())
+#define FORMAT(ITEMS) \
+ (dynamic_cast<std::ostringstream &>(std::ostringstream().seekp( \
+ 0, std::ios_base::cur) << ITEMS)).str()
-#define LOG(LEVEL, MESSAGE) \
- Csr::Audit::Logger::log( \
- Csr::Audit::LogLevel::LEVEL, \
- __FILENAME__, __LINE__, __func__, \
+#define LOG(LEVEL, MESSAGE) Csr::Audit::Logger::log( \
+ Csr::Audit::LogLevel::LEVEL, __FILENAME__, __LINE__, __func__, \
FORMAT(MESSAGE))
-#define ERROR(MESSAGE) LOG(Error, MESSAGE)
-#define WARN(MESSAGE) LOG(Warning, MESSAGE)
-#define INFO(MESSAGE) LOG(Info, MESSAGE)
+#define ERROR(MESSAGE) LOG(Error, MESSAGE)
+#define WARN(MESSAGE) LOG(Warning, MESSAGE)
+#define INFO(MESSAGE) LOG(Info, MESSAGE)
#if !defined(NDEBUG)
-#define DEBUG(MESSAGE) LOG(Debug, MESSAGE)
-#define TRACE(MESSAGE) LOG(Trace, MESSAGE)
+#define DEBUG(MESSAGE) LOG(Debug, MESSAGE)
+#define TRACE(MESSAGE) LOG(Trace, MESSAGE)
#else
#define DEBUG(MESSAGE) do {} while (false)
#define TRACE(MESSAGE) do {} while (false)
size -= count;
m_size -= count;
+
if (m_buckets.front()->left == 0)
m_buckets.pop();
}
BinaryQueue();
virtual ~BinaryQueue();
- BinaryQueue(BinaryQueue&&) = default;
- BinaryQueue &operator=(BinaryQueue&&) = default;
+ BinaryQueue(BinaryQueue &&) = default;
+ BinaryQueue &operator=(BinaryQueue &&) = default;
BinaryQueue(const BinaryQueue &) = delete;
BinaryQueue &operator=(const BinaryQueue &) = delete;
int intAskUser;
int intCoreUsage;
Deserializer<std::string, int, int, bool>::Deserialize(stream,
- m_popupMessage, intAskUser, intCoreUsage, m_isScanOnCloud);
+ m_popupMessage, intAskUser, intCoreUsage, m_isScanOnCloud);
m_askUser = static_cast<csr_cs_ask_user_e>(intAskUser);
m_coreUsage = static_cast<csr_cs_core_usage_e>(intCoreUsage);
void CsContext::Serialize(IStream &stream) const
{
Serializer<std::string, int, int, bool>::Serialize(stream,
- m_popupMessage, static_cast<int>(m_askUser), static_cast<int>(m_coreUsage), m_isScanOnCloud);
+ m_popupMessage, static_cast<int>(m_askUser), static_cast<int>(m_coreUsage),
+ m_isScanOnCloud);
}
CsContext::CsContext(CsContext &&other) :
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as int."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as string."));
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to get as string."));
+ throw std::logic_error(FORMAT("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."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as bool."));
}
}
int intSeverity;
int intThreat;
int intResponse;
- Deserializer<std::string, std::string, std::string, int, int, int, time_t>
- ::Deserialize(stream,
- m_targetName, m_malwareName, m_detailedUrl,
- intSeverity, intThreat, intResponse, m_ts);
+ Deserializer<std::string, std::string, std::string, int, int, int, time_t>::Deserialize(
+ stream, m_targetName, m_malwareName, m_detailedUrl, intSeverity, intThreat,
+ intResponse, m_ts);
m_severity = static_cast<csr_cs_severity_level_e>(intSeverity);
m_threat = static_cast<csr_cs_threat_type_e>(intThreat);
if (!hasValue())
return;
- Serializer<std::string, std::string, std::string, int, int, int, time_t>
- ::Serialize(stream,
- m_targetName, m_malwareName, m_detailedUrl,
- static_cast<int>(m_severity), static_cast<int>(m_threat),
- static_cast<int>(m_response), m_ts);
+ Serializer<std::string, std::string, std::string, int, int, int, time_t>::Serialize(
+ stream, m_targetName, m_malwareName, m_detailedUrl,
+ static_cast<int>(m_severity), static_cast<int>(m_threat),
+ static_cast<int>(m_response), m_ts);
}
CsDetected::CsDetected(CsDetected &&other) :
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as int."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as int."));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as bool."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as bool."));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as string."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as string."));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as string."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as string."));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as time_t."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as time_t."));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to get as int."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as int."));
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to get as bool."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as bool."));
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to get as string."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as string."));
}
}
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to get as time_t."));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to get as time_t."));
}
}
virtual void get(int, int &) const;
virtual void get(int, bool &) const;
virtual void get(int, std::string &) const;
- virtual void get(int, const char **) const; // For not copy to string lifecycle within itself.
+ // For not copy to string lifecycle within itself.
+ virtual void get(int, const char **) const;
virtual void get(int, time_t &) const;
};
{
if (!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);
}
{
/* 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!"));
+ throw std::logic_error(FORMAT("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"));
+ throw std::logic_error(FORMAT("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");
if (m_callbacks.count(fd) == 0)
throw std::logic_error(FORMAT(
- "event in on fd[" << fd << "] but associated callback isn't exist!"));
+ "event in on fd[" << fd << "] but associated callback isn't exist!"));
if (event[i].events & (EPOLLHUP | EPOLLRDHUP)) {
INFO("peer connection closed on fd[" << fd << "]");
// 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(){}
+ 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&) {}
+ ISerializable(IStream &) {}
virtual void Serialize(IStream &) const = 0;
virtual ~ISerializable() {}
};
// normal functions
// ISerializable objects
- static void Serialize(IStream& stream, const ISerializable& object)
+ static void Serialize(IStream &stream, const ISerializable &object)
{
object.Serialize(stream);
}
- static void Serialize(IStream& stream, const ISerializable* const object)
+ static void Serialize(IStream &stream, const ISerializable *const object)
{
object->Serialize(stream);
}
// char
- static void Serialize(IStream& stream, const char value)
+ static void Serialize(IStream &stream, const char value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const char* const 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)
+ static void Serialize(IStream &stream, const unsigned char value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const unsigned char* const 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)
+ static void Serialize(IStream &stream, const uint32_t value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const uint32_t* const 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)
+ static void Serialize(IStream &stream, const int32_t value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const int32_t* const 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)
+ static void Serialize(IStream &stream, const uint64_t value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const uint64_t* const 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)
+ static void Serialize(IStream &stream, const int64_t value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const int64_t* const value)
+ static void Serialize(IStream &stream, const int64_t *const value)
{
stream.write(sizeof(*value), value);
}
- static void Serialize(IStream& stream, const time_t value)
+ static void Serialize(IStream &stream, const time_t value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const time_t* const value)
+ static void Serialize(IStream &stream, const time_t *const value)
{
stream.write(sizeof(*value), value);
}
// bool
- static void Serialize(IStream& stream, const bool value)
+ static void Serialize(IStream &stream, const bool value)
{
stream.write(sizeof(value), &value);
}
- static void Serialize(IStream& stream, const bool* const value)
+ static void Serialize(IStream &stream, const bool *const value)
{
stream.write(sizeof(*value), value);
}
- static void Serialize(IStream& stream, const CommandId value)
+ static void Serialize(IStream &stream, const CommandId value)
{
Serialize(stream, static_cast<int>(value));
}
- static void Serialize(IStream& stream, const csr_error_e value)
+ static void Serialize(IStream &stream, const csr_error_e value)
{
Serialize(stream, static_cast<int>(value));
}
// std::string
template <typename T, typename R, typename A>
- static void Serialize(IStream& stream, const std::basic_string<T, R, A>& str)
+ 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());
+ 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)
+ 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());
+ stream.write(length * sizeof(T), str->data());
}
// STL templates
// std::list
template <typename T>
- static void Serialize(IStream& stream, const std::list<T>& list)
+ static void Serialize(IStream &stream, const std::list<T> &list)
{
size_t length = list.size();
stream.write(sizeof(length), &length);
+
for (const auto &item : list)
Serialize(stream, item);
}
template <typename T>
- static void Serialize(IStream& stream, const std::list<T>* const list)
+ static void Serialize(IStream &stream, const std::list<T> *const list)
{
Serialize(stream, *list);
}
template <typename T>
- static void Serialize(IStream& stream, const std::set<T>& set)
+ static void Serialize(IStream &stream, const std::set<T> &set)
{
auto len = set.size();
stream.write(sizeof(len), &len);
+
for (const auto &item : set)
Serialize(stream, item);
}
template <typename T>
- static void Serialize(IStream& stream, const std::set<T>* const set)
+ static void Serialize(IStream &stream, const std::set<T> *const set)
{
Serialize(stream, *set);
}
// RawBuffer
template <typename A>
- static void Serialize(IStream& stream, const std::vector<unsigned char, A>& vec)
+ static void Serialize(IStream &stream, const std::vector<unsigned char, A> &vec)
{
int length = vec.size();
stream.write(sizeof(length), &length);
}
template <typename A>
- static void Serialize(IStream& stream, const std::vector<unsigned char, A>* const vec)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ static void Serialize(IStream &stream, const std::map<K, T> &map)
{
size_t length = map.size();
stream.write(sizeof(length), &length);
+
for (const auto &item : map) {
Serialize(stream, item.first);
Serialize(stream, item.second);
}
}
template <typename K, typename T>
- static void Serialize(IStream& stream, const std::map<K, T>* const map)
+ static void Serialize(IStream &stream, const std::map<K, T> *const map)
{
Serialize(stream, *map);
}
// std::unordered_map
template <typename K, typename T>
- static void Serialize(IStream& stream, const std::unordered_map<K, T>& map)
+ static void Serialize(IStream &stream, const std::unordered_map<K, T> &map)
{
size_t length = map.size();
stream.write(sizeof(length), &length);
+
for (const auto &item : map) {
Serialize(stream, item.first);
Serialize(stream, item.second);
}
}
template <typename K, typename T>
- static void Serialize(IStream& stream, const std::unordered_map<K, T>* const map)
+ static void Serialize(IStream &stream,
+ const std::unordered_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)
+ static void Serialize(IStream &stream, const std::unique_ptr<T> &p)
{
Serialize(stream, *p);
}
// std::shared_ptr
template <typename T>
- static void Serialize(IStream& stream, const std::shared_ptr<T>& p)
+ static void Serialize(IStream &stream, const std::shared_ptr<T> &p)
{
Serialize(stream, *p);
}
-
}; // struct Serialization
struct Deserialization {
// ISerializable objects
// T instead of ISerializable is needed to call proper constructor
template <typename T>
- static void Deserialize(IStream& stream, T& object)
+ static void Deserialize(IStream &stream, T &object)
{
object = T(stream);
}
template <typename T>
- static void Deserialize(IStream& stream, T*& object)
+ static void Deserialize(IStream &stream, T *&object)
{
object = new T(stream);
}
// char
- static void Deserialize(IStream& stream, char& value)
+ static void Deserialize(IStream &stream, char &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, char*& 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)
+ static void Deserialize(IStream &stream, unsigned char &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, unsigned char*& 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)
+ static void Deserialize(IStream &stream, uint32_t &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, uint32_t*& 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)
+ static void Deserialize(IStream &stream, int32_t &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, int32_t*& 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)
+ static void Deserialize(IStream &stream, uint64_t &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, uint64_t*& 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)
+ static void Deserialize(IStream &stream, int64_t &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, int64_t*& value)
+ static void Deserialize(IStream &stream, int64_t *&value)
{
value = new int64_t;
stream.read(sizeof(*value), value);
}
- static void Deserialize(IStream& stream, time_t& value)
+ static void Deserialize(IStream &stream, time_t &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, time_t*& value)
+ static void Deserialize(IStream &stream, time_t *&value)
{
value = new time_t;
stream.read(sizeof(*value), value);
}
// bool
- static void Deserialize(IStream& stream, bool& value)
+ static void Deserialize(IStream &stream, bool &value)
{
stream.read(sizeof(value), &value);
}
- static void Deserialize(IStream& stream, bool*& value)
+ static void Deserialize(IStream &stream, bool *&value)
{
value = new bool;
stream.read(sizeof(*value), value);
}
- static void Deserialize(IStream& stream, CommandId& value)
+ static void Deserialize(IStream &stream, CommandId &value)
{
int val;
Deserialize(stream, val);
value = static_cast<CommandId>(val);
}
- static void Deserialize(IStream& stream, csr_error_e& value)
+ static void Deserialize(IStream &stream, csr_error_e &value)
{
int val;
Deserialize(stream, val);
}
template <typename T, typename R, typename A>
- static void Deserialize(IStream& stream, std::basic_string<T, R, A>& str)
+ 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());
+ 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)
+ 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());
+ stream.read(length * sizeof(T), buf.data());
str = new std::basic_string<T, R, A>(buf.data(), buf.data() + length);
}
// std::list
template <typename T>
- static void Deserialize(IStream& stream, std::list<T>& list)
+ 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);
}
}
template <typename T>
- static void Deserialize(IStream& stream, std::list<T>*& list)
+ static void Deserialize(IStream &stream, std::list<T> *&list)
{
list = new std::list<T>;
Deserialize(stream, *list);
}
template <typename T>
- static void Deserialize(IStream& stream, std::set<T>& set)
+ static void Deserialize(IStream &stream, std::set<T> &set)
{
size_t len;
stream.read(sizeof(len), &len);
+
for (size_t i = 0; i < len; ++i) {
T obj;
Deserialize(stream, obj);
}
}
template <typename T>
- static void Deserialize(IStream& stream, std::set<T>*& set)
+ static void Deserialize(IStream &stream, std::set<T> *&set)
{
set = new std::set<T>;
Deserialize(stream, *set);
// RawBuffer
template <typename A>
- static void Deserialize(IStream& stream, std::vector<unsigned char, A>& vec)
+ static void Deserialize(IStream &stream, std::vector<unsigned char, A> &vec)
{
int length;
stream.read(sizeof(length), &length);
}
template <typename A>
- static void Deserialize(IStream& stream, std::vector<unsigned char, A>*& vec)
+ 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)
+ 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);
}
}
template <typename T, typename A>
- static void Deserialize(IStream& stream, std::vector<T, A>*& vec)
+ 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)
+ 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)
+ 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)
+ 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;
}
}
template <typename K, typename T>
- static void Deserialize(IStream& stream, std::map<K, T>*& map)
+ static void Deserialize(IStream &stream, std::map<K, T> *&map)
{
map = new std::map<K, T>;
Deserialize(stream, *map);
// std::unordered_map
template <typename K, typename T>
- static void Deserialize(IStream& stream, std::unordered_map<K, T>& map)
+ static void Deserialize(IStream &stream, std::unordered_map<K, T> &map)
{
size_t length;
stream.read(sizeof(length), &length);
+
for (size_t i = 0; i < length; ++i) {
K key;
T obj;
}
}
template <typename K, typename T>
- static void Deserialize(IStream& stream, std::unordered_map<K, T>*& map)
+ static void Deserialize(IStream &stream, std::unordered_map<K, T> *&map)
{
map = new std::map<K, T>;
Deserialize(stream, *map);
}
-
}; // struct Deserialization
// generic serialization
template <typename First, typename... Args>
struct Serializer<First, Args...> : public Serializer<Args...> {
- static void Serialize(IStream& stream, const First& f, const Args&... 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&)
+ static void Serialize(IStream &)
{
return;
}
template <typename First, typename... Args>
struct Deserializer<First, Args...> : public Deserializer<Args...> {
- static void Deserialize(IStream& stream, First& f, Args&... 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&)
+ static void Deserialize(IStream &)
{
return;
}
Socket socket(m_address);
DEBUG("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)
- return;
+ [&](uint32_t event) {
+ if (event != EPOLLIN)
+ return;
- m_onNewConnection(std::make_shared<Connection>(socket.accept()));
- });
+ m_onNewConnection(std::make_shared<Connection>(socket.accept()));
+ });
m_loop.run(timeout);
}
void Service::setNewConnectionCallback(const ConnCallback &/*callback*/)
{
/* TODO: scoped-lock */
- m_onNewConnection = [&](const ConnShPtr &connection) {
+ m_onNewConnection = [&](const ConnShPtr & connection) {
if (!connection)
throw std::logic_error("onNewConnection called but ConnShPtr is nullptr.");
INFO("welcome! accepted client socket fd[" << fd << "]");
-/*
- // TODO: disable temporarily
- if (callback)
- callback(connection);
-*/
+ /*
+ // TODO: disable temporarily
+ if (callback)
+ callback(connection);
+ */
m_loop.addEventSource(fd, EPOLLIN | EPOLLHUP | EPOLLRDHUP,
- [&, fd](uint32_t event) {
- DEBUG("read event comes in to fd[" << fd << "]");
+ [ &, fd](uint32_t event) {
+ 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"));
+ if (m_connectionRegistry.count(fd) == 0)
+ throw std::logic_error(FORMAT("get event on fd[" << fd
+ << "] but no associated connection exist"));
- auto &conn = m_connectionRegistry[fd];
+ auto &conn = m_connectionRegistry[fd];
- if (event & (EPOLLHUP | EPOLLRDHUP)) {
- DEBUG("event of epoll hup. close connection on fd[" << fd << "]");
- m_onCloseConnection(conn);
- return;
- }
+ if (event & (EPOLLHUP | EPOLLRDHUP)) {
+ DEBUG("event of epoll hup. close connection on fd[" << fd << "]");
+ m_onCloseConnection(conn);
+ return;
+ }
- DEBUG("Start message process on fd[" << fd << "]");
+ DEBUG("Start message process on fd[" << fd << "]");
- onMessageProcess(conn);
- });
+ onMessageProcess(conn);
+ });
m_connectionRegistry[fd] = connection;
};
void Service::setCloseConnectionCallback(const ConnCallback &/*callback*/)
{
/* TODO: scoped-lock */
- m_onCloseConnection = [&](const ConnShPtr &connection) {
+ m_onCloseConnection = [&](const ConnShPtr & connection) {
if (!connection)
throw std::logic_error("no connection to close");
if (m_connectionRegistry.count(fd) == 0)
throw std::logic_error(FORMAT("no connection in registry to remove "
- "associated to fd[" << fd << "]"));
+ "associated to fd[" << fd << "]"));
INFO("good-bye! close socket fd[" << fd << "]");
m_loop.removeEventSource(fd);
m_connectionRegistry.erase(fd); /* scoped-lock needed? */
-/*
- // TODO: disable temporarily
- if (callback)
- callback(connection);
-*/
+ /*
+ // TODO: disable temporarily
+ if (callback)
+ callback(connection);
+ */
};
}
int createSystemdSocket(const std::string &path)
{
int n = ::sd_listen_fds(-1);
+
if (n < 0)
throw std::system_error(std::error_code(), "failed to sd_listen_fds");
Socket Socket::accept() const
{
int fd = ::accept(m_fd, nullptr, nullptr);
+
if (fd < 0)
throw std::system_error(
std::error_code(errno, std::generic_category()),
throw std::invalid_argument("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()),
strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path));
- if (::connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(sockaddr_un)) == -1)
+ 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!");
while (total < size) {
int bytes = ::read(m_fd, buf + total, size - total);
+
if (bytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
data.resize(total);
DEBUG("Read data of size[" << total
- << "] from stream on socket fd[" << m_fd << "] done.");
+ << "] from stream on socket fd[" << m_fd << "] done.");
return data;
}
while (total < size) {
int bytes = ::write(m_fd, buf + total, size - total);
+
if (bytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
total += bytes;
}
- DEBUG("Write data of size[" << total
- << "] to stream on socket fd[" << m_fd << "] done.");
+ DEBUG("Write data of size[" << total <<
+ "] to stream on socket fd[" << m_fd << "] done.");
}
}
RawBuffer read(void) const;
void write(const RawBuffer &data) const;
- static Socket connect(const std::string &path); /* TODO: can it be constructor? */
+ /* TODO: can it be constructor? */
+ static Socket connect(const std::string &path);
private:
int m_fd;
-
};
}
void WpContext::Serialize(IStream &stream) const
{
- Serializer<std::string, int>::Serialize(stream, m_popupMessage, static_cast<int>(m_askUser));
+ Serializer<std::string, int>::Serialize(stream, m_popupMessage,
+ static_cast<int>(m_askUser));
}
WpContext::WpContext(WpContext &&other) :
{
}
-WpContext &WpContext::operator=(WpContext && other)
+WpContext &WpContext::operator=(WpContext &&other)
{
if (this == &other)
return *this;
case Key::AskUser:
m_askUser = static_cast<csr_wp_ask_user_e>(value);
break;
+
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as int. value=" << value));
+ throw std::logic_error(FORMAT("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));
+ throw std::logic_error(FORMAT("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));
+ throw std::logic_error(FORMAT("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));
+ throw std::logic_error(FORMAT("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));
+ throw std::logic_error(FORMAT("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));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as char*. value=" << value));
}
}
{
}
-WpResult &WpResult::operator=(WpResult && other)
+WpResult &WpResult::operator=(WpResult &&other)
{
if (this == &other)
return *this;
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as int. value=" << value));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as int. value=" << value));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as std::string. value=" << value));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as std::string. value=" << value));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as char*. value=" << value));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as char*. value=" << value));
}
setValueFlag();
break;
default:
- throw std::logic_error(FORMAT("Invalid key[" << key
- << "] comes in to set as int. value=" << value));
+ throw std::logic_error(FORMAT("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 char**. value=" << value));
+ throw std::logic_error(FORMAT("Invalid key[" << key <<
+ "] comes in to set as char**. value=" << value));
}
}
int Connection::exec(const std::string &query)
{
- if (::sqlite3_exec(m_handle, query.c_str(), nullptr, nullptr, nullptr) != SQLITE_OK)
+ if (::sqlite3_exec(m_handle, query.c_str(), nullptr, nullptr,
+ nullptr) != SQLITE_OK)
throw std::runtime_error(getErrorMessage());
return sqlite3_changes(m_handle);
ERROR("getDetectedMalwares failed. error_msg=" << e.what());
return nullptr;
}
-
}
DetectedShrPtr Manager::getDetectedMalware(const std::string &path) noexcept
bool CpuUsageManager::setThreadCoreUsage(int percent)
{
- if(percent > 100 || percent <= 0)
+ if (percent > 100 || percent <= 0)
throw std::runtime_error("invalid core usage percent.");
+
cpu_set_t set;
CPU_ZERO(&set);
int cnt = (m_cores * percent) / 100;
+
if (cnt < MIN_CORE_USED)
cnt = MIN_CORE_USED;
+
for (int cpuid = m_cores - 1; cpuid >= (m_cores - cnt); cpuid--)
CPU_SET(cpuid, &set);
{
cpu_set_t usedCore;
CPU_ZERO(&usedCore);
+
if (sched_getaffinity(0, sizeof(cpu_set_t), &usedCore) != 0)
throw std::runtime_error("sched_getaffinity failed.");
+
return CPU_COUNT(&usedCore);
}
class CpuUsageManager {
public:
- static CpuUsageManager *getInstance() {
+ static CpuUsageManager *getInstance()
+ {
static CpuUsageManager instance;
return &instance;
}
int getCoreUsage() const;
int getCoreCnt() const;
+
private:
int m_cores;
- CpuUsageManager() : m_cores(1) {
+ CpuUsageManager() : m_cores(1)
+ {
initialize();
};
- ~CpuUsageManager() {};
+
+ ~CpuUsageManager() {}
void initialize();
static int getUsedCnt();
{
const char *cvalue = nullptr;
auto retval = getfunc(&cvalue);
+
if (retval == CSRE_ERROR_NONE && cvalue != nullptr)
value = cvalue;
return m_pc.fpGetEngineActivated(e, pactivated);
}
-int CsLoader::getEngineVendorLogo(csre_cs_engine_h e, std::vector<unsigned char> &value)
+int CsLoader::getEngineVendorLogo(csre_cs_engine_h e,
+ std::vector<unsigned char> &value)
{
if (e == nullptr)
throw std::invalid_argument("cs loader get engine vendor logo");
void *handle = dlopen(enginePath.c_str(), RTLD_LAZY);
if (handle == nullptr)
- throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath <<" errno: " << errno));
+ throw std::logic_error(FORMAT("engine dlopen error. path: " << enginePath <<
+ " errno: " << errno));
m_pc.dlhandle = handle;
- m_pc.fpGlobalInit = reinterpret_cast<FpGlobalInit>(dlsym(handle, "csre_cs_global_initialize"));
- m_pc.fpGlobalDeinit = reinterpret_cast<FpGlobalDeinit>(dlsym(handle, "csre_cs_global_deinitialize"));
- m_pc.fpContextCreate = reinterpret_cast<FpContextCreate>(dlsym(handle, "csre_cs_context_create"));
- m_pc.fpContextDestroy = reinterpret_cast<FpContextDestroy>(dlsym(handle, "csre_cs_context_destroy"));
- m_pc.fpScanData = reinterpret_cast<FpScanData>(dlsym(handle, "csre_cs_scan_data"));
- m_pc.fpScanFile = reinterpret_cast<FpScanFile>(dlsym(handle, "csre_cs_scan_file"));
- m_pc.fpScanAppOnCloud = reinterpret_cast<FpScanAppOnCloud>(dlsym(handle, "csre_cs_scan_app_on_cloud"));
- m_pc.fpGetSeverity = reinterpret_cast<FpGetSeverity>(dlsym(handle, "csre_cs_detected_get_severity"));
- m_pc.fpGetThreatType = reinterpret_cast<FpGetThreatType>(dlsym(handle, "csre_cs_detected_get_threat_type"));
- m_pc.fpGetMalwareName = reinterpret_cast<FpGetMalwareName>(dlsym(handle, "csre_cs_detected_get_malware_name"));
- m_pc.fpGetDetailedUrl = reinterpret_cast<FpGetDetailedUrl>(dlsym(handle, "csre_cs_detected_get_detailed_url"));
- m_pc.fpGetTimestamp = reinterpret_cast<FpGetTimestamp>(dlsym(handle, "csre_cs_detected_get_timestamp"));
- m_pc.fpGetErrorString = reinterpret_cast <FpGetErrorString>(dlsym(handle, "csre_cs_get_error_string"));
- m_pc.fpGetEngineInfo = reinterpret_cast<FpGetEngineInfo>(dlsym(handle, "csre_cs_engine_get_info"));
- m_pc.fpDestroyEngine = reinterpret_cast<FpDestroyEngine>(dlsym(handle, "csre_cs_engine_destroy"));
- m_pc.fpGetEngineApiVersion = reinterpret_cast<FpGetEngineApiVersion>(dlsym(handle, "csre_cs_engine_get_api_version"));
- m_pc.fpGetEngineVendor = reinterpret_cast<FpGetEngineVendor>(dlsym(handle, "csre_cs_engine_get_vendor"));
- m_pc.fpGetEngineName = reinterpret_cast<FpGetEngineName>(dlsym(handle, "csre_cs_engine_get_name"));
- m_pc.fpGetEngineVersion = reinterpret_cast<FpGetEngineVersion>(dlsym(handle, "csre_cs_engine_get_version"));
- m_pc.fpGetEngineDataVersion = reinterpret_cast<FpGetEngineDataVersion>(dlsym(handle, "csre_cs_engine_get_data_version"));
- m_pc.fpGetEngineLatestUpdateTime = reinterpret_cast<FpGetEngineLatestUpdateTime>(dlsym(handle, "csre_cs_engine_get_latest_update_time"));
- m_pc.fpGetEngineActivated = reinterpret_cast<FpGetEngineActivated>(dlsym(handle, "csre_cs_engine_get_activated"));
- m_pc.fpGetEngineVendorLogo = reinterpret_cast<FpGetEngineVendorLogo>(dlsym(handle, "csre_cs_engine_get_vendor_logo"));
+ m_pc.fpGlobalInit = reinterpret_cast<FpGlobalInit>(dlsym(handle,
+ "csre_cs_global_initialize"));
+ m_pc.fpGlobalDeinit = reinterpret_cast<FpGlobalDeinit>(dlsym(handle,
+ "csre_cs_global_deinitialize"));
+ m_pc.fpContextCreate = reinterpret_cast<FpContextCreate>(dlsym(handle,
+ "csre_cs_context_create"));
+ m_pc.fpContextDestroy = reinterpret_cast<FpContextDestroy>(dlsym(handle,
+ "csre_cs_context_destroy"));
+ m_pc.fpScanData = reinterpret_cast<FpScanData>(dlsym(handle,
+ "csre_cs_scan_data"));
+ m_pc.fpScanFile = reinterpret_cast<FpScanFile>(dlsym(handle,
+ "csre_cs_scan_file"));
+ m_pc.fpScanAppOnCloud = reinterpret_cast<FpScanAppOnCloud>(dlsym(handle,
+ "csre_cs_scan_app_on_cloud"));
+ m_pc.fpGetSeverity = reinterpret_cast<FpGetSeverity>(dlsym(handle,
+ "csre_cs_detected_get_severity"));
+ m_pc.fpGetThreatType = reinterpret_cast<FpGetThreatType>(dlsym(handle,
+ "csre_cs_detected_get_threat_type"));
+ m_pc.fpGetMalwareName = reinterpret_cast<FpGetMalwareName>(dlsym(handle,
+ "csre_cs_detected_get_malware_name"));
+ m_pc.fpGetDetailedUrl = reinterpret_cast<FpGetDetailedUrl>(dlsym(handle,
+ "csre_cs_detected_get_detailed_url"));
+ m_pc.fpGetTimestamp = reinterpret_cast<FpGetTimestamp>(dlsym(handle,
+ "csre_cs_detected_get_timestamp"));
+ m_pc.fpGetErrorString = reinterpret_cast <FpGetErrorString>(dlsym(handle,
+ "csre_cs_get_error_string"));
+ m_pc.fpGetEngineInfo = reinterpret_cast<FpGetEngineInfo>(dlsym(handle,
+ "csre_cs_engine_get_info"));
+ m_pc.fpDestroyEngine = reinterpret_cast<FpDestroyEngine>(dlsym(handle,
+ "csre_cs_engine_destroy"));
+ m_pc.fpGetEngineApiVersion = reinterpret_cast<FpGetEngineApiVersion>(dlsym(
+ handle, "csre_cs_engine_get_api_version"));
+ m_pc.fpGetEngineVendor = reinterpret_cast<FpGetEngineVendor>(dlsym(handle,
+ "csre_cs_engine_get_vendor"));
+ m_pc.fpGetEngineName = reinterpret_cast<FpGetEngineName>(dlsym(handle,
+ "csre_cs_engine_get_name"));
+ m_pc.fpGetEngineVersion = reinterpret_cast<FpGetEngineVersion>(dlsym(handle,
+ "csre_cs_engine_get_version"));
+ m_pc.fpGetEngineDataVersion = reinterpret_cast<FpGetEngineDataVersion>(dlsym(
+ handle, "csre_cs_engine_get_data_version"));
+ m_pc.fpGetEngineLatestUpdateTime =
+ reinterpret_cast<FpGetEngineLatestUpdateTime>(dlsym(handle,
+ "csre_cs_engine_get_latest_update_time"));
+ m_pc.fpGetEngineActivated = reinterpret_cast<FpGetEngineActivated>(dlsym(handle,
+ "csre_cs_engine_get_activated"));
+ m_pc.fpGetEngineVendorLogo = reinterpret_cast<FpGetEngineVendorLogo>(dlsym(
+ handle, "csre_cs_engine_get_vendor_logo"));
if (m_pc.fpGlobalInit == nullptr || m_pc.fpGlobalDeinit == nullptr ||
m_pc.fpContextCreate == nullptr || m_pc.fpContextDestroy == nullptr ||
throw std::logic_error("invalid argument. 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));
}
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));
+ throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " <<
+ ret));
}
csre_cs_context_h &CsEngineContext::get(void)
throw std::logic_error("invalid argument. 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));
}
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));
}
using FpContextCreate = int(*)(csre_cs_context_h *);
using FpContextDestroy = int(*)(csre_cs_context_h);
using FpScanData = int(*)(csre_cs_context_h, const unsigned char *, size_t,
- csre_cs_detected_h *);
+ csre_cs_detected_h *);
using FpScanFile = int(*)(csre_cs_context_h, const char *,
- csre_cs_detected_h *);
+ csre_cs_detected_h *);
using FpScanAppOnCloud = int(*)(csre_cs_context_h, const char *,
csre_cs_detected_h *);
using FpGetSeverity = int(*)(csre_cs_detected_h, csre_cs_severity_level_e *);
using FpGetEngineLatestUpdateTime = int(*)(csre_cs_engine_h, time_t *);
using FpGetEngineActivated = int(*)(csre_cs_engine_h, csre_cs_activated_e *);
using FpGetEngineVendorLogo = int(*)(csre_cs_engine_h, unsigned char **,
- unsigned int *);
+ unsigned int *);
struct PluginContext {
void *dlhandle;
//===========================================================================
std::vector<std::regex> File::m_regexprs;
-File::File(const std::string &fpath)
- : m_path(fpath), m_inApp(false)
+File::File(const std::string &fpath) : m_path(fpath), m_inApp(false)
{
if (m_regexprs.size() == 0)
initRegex();
}
File::File(const std::string &fpath, bool belongToApp,
- const std::string &pkgId, const std::string &user, const std::string &pkgPath)
- : m_path(fpath), m_inApp(belongToApp), m_appPkgId(pkgId), m_appUser(user),
- m_appPkgPath(pkgPath)
+ const std::string &pkgId, const std::string &user, const std::string &pkgPath) :
+ m_path(fpath), m_inApp(belongToApp), m_appPkgId(pkgId), m_appUser(user),
+ m_appPkgPath(pkgPath)
{
}
int ret = stat(fpath.c_str(), &s);
if (ret != 0) {
- if (errno == ENOENT)
+ if (errno == ENOENT) {
WARN("file[" << fpath << "] not exist!");
- else {
+ } else {
// TODO: throw exception? can we trust errno value?
ERROR("stat() failed with file[" << fpath << "]. errno: " << errno);
}
return item;
}
-DirVisitor::DirVisitor(const std::string &fpath, time_t modifiedSince)
- : m_path(fpath), m_since(modifiedSince), m_currDir(nullptr),
- m_currEntry(nullptr)
+DirVisitor::DirVisitor(const std::string &fpath, time_t modifiedSince) :
+ m_path(fpath), m_since(modifiedSince), m_currDir(nullptr), m_currEntry(nullptr)
{
m_dirs.push(m_path);
}
std::string fullPath;
if (m_dirs.front().size() > 0 &&
- m_dirs.front().at(m_dirs.front().size() - 1) == '/') {
+ m_dirs.front().at(m_dirs.front().size() - 1) == '/')
fullPath = m_dirs.front() + result->d_name;
- } else {
+ else
fullPath = m_dirs.front() + "/" + result->d_name;
- }
if (result->d_type == DT_DIR) {
- if (strcmp(result->d_name, ".") != 0 && strcmp(result->d_name, "..") != 0) {
+ if (strcmp(result->d_name, ".") != 0 && strcmp(result->d_name, "..") != 0)
m_dirs.push(fullPath);
- }
continue;
}
context.get(static_cast<int>(CsContext::Key::ScanOnCloud), scanOnCloud);
INFO("Context info:"
- " PopupMessage: " << popupMessage <<
- " AskUser: " << askUser <<
- " CoreUsage: " << coreUsage <<
- " ScanOnCloud: " << scanOnCloud);
+ " PopupMessage: " << popupMessage <<
+ " AskUser: " << askUser <<
+ " CoreUsage: " << coreUsage <<
+ " ScanOnCloud: " << scanOnCloud);
}
}
m_wp(new WpLoader(WP_ENGINE_PATH))
{
// TODO: Provide engine-specific res/working dirs
- int ret = m_cs->globalInit(SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
+ int ret = m_cs->globalInit(SAMPLE_ENGINE_RO_RES_DIR,
+ SAMPLE_ENGINE_RW_WORKING_DIR);
+
if (ret != CSRE_ERROR_NONE)
throw std::runtime_error(FORMAT("global init cs engine. 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));
Logic::~Logic()
{
int ret = m_cs->globalDeinit();
+
if (ret != CSRE_ERROR_NONE)
throw std::runtime_error(FORMAT("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));
}
default:
throw std::range_error(FORMAT("Command id[" << static_cast<int>(info.first)
- << "] isn't in range."));
+ << "] isn't in range."));
}
}
return BinaryQueue::Serialize(CSR_ERROR_NONE, StrSet()).pop();
}
-RawBuffer Logic::judgeStatus(const CsContext &context, const std::string &filepath)
+RawBuffer Logic::judgeStatus(const CsContext &context,
+ const std::string &filepath)
{
INFO("Judge Status[" << filepath << "] by engine");
return BinaryQueue::Serialize(CSR_ERROR_NONE).pop();
}
-RawBuffer Logic::getDetected(const CsContext &context, const std::string &filepath)
+RawBuffer Logic::getDetected(const CsContext &context,
+ const std::string &filepath)
{
INFO("Get Detected[" << filepath << "] by engine");
return BinaryQueue::Serialize(CSR_ERROR_NONE, detected).pop();
}
-RawBuffer Logic::getDetectedList(const CsContext &context, const std::string &dir)
+RawBuffer Logic::getDetectedList(const CsContext &context,
+ const std::string &dir)
{
INFO("Get Detected List[" << dir << "] by engine");
return BinaryQueue::Serialize(CSR_ERROR_NONE, list).pop();
}
-RawBuffer Logic::getIgnored(const CsContext &context, const std::string &filepath)
+RawBuffer Logic::getIgnored(const CsContext &context,
+ const std::string &filepath)
{
INFO("Get Ignored[" << filepath << "] by engine");
return BinaryQueue::Serialize(CSR_ERROR_NONE, detected).pop();
}
-RawBuffer Logic::getIgnoredList(const CsContext &context, const std::string &dir)
+RawBuffer Logic::getIgnoredList(const CsContext &context,
+ const std::string &dir)
{
INFO("Get Ignored List[" << dir << "] by engine");
csre_wp_check_result_h result;
int ret = CSR_ERROR_NONE;
int eret = m_wp->checkUrl(c, url.c_str(), &result);
+
if (eret != CSRE_ERROR_NONE) {
ret = CSR_ERROR_ENGINE_INTERNAL;
ERROR("Engine error. engine api ret: " << eret);
return BinaryQueue::Serialize(ret, wr).pop();
}
-void Logic::getUserResponse(const WpContext &c, const std::string &url, csr_wp_risk_level_e level, WpResult &wr)
+void Logic::getUserResponse(const WpContext &c, const std::string &url,
+ csr_wp_risk_level_e level, WpResult &wr)
{
int isAsk;
c.get(static_cast<int>(WpContext::Key::AskUser), isAsk);
+
if (static_cast<csr_wp_ask_user_e>(isAsk) == CSR_WP_NOT_ASK_USER)
return;
response = askUser.wpAskPermission(popupMessage, item);
if (response == Ui::WpResponse::ALLOW)
- wr.set(static_cast<int>(WpResult::Key::UserResponse), CSR_WP_PROCESSING_ALLOWED);
+ wr.set(static_cast<int>(WpResult::Key::UserResponse),
+ CSR_WP_PROCESSING_ALLOWED);
else if (response == Ui::WpResponse::DENY)
- wr.set(static_cast<int>(WpResult::Key::UserResponse), CSR_WP_PROCESSING_DISALLOWED);
+ wr.set(static_cast<int>(WpResult::Key::UserResponse),
+ CSR_WP_PROCESSING_DISALLOWED);
else
throw std::runtime_error("Invalid response from popup service.");
} else {
item.risk = CSR_WP_RISK_HIGH;
response = askUser.wpNotify(popupMessage, item);
+
if (response == Ui::WpResponse::CONFIRM)
- wr.set(static_cast<int>(WpResult::Key::UserResponse), CSR_WP_PROCESSING_DISALLOWED);
+ wr.set(static_cast<int>(WpResult::Key::UserResponse),
+ CSR_WP_PROCESSING_DISALLOWED);
else
throw std::runtime_error("Invalid response from popup service.");
}
csre_wp_risk_level_e elevel;
int eret = m_wp->getRiskLevel(r, &elevel);
+
if (eret != CSRE_ERROR_NONE)
throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret));
DEBUG("Get engine risk level: " << static_cast<int>(elevel));
csr_wp_risk_level_e level;
+
switch (elevel) {
case CSRE_WP_RISK_LOW:
level = CSR_WP_RISK_LOW;
break;
+
case CSRE_WP_RISK_UNVERIFIED:
level = CSR_WP_RISK_UNVERIFIED;
break;
+
case CSRE_WP_RISK_MEDIUM:
level = CSR_WP_RISK_MEDIUM;
break;
+
case CSRE_WP_RISK_HIGH:
level = CSR_WP_RISK_HIGH;
break;
+
default:
throw std::logic_error(FORMAT("Invalid elevel: " << static_cast<int>(elevel)));
}
std::string detailedUrl;
eret = m_wp->getDetailedUrl(r, detailedUrl);
+
if (eret != CSRE_ERROR_NONE)
throw std::runtime_error(FORMAT("Converting wp result. ret: " << eret));
RawBuffer checkUrl(const WpContext &context, const std::string &url);
WpResult convert(csre_wp_check_result_h &);
- void getUserResponse(const WpContext &, const std::string &url, csr_wp_risk_level_e, WpResult &);
+ void getUserResponse(const WpContext &, const std::string &url,
+ csr_wp_risk_level_e, WpResult &);
std::shared_ptr<CsLoader> m_cs;
std::shared_ptr<WpLoader> m_wp;
{
DEBUG("let's dispatch it to worker threads.");
- auto process = [&](RawBuffer &buffer) {
+ auto process = [&](RawBuffer & buffer) {
connection->send(m_logic.dispatch(buffer));
};
void ThreadPool::add(void)
{
std::thread t([this]() {
-
DEBUG("Thread[" << std::this_thread::get_id() << "] start in pool");
while (true) {
if (m_stop && m_tasks.empty()) {
DEBUG("Thread pool stop requested. "
- "thread[" << std::this_thread::get_id() << "] returning.");
+ "thread[" << std::this_thread::get_id() << "] returning.");
break;
}
m_cv.notify_all();
- for (auto &worker: m_workers) {
+ for (auto &worker : m_workers) {
if (worker.second.joinable())
worker.second.join();
}
return m_pc.fpContextDestroy(c);
}
-int WpLoader::checkUrl(csre_wp_context_h c, const std::string &url, csre_wp_check_result_h *presult)
+int WpLoader::checkUrl(csre_wp_context_h c, const std::string &url,
+ csre_wp_check_result_h *presult)
{
- if(c == nullptr || url.empty() || presult == nullptr)
+ if (c == nullptr || url.empty() || presult == nullptr)
throw std::invalid_argument("wp loader check url error");
- return m_pc.fpCheckUrl(c,(const char*)url.c_str(),presult);
+ return m_pc.fpCheckUrl(c, (const char *)url.c_str(), presult);
}
-int WpLoader::getRiskLevel(csre_wp_check_result_h r, csre_wp_risk_level_e *plevel)
+int WpLoader::getRiskLevel(csre_wp_check_result_h r,
+ csre_wp_risk_level_e *plevel)
{
- if(r == nullptr || plevel == nullptr)
+ if (r == nullptr || plevel == nullptr)
throw std::invalid_argument("wp loader Get Risk Level error");
- return m_pc.fpGetRiskLevel(r,plevel);
+ return m_pc.fpGetRiskLevel(r, plevel);
}
int WpLoader::getDetailedUrl(csre_wp_check_result_h r, std::string &value)
}
int WpLoader::getEngineActivated(csre_wp_engine_h e,
- csre_wp_activated_e *pactivated)
+ csre_wp_activated_e *pactivated)
{
if (e == nullptr || pactivated == nullptr)
throw std::invalid_argument("wp loader get engine activated");
}
int WpLoader::getEngineVendorLogo(csre_wp_engine_h e,
- std::vector<unsigned char> &value)
+ std::vector<unsigned char> &value)
{
if (e == nullptr)
throw std::invalid_argument("wp loader get engine vendor logo");
m_pc.dlhandle = handle;
- m_pc.fpGlobalInit = reinterpret_cast<FpGlobalInit>(dlsym(handle, "csre_wp_global_initialize"));
- m_pc.fpGlobalDeinit = reinterpret_cast<FpGlobalDeinit>(dlsym(handle, "csre_wp_global_deinitialize"));
- m_pc.fpContextCreate = reinterpret_cast<FpContextCreate>(dlsym(handle, "csre_wp_context_create"));
- m_pc.fpContextDestroy = reinterpret_cast<FpContextDestroy>(dlsym(handle, "csre_wp_context_destroy"));
- m_pc.fpCheckUrl = reinterpret_cast<FpCheckUrl>(dlsym(handle, "csre_wp_check_url"));
- m_pc.fpGetRiskLevel = reinterpret_cast<FpGetRiskLevel>(dlsym(handle, "csre_wp_result_get_risk_level"));
- m_pc.fpGetDetailedUrl = reinterpret_cast<FPGetDetailedUrl>(dlsym(handle, "csre_wp_result_get_detailed_url"));
- m_pc.fpGetErrorString = reinterpret_cast <FpGetErrorString>(dlsym(handle, "csre_wp_get_error_string"));
- m_pc.fpGetEngineInfo = reinterpret_cast<FpGetEngineInfo>(dlsym(handle, "csre_wp_engine_get_info"));
- m_pc.fpDestroyEngine = reinterpret_cast<FpDestroyEngine>(dlsym(handle, "csre_wp_engine_destroy"));
- m_pc.fpGetEngineApiVersion = reinterpret_cast<FpGetEngineApiVersion>(dlsym(handle, "csre_wp_engine_get_api_version"));
- m_pc.fpGetEngineVendor = reinterpret_cast<FpGetEngineVendor>(dlsym(handle, "csre_wp_engine_get_vendor"));
- m_pc.fpGetEngineName = reinterpret_cast<FpGetEngineName>(dlsym(handle, "csre_wp_engine_get_name"));
- m_pc.fpGetEngineVersion = reinterpret_cast<FpGetEngineVersion>(dlsym(handle, "csre_wp_engine_get_version"));
- m_pc.fpGetEngineDataVersion = reinterpret_cast<FpGetEngineDataVersion>(dlsym(handle, "csre_wp_engine_get_data_version"));
- m_pc.fpGetEngineLatestUpdateTime = reinterpret_cast<FpGetEngineLatestUpdateTime>(dlsym(handle, "csre_wp_engine_get_latest_update_time"));
- m_pc.fpGetEngineActivated = reinterpret_cast<FpGetEngineActivated>(dlsym(handle, "csre_wp_engine_get_activated"));
- m_pc.fpGetEngineVendorLogo = reinterpret_cast<FpGetEngineVendorLogo>(dlsym(handle, "csre_wp_engine_get_vendor_logo"));
+ m_pc.fpGlobalInit = reinterpret_cast<FpGlobalInit>(dlsym(handle,
+ "csre_wp_global_initialize"));
+ m_pc.fpGlobalDeinit = reinterpret_cast<FpGlobalDeinit>(dlsym(handle,
+ "csre_wp_global_deinitialize"));
+ m_pc.fpContextCreate = reinterpret_cast<FpContextCreate>(dlsym(handle,
+ "csre_wp_context_create"));
+ m_pc.fpContextDestroy = reinterpret_cast<FpContextDestroy>(dlsym(handle,
+ "csre_wp_context_destroy"));
+ m_pc.fpCheckUrl = reinterpret_cast<FpCheckUrl>(dlsym(handle,
+ "csre_wp_check_url"));
+ m_pc.fpGetRiskLevel = reinterpret_cast<FpGetRiskLevel>(dlsym(handle,
+ "csre_wp_result_get_risk_level"));
+ m_pc.fpGetDetailedUrl = reinterpret_cast<FPGetDetailedUrl>(dlsym(handle,
+ "csre_wp_result_get_detailed_url"));
+ m_pc.fpGetErrorString = reinterpret_cast <FpGetErrorString>(dlsym(handle,
+ "csre_wp_get_error_string"));
+ m_pc.fpGetEngineInfo = reinterpret_cast<FpGetEngineInfo>(dlsym(handle,
+ "csre_wp_engine_get_info"));
+ m_pc.fpDestroyEngine = reinterpret_cast<FpDestroyEngine>(dlsym(handle,
+ "csre_wp_engine_destroy"));
+ m_pc.fpGetEngineApiVersion = reinterpret_cast<FpGetEngineApiVersion>(dlsym(
+ handle, "csre_wp_engine_get_api_version"));
+ m_pc.fpGetEngineVendor = reinterpret_cast<FpGetEngineVendor>(dlsym(handle,
+ "csre_wp_engine_get_vendor"));
+ m_pc.fpGetEngineName = reinterpret_cast<FpGetEngineName>(dlsym(handle,
+ "csre_wp_engine_get_name"));
+ m_pc.fpGetEngineVersion = reinterpret_cast<FpGetEngineVersion>(dlsym(handle,
+ "csre_wp_engine_get_version"));
+ m_pc.fpGetEngineDataVersion = reinterpret_cast<FpGetEngineDataVersion>(dlsym(
+ handle, "csre_wp_engine_get_data_version"));
+ m_pc.fpGetEngineLatestUpdateTime =
+ reinterpret_cast<FpGetEngineLatestUpdateTime>(dlsym(handle,
+ "csre_wp_engine_get_latest_update_time"));
+ m_pc.fpGetEngineActivated = reinterpret_cast<FpGetEngineActivated>(dlsym(handle,
+ "csre_wp_engine_get_activated"));
+ m_pc.fpGetEngineVendorLogo = reinterpret_cast<FpGetEngineVendorLogo>(dlsym(
+ handle, "csre_wp_engine_get_vendor_logo"));
if (m_pc.fpGlobalInit == nullptr || m_pc.fpGlobalDeinit == nullptr ||
m_pc.fpContextCreate == nullptr || m_pc.fpContextDestroy == nullptr ||
throw std::logic_error("invalid argument. 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));
}
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));
+ throw std::runtime_error(FORMAT("destroy engine context by loader. ret: " <<
+ ret));
}
csre_wp_context_h &WpEngineContext::get(void)
throw std::logic_error("invalid argument. 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));
}
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));
}
int globalDeinit();
int contextCreate(csre_wp_context_h &);
int contextDestroy(csre_wp_context_h);
- int checkUrl(csre_wp_context_h handle, const std::string &, csre_wp_check_result_h *);
+ int checkUrl(csre_wp_context_h handle, const std::string &,
+ csre_wp_check_result_h *);
int getRiskLevel(csre_wp_check_result_h, csre_wp_risk_level_e *);
int getDetailedUrl(csre_wp_check_result_h, std::string &);
int getErrorString(int, std::string &);
using FpGlobalDeinit = int(*)();
using FpContextCreate = int(*)(csre_wp_context_h *);
using FpContextDestroy = int(*)(csre_wp_context_h);
- using FpCheckUrl = int(*)(csre_wp_context_h , const char *, csre_wp_check_result_h *);
+ using FpCheckUrl = int(*)(csre_wp_context_h , const char *,
+ csre_wp_check_result_h *);
using FpGetRiskLevel = int(*)(csre_wp_check_result_h, csre_wp_risk_level_e *);
using FPGetDetailedUrl = int(*)(csre_wp_check_result_h, const char **);
using FpGetErrorString = int(*)(int, const char **);
using FpGetEngineDataVersion = int(*)(csre_wp_engine_h, const char **);
using FpGetEngineLatestUpdateTime = int(*)(csre_wp_engine_h, time_t *);
using FpGetEngineActivated = int(*)(csre_wp_engine_h, csre_wp_activated_e *);
- using FpGetEngineVendorLogo = int(*)(csre_wp_engine_h, unsigned char **, unsigned int *);
+ using FpGetEngineVendorLogo = int(*)(csre_wp_engine_h, unsigned char **,
+ unsigned int *);
struct PluginContext {
void *dlhandle;
{
}
-CsResponse AskUser::fileSingle(const std::string &message, const FileItem &item) const
+CsResponse AskUser::fileSingle(const std::string &message,
+ const FileItem &item) const
{
return static_cast<CsResponse>(m_dispatcher->methodCall<int>(
- static_cast<int>(CommandId::FILE_SINGLE),
- message,
- item));
+ static_cast<int>(CommandId::FILE_SINGLE),
+ message,
+ item));
}
-ResponseMap AskUser::fileMultiple(const std::string &message, const FileItems &items) const
+ResponseMap AskUser::fileMultiple(const std::string &message,
+ const FileItems &items) const
{
return m_dispatcher->methodCall<ResponseMap>(
- static_cast<int>(CommandId::FILE_MULTIPLE),
- message,
- items);
+ static_cast<int>(CommandId::FILE_MULTIPLE),
+ message,
+ items);
}
-WpResponse AskUser::wpAskPermission(const std::string &message, const UrlItem &item) const
+WpResponse AskUser::wpAskPermission(const std::string &message,
+ const UrlItem &item) const
{
return static_cast<WpResponse>(m_dispatcher->methodCall<int>(
- static_cast<int>(CommandId::WP_ASK_PERMISSION),
- message,
- item));
+ static_cast<int>(CommandId::WP_ASK_PERMISSION),
+ message,
+ item));
}
-WpResponse AskUser::wpNotify(const std::string &message, const UrlItem &item) const
+WpResponse AskUser::wpNotify(const std::string &message,
+ const UrlItem &item) const
{
return static_cast<WpResponse>(m_dispatcher->methodCall<int>(
- static_cast<int>(CommandId::WP_NOTIFY),
- message,
- item));
+ static_cast<int>(CommandId::WP_NOTIFY),
+ message,
+ item));
}
} // namespace Ui
AskUser &operator=(const AskUser &) = delete;
CsResponse fileSingle(const std::string &message, const FileItem &item) const;
- ResponseMap fileMultiple(const std::string &message, const FileItems &items) const;
+ ResponseMap fileMultiple(const std::string &message,
+ const FileItems &items) const;
- WpResponse wpAskPermission(const std::string &message, const UrlItem &item) const;
+ WpResponse wpAskPermission(const std::string &message,
+ const UrlItem &item) const;
WpResponse wpNotify(const std::string &message, const UrlItem &item) const;
private:
g_callbackRegistry[*response]();
}
-void registerCb(Evas_Object *button, int *response, std::function<void()> &&func)
+void registerCb(Evas_Object *button, int *response,
+ std::function<void()> &&func)
{
evas_object_smart_callback_add(button, "clicked", evasCbWrapper, response);
g_callbackRegistry[*response] = std::move(func);
RawBuffer Logic::dispatch(const RawBuffer &in)
{
auto info = getRequestInfo(in);
- INFO("Request dispatch on popup-service. CommandId: " << static_cast<int>(info.first));
+ INFO("Request dispatch on popup-service. CommandId: " << static_cast<int>
+ (info.first));
switch (info.first) {
case CommandId::FILE_SINGLE: {
return std::make_pair(static_cast<CommandId>(int_id), std::move(q));
}
-RawBuffer Logic::fileSingle(const std::string &message, const FileItem &item) const
+RawBuffer Logic::fileSingle(const std::string &message,
+ const FileItem &item) const
{
INFO("fileSingle start with param.. "
- "message[" << message << "] "
- "filepath[" << item.filepath << "] "
- "severity[" << static_cast<int>(item.severity) << "] "
- "threat[" << static_cast<int>(item.threat) << "]");
+ "message[" << message << "] "
+ "filepath[" << item.filepath << "] "
+ "severity[" << static_cast<int>(item.severity) << "] "
+ "threat[" << static_cast<int>(item.threat) << "]");
Popup popup;
return q.pop();
}
-RawBuffer Logic::fileMultiple(const std::string &message, const FileItems &items) const
+RawBuffer Logic::fileMultiple(const std::string &message,
+ const FileItems &items) const
{
(void) message;
(void) items;
return RawBuffer();
}
-RawBuffer Logic::wpAskPermission(const std::string &message, const UrlItem &item) const
+RawBuffer Logic::wpAskPermission(const std::string &message,
+ const UrlItem &item) const
{
Popup popup;
popup.fillText("Danger URL", FORMAT(
- "URL: " << item.url << "\n" <<
- "Risky: " << (item.risk == CSR_WP_RISK_HIGH
- ? "High" : "Medium") << "\n" <<
- message.c_str()));
+ "URL: " << item.url << "\n" <<
+ "Risky: " << (item.risk == CSR_WP_RISK_HIGH
+ ? "High" : "Medium") << "\n" <<
+ message.c_str()));
BinaryQueue q;
Popup popup;
popup.fillText("Danger URL", FORMAT(
- "URL: " << item.url << "\n" <<
- "Risky: " << (item.risk == CSR_WP_RISK_HIGH
- ? "High" : "Medium") << "\n" <<
- message.c_str()));
+ "URL: " << item.url << "\n" <<
+ "Risky: " << (item.risk == CSR_WP_RISK_HIGH
+ ? "High" : "Medium") << "\n" <<
+ message.c_str()));
BinaryQueue q;
std::pair<CommandId, BinaryQueue> getRequestInfo(const RawBuffer &);
RawBuffer fileSingle(const std::string &message, const FileItem &item) const;
- RawBuffer fileMultiple(const std::string &message, const FileItems &items) const;
+ RawBuffer fileMultiple(const std::string &message,
+ const FileItems &items) const;
- RawBuffer wpAskPermission(const std::string &message, const UrlItem &item) const;
+ RawBuffer wpAskPermission(const std::string &message,
+ const UrlItem &item) const;
RawBuffer wpNotify(const std::string &message, const UrlItem &item) const;
};
/* TODO: do shutdown.
* shutdown generates segmentation fault by unknown reason.
*/
-// elm_shutdown();
+ // elm_shutdown();
}
};
{
if (m_popup)
evas_object_del(m_popup);
+
if (m_win)
evas_object_del(m_win);
+
elm_exit();
}
/**
* @brief TCS context handle.
*/
-typedef struct __csr_cs_context_s* csr_cs_context_h;
+typedef struct __csr_cs_context_s *csr_cs_context_h;
/**
* @brief TCS detected malware info handle.
*/
-typedef struct __csr_cs_detected_s* csr_cs_detected_h;
+typedef struct __csr_cs_detected_s *csr_cs_detected_h;
/**
* @brief TCS detected malware list handle
*/
-typedef struct __csr_cs_detected_list_s* csr_cs_detected_list_h;
+typedef struct __csr_cs_detected_list_s *csr_cs_detected_list_h;
/**
* @brief TCS engine info handle.
*/
-typedef struct __csr_cs_engine_s* csr_cs_engine_h;
+typedef struct __csr_cs_engine_s *csr_cs_engine_h;
/**
* @brief The callback function is called when a malware detected.\
* It's only for an asynchronous scan function.
*/
-typedef void (*csr_cs_on_detected_cb)(void *user_data, csr_cs_detected_h detected);
+typedef void (*csr_cs_on_detected_cb)(void *user_data,
+ csr_cs_detected_h detected);
/**
* @brief The callback function is called when scanning is fininshed without an error.\
* @brief The callback function is called when a file scan is completed.\
* It's only for an asynchronous scan function.
*/
-typedef void (*csr_cs_on_file_scanned_cb)(void *user_data, const char* file_path);
+typedef void (*csr_cs_on_file_scanned_cb)(void *user_data,
+ const char *file_path);
#ifdef __cplusplus
}
* @retval #CSR_ERROR_ENGINE_INTERNAL Engine Internal error
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_context_create(csr_cs_context_h* phandle);
+int csr_cs_context_create(csr_cs_context_h *phandle);
/**
* @brief Releases all system resources associated with a Malware Screening API handle.
*
* @see csr_cs_context_create()
*/
-int csr_cs_set_popup_message(csr_cs_context_h handle, const char* message);
+int csr_cs_set_popup_message(csr_cs_context_h handle, const char *message);
/**
* @brief Sets a maxium core usage during scanning.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_scan_data(csr_cs_context_h handle,
- const unsigned char *data,
- size_t length,
- csr_cs_detected_h *pdetected);
+ const unsigned char *data,
+ size_t length,
+ csr_cs_detected_h *pdetected);
/**
* @brief Main function for caller to scan a file specified by file path for malware.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_scan_file(csr_cs_context_h handle,
- const char *file_path,
- csr_cs_detected_h *pdetected);
+ const char *file_path,
+ csr_cs_detected_h *pdetected);
/**
* @brief Sets a callback function for detection of a malware.
* @retval #CSR_ERROR_INVALID_PARAMETER callback is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_set_callback_on_detected(csr_cs_context_h handle, csr_cs_on_detected_cb callback);
+int csr_cs_set_callback_on_detected(csr_cs_context_h handle,
+ csr_cs_on_detected_cb callback);
/**
* @brief Sets a callback function for scanning completed without an error.
* @retval #CSR_ERROR_INVALID_PARAMETER callback is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_set_callback_on_completed(csr_cs_context_h handle, csr_cs_on_completed_cb callback);
+int csr_cs_set_callback_on_completed(csr_cs_context_h handle,
+ csr_cs_on_completed_cb callback);
/**
* @brief Sets a callback function for scanning cancelled.
* @retval #CSR_ERROR_INVALID_PARAMETER callback is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_set_callback_on_cancelled(csr_cs_context_h handle, csr_cs_on_cancelled_cb callback);
+int csr_cs_set_callback_on_cancelled(csr_cs_context_h handle,
+ csr_cs_on_cancelled_cb callback);
/**
* @brief Sets a callback function for scanning stopped with an error.
* @retval #CSR_ERROR_INVALID_PARAMETER callback is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_set_callback_on_error(csr_cs_context_h handle, csr_cs_on_error_cb callback);
+int csr_cs_set_callback_on_error(csr_cs_context_h handle,
+ csr_cs_on_error_cb callback);
/**
* @retval #CSR_ERROR_INVALID_PARAMETER callback is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_set_callback_on_file_scanned(csr_cs_context_h handle, csr_cs_on_file_scanned_cb callback);
+int csr_cs_set_callback_on_file_scanned(csr_cs_context_h handle,
+ csr_cs_on_file_scanned_cb callback);
/**
* @brief Main function for caller to scan files specified by an array of file paths
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_scan_files_async(csr_cs_context_h handle,
- const char **file_paths,
- size_t count,
- void *user_data);
+ const char **file_paths,
+ size_t count,
+ void *user_data);
/**
* @brief Main function for caller to scan a directoy specified by
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_scan_dir_async(csr_cs_context_h handle,
- const char *dir_path,
- void *user_data);
+ const char *dir_path,
+ void *user_data);
/**
* @brief Main function for caller to scan directories specified by
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_scan_dirs_async(csr_cs_context_h handle,
- const char **dir_paths,
- size_t count,
- void *user_data);
+ const char **dir_paths,
+ size_t count,
+ void *user_data);
/**
* @retval #CSR_ERROR_INVALID_PARAMETER pseverity is invalid.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_severity(csr_cs_detected_h detected, csr_cs_severity_level_e* pseverity);
+int csr_cs_detected_get_severity(csr_cs_detected_h detected,
+ csr_cs_severity_level_e *pseverity);
/**
* @brief extracts the threat type of a detected malware from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER pharmful_type is invalid.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_threat_type(csr_cs_detected_h detected, csr_cs_threat_type_e* pthreat_type);
+int csr_cs_detected_get_threat_type(csr_cs_detected_h detected,
+ csr_cs_threat_type_e *pthreat_type);
/**
* @brief extracts the name of a detected malware from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER malware_name is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_malware_name(csr_cs_detected_h detected, const char** pmalware_name);
+int csr_cs_detected_get_malware_name(csr_cs_detected_h detected,
+ const char **pmalware_name);
/**
* @brief extracts an url that contains detailed information on vendor's web site from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER malware_name is invalid.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_detailed_url(csr_cs_detected_h detected, const char** pdetailed_url);
+int csr_cs_detected_get_detailed_url(csr_cs_detected_h detected,
+ const char **pdetailed_url);
/**
* @brief extracts the time stamp when a malware is detected from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER timestamp is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_timestamp(csr_cs_detected_h detected, time_t* ptimestamp);
+int csr_cs_detected_get_timestamp(csr_cs_detected_h detected,
+ time_t *ptimestamp);
/**
* @brief extracts the file name where a malware is detected from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER file_name is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_file_name(csr_cs_detected_h detected, const char** pfile_name);
+int csr_cs_detected_get_file_name(csr_cs_detected_h detected,
+ const char **pfile_name);
/**
* @brief extracts a user reponse of a popup from the detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER presponse is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_user_response(csr_cs_detected_h detected, csr_cs_user_response_e* presponse);
+int csr_cs_detected_get_user_response(csr_cs_detected_h detected,
+ csr_cs_user_response_e *presponse);
/**
* @brief check if a malware was detected in an application or in a file.
* @retval #CSR_ERROR_INVALID_PARAMETER pis_app is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_is_app(csr_cs_detected_h detected, bool* pis_app);
+int csr_cs_detected_is_app(csr_cs_detected_h detected, bool *pis_app);
/**
* @brief extracts the package id of an application where a malware is detected from detected malware handle.
* @retval #CSR_ERROR_INVALID_PARAMETER ppkg_id is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_detected_get_pkg_id(csr_cs_detected_h detected, const char** ppkg_id);
+int csr_cs_detected_get_pkg_id(csr_cs_detected_h detected,
+ const char **ppkg_id);
/**
* @brief Judges how a detected malware file is handled.
* @retval #CSR_ERROR_SERVER Server has been failed for some reason
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_judge_detected_malware(csr_cs_context_h handle, csr_cs_detected_h detected, csr_cs_action_e action);
+int csr_cs_judge_detected_malware(csr_cs_context_h handle,
+ csr_cs_detected_h detected, csr_cs_action_e action);
/**
* @retval #CSR_ERROR_SERVER Server has been failed for some reason
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_get_detected_malware(csr_cs_context_h handle, const char *file_path, csr_cs_detected_h *pdetected);
+int csr_cs_get_detected_malware(csr_cs_context_h handle, const char *file_path,
+ csr_cs_detected_h *pdetected);
/**
* @brief Gets information on a detected malware files specified by directory path.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_get_detected_malwares(csr_cs_context_h handle, const char *dir,
- csr_cs_detected_list_h *plist, size_t *pcount);
+ csr_cs_detected_list_h *plist, size_t *pcount);
/**
* @brief Gets information on a ignored malware file specified by file path.
* @retval #CSR_ERROR_SERVER Server has been failed for some reason
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_get_ignored_malware(csr_cs_context_h handle, const char *file_path, csr_cs_detected_h *pdetected);
+int csr_cs_get_ignored_malware(csr_cs_context_h handle, const char *file_path,
+ csr_cs_detected_h *pdetected);
/**
* @brief Gets information on a ignored malware files specified by directory path.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
int csr_cs_get_ignored_malwares(csr_cs_context_h handle, const char *dir,
- csr_cs_detected_list_h *plist, size_t *pcount);
+ csr_cs_detected_list_h *plist, size_t *pcount);
/**
* @brief Extracts the detected malware handle from the detected malware list handle.
* @retval #CSR_ERROR_INVALID_PARAMETER index or pdetected is invalid.
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_cs_dlist_get_detected(csr_cs_detected_list_h list, size_t index, csr_cs_detected_h *pdetected);
+int csr_cs_dlist_get_detected(csr_cs_detected_list_h list, size_t index,
+ csr_cs_detected_h *pdetected);
#ifdef __cplusplus
}
* @retval #CSR_ERROR_INVALID_PARAMETER error_code or error_string is invalid
* @retval #CSR_ERROR_UNKNOWN Error with unknown reason
*/
-int csr_get_error_string(int error_code, char** string);
+int csr_get_error_string(int error_code, char **string);
#ifdef __cplusplus
/**
* CSR WP context handle.
*/
-typedef struct __csr_wp_context_s* csr_wp_context_h;
+typedef struct __csr_wp_context_s *csr_wp_context_h;
/**
* CSR WP scan result handle.
*/
-typedef struct __csr_wp_check_result_h* csr_wp_check_result_h;
+typedef struct __csr_wp_check_result_h *csr_wp_check_result_h;
/**
* @brief the options about prompting a popup to a user.
*
* @see csr_wp_context_destroy()
*/
-int csr_wp_context_create(csr_wp_context_h* phandle);
+int csr_wp_context_create(csr_wp_context_h *phandle);
/**
* @brief Releases all system resources associated with a CSR Web Protection API handle.
*
* @see csr_wp_context_create()
*/
-int csr_wp_set_popup_message(csr_wp_context_h handle, const char* message);
+int csr_wp_set_popup_message(csr_wp_context_h handle, const char *message);
/**
* @brief Main function for caller to check URL reputation against the engine vendor's
* @see csr_wp_set_ask_user()
* @see csr_wp_set_popup_message()
*/
-int csr_wp_check_url(csr_wp_context_h handle, const char *url, csr_wp_check_result_h *presult);
+int csr_wp_check_url(csr_wp_context_h handle, const char *url,
+ csr_wp_check_result_h *presult);
//==============================================================================
// Result related
*
* @see csr_wp_check_url()
*/
-int csr_wp_result_get_risk_level(csr_wp_check_result_h result, csr_wp_risk_level_e* plevel);
+int csr_wp_result_get_risk_level(csr_wp_check_result_h result,
+ csr_wp_risk_level_e *plevel);
/**
* @brief Extracts an url of vendor's web site that contains detailed information about the risk
*
* @see csr_wp_check_url()
*/
-int csr_wp_result_get_detailed_url(csr_wp_check_result_h result, const char** detailed_url);
+int csr_wp_result_get_detailed_url(csr_wp_check_result_h result,
+ const char **detailed_url);
/**
* @brief Extracts a user reponse of a popup from the result handle.
* @see csr_wp_check_url()
* @see #csr_wp_user_response_e
*/
-int csr_wp_result_get_user_response(csr_wp_check_result_h result, csr_wp_user_response_e* presponse);
+int csr_wp_result_get_user_response(csr_wp_check_result_h result,
+ csr_wp_user_response_e *presponse);
#ifdef __cplusplus
*
* @see csre_cs_get_engine_info()
*/
-int csre_cs_engine_get_api_version(csre_cs_engine_h engine, const char **version);
+int csre_cs_engine_get_api_version(csre_cs_engine_h engine,
+ const char **version);
/**
* @brief Extracts an vendor name from the engine information handle.
*
* @see csre_cs_get_engine_info()
*/
-int csre_cs_engine_get_data_version(csre_cs_engine_h engine, const char **version);
+int csre_cs_engine_get_data_version(csre_cs_engine_h engine,
+ const char **version);
/**
* @brief Extracts the latest update time of an engine from the engine information handle.
*
* @see csre_cs_get_engine_info()
*/
-int csre_cs_engine_get_latest_update_time(csre_cs_engine_h engine, time_t *time);
+int csre_cs_engine_get_latest_update_time(csre_cs_engine_h engine,
+ time_t *time);
/**
* @brief Extracts the state of engine activation from the engine information handle.
*
* @see csre_cs_get_engine_info()
*/
-int csre_cs_engine_get_activated(csre_cs_engine_h engine, csre_cs_activated_e *pactivated);
+int csre_cs_engine_get_activated(csre_cs_engine_h engine,
+ csre_cs_activated_e *pactivated);
/**
* @brief Extracts an vendor logo image from the engine information handle.
*
* @see csre_cs_get_engine_info()
*/
-int csre_cs_engine_get_vendor_logo(csre_cs_engine_h engine, unsigned char** vendor_logo_image, unsigned int* image_size);
+int csre_cs_engine_get_vendor_logo(csre_cs_engine_h engine,
+ unsigned char **vendor_logo_image, unsigned int *image_size);
#ifdef __cplusplus
}
/**
* CSR CS engine's context handle.
*/
-typedef struct csre_cs_context_s* csre_cs_context_h;
+typedef struct csre_cs_context_s *csre_cs_context_h;
/**
* CSR CS engine's detected malware info handle.
*/
-typedef struct csre_cs_detected_s* csre_cs_detected_h;
+typedef struct csre_cs_detected_s *csre_cs_detected_h;
/**
* @brief Severity level of an detected malware
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_cs_global_initialize(const char *ro_res_dir, const char *rw_working_dir);
+int csre_cs_global_initialize(const char *ro_res_dir,
+ const char *rw_working_dir);
/**
* @brief Deinitializes content screening engine. This will be called only once before
*
* @see csre_cs_context_destroy()
*/
-int csre_cs_context_create(csre_cs_context_h* phandle);
+int csre_cs_context_create(csre_cs_context_h *phandle);
/**
* @brief Destroys context handle.
* @see csre_cs_scan_file()
*/
int csre_cs_scan_data(csre_cs_context_h handle,
- const unsigned char *data,
- size_t length,
- csre_cs_detected_h *pdetected);
+ const unsigned char *data,
+ size_t length,
+ csre_cs_detected_h *pdetected);
/**
* @brief Main function for caller to scan a file specified by file path for malware.
* @see csre_cs_scan_data()
*/
int csre_cs_scan_file(csre_cs_context_h handle,
- const char *file_path,
- csre_cs_detected_h *pdetected);
+ const char *file_path,
+ csre_cs_detected_h *pdetected);
/**
- * @brief Main function for caller to scan an application specified
+ * @brief Main function for caller to scan an application specified
* by an application's root directory for malware.
* The detection of a malware is done on the vendor's clould server.
*
* @see csre_cs_context_create()
* @see csre_cs_scan_data()
*/
-int csre_cs_scan_app_on_cloud(csre_cs_context_h handle, const char* app_root_dir,
- csre_cs_detected_h *pdetected);
+int csre_cs_scan_app_on_cloud(csre_cs_context_h handle,
+ const char *app_root_dir,
+ csre_cs_detected_h *pdetected);
//==============================================================================
// Result related
* @see csre_cs_result_get_detected_by_idx()
* @see csre_cs_result_get_detected_most_severe()
*/
-int csre_cs_detected_get_severity(csre_cs_detected_h detected, csre_cs_severity_level_e* pseverity);
+int csre_cs_detected_get_severity(csre_cs_detected_h detected,
+ csre_cs_severity_level_e *pseverity);
/**
* @retval #CSRE_ERROR_INVALID_PARAMETER pharmful_type is invalid.
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
*/
-int csre_cs_detected_get_threat_type(csre_cs_detected_h detected, csre_cs_threat_type_e* pthreat_type);
+int csre_cs_detected_get_threat_type(csre_cs_detected_h detected,
+ csre_cs_threat_type_e *pthreat_type);
/**
* @brief Extracts the name of a detected malware from the detected malware handle.
* @see csre_cs_result_get_detected_by_idx()
* @see csre_cs_result_get_detected_most_severe()
*/
-int csre_cs_detected_get_malware_name(csre_cs_detected_h detected, const char** name);
+int csre_cs_detected_get_malware_name(csre_cs_detected_h detected,
+ const char **name);
/**
- * @brief Extracts an url of the vendor's web site that contains detailed information
+ * @brief Extracts an url of the vendor's web site that contains detailed information
* about the detected malware from the detected malware handle.
*
* @param[in] detected A detected malware handle.
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_cs_detected_get_detailed_url(csre_cs_detected_h detected, const char** detailed_url);
+int csre_cs_detected_get_detailed_url(csre_cs_detected_h detected,
+ const char **detailed_url);
/**
* @brief Extracts the time stamp when a malware is detected from the detected malware
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_cs_detected_get_timestamp(csre_cs_detected_h detected, time_t* timestamp);
+int csre_cs_detected_get_timestamp(csre_cs_detected_h detected,
+ time_t *timestamp);
/**
* @brief Get the error string for a given engine-defined error code.
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_cs_get_error_string(int error_code, const char** string);
+int csre_cs_get_error_string(int error_code, const char **string);
#ifdef __cplusplus
}
*
* @see csre_wp_engine_get_info()
*/
-int csre_wp_engine_get_api_version(csre_wp_engine_h engine, const char **version);
+int csre_wp_engine_get_api_version(csre_wp_engine_h engine,
+ const char **version);
/**
* @brief Extracts an vendor name from the engine information handle.
*
* @see csre_wp_engine_get_info()
*/
-int csre_wp_engine_get_data_version(csre_wp_engine_h engine, const char **version);
+int csre_wp_engine_get_data_version(csre_wp_engine_h engine,
+ const char **version);
/**
* @brief Extracts the latest update time of an engine from the engine information handle.
*
* @see csre_wp_get_engine_info()
*/
-int csre_wp_engine_get_latest_update_time(csre_wp_engine_h engine, time_t *time);
+int csre_wp_engine_get_latest_update_time(csre_wp_engine_h engine,
+ time_t *time);
/**
* @brief Extracts the state of engine activation from the engine information handle.
*
* @see csre_wp_engine_get_info()
*/
-int csre_wp_engine_get_activated(csre_wp_engine_h engine, csre_wp_activated_e *pactivated);
+int csre_wp_engine_get_activated(csre_wp_engine_h engine,
+ csre_wp_activated_e *pactivated);
/**
* @brief Extracts an vendor logo image from the engine information handle.
*
* @see csre_wp_engine_get_info()
*/
-int csre_wp_engine_get_vendor_logo(csre_wp_engine_h engine, unsigned char** vendor_logo_image, unsigned int* image_size);
+int csre_wp_engine_get_vendor_logo(csre_wp_engine_h engine,
+ unsigned char **vendor_logo_image, unsigned int *image_size);
#ifdef __cplusplus
}
/**
* TWP Engine context handle.
*/
-typedef struct csre_wp_context_s* csre_wp_context_h;
+typedef struct csre_wp_context_s *csre_wp_context_h;
/**
* TWP Engine's check result handle.
*/
-typedef struct csre_wp_check_result_s* csre_wp_check_result_h;
+typedef struct csre_wp_check_result_s *csre_wp_check_result_h;
/**
* @brief Risk level of a url
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_wp_global_initialize(const char *ro_res_dir, const char *rw_working_dir);
+int csre_wp_global_initialize(const char *ro_res_dir,
+ const char *rw_working_dir);
/**
* @brief Deinitializes web protection engine. This will be called only once before
*
* @see csre_wp_context_destroy()
*/
-int csre_wp_context_create(csre_wp_context_h* phandle);
+int csre_wp_context_create(csre_wp_context_h *phandle);
/**
* @brief Releases all system resources associated with a CSR WP engine API handle.
*
* @see csre_wp_context_create()
*/
-int csre_wp_check_url(csre_wp_context_h handle, const char *url, csre_wp_check_result_h *presult);
+int csre_wp_check_url(csre_wp_context_h handle, const char *url,
+ csre_wp_check_result_h *presult);
/**
* @brief Extracts a risk level of the url from the result handle.
*
* @see csre_wp_check_url()
*/
-int csre_wp_result_get_risk_level(csre_wp_check_result_h result, csre_wp_risk_level_e* plevel);
+int csre_wp_result_get_risk_level(csre_wp_check_result_h result,
+ csre_wp_risk_level_e *plevel);
/**
* @brief Extracts an url of vendor's web site that contains detailed information about the risk
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_wp_result_get_detailed_url(csre_wp_check_result_h result, const char** detailed_url);
+int csre_wp_result_get_detailed_url(csre_wp_check_result_h result,
+ const char **detailed_url);
/**
* @brief Get the error string for a given engine-defined error code.
* @retval #CSRE_ERROR_UNKNOWN Error with unknown reason
* @retval -0x0100~-0xFF00 Engine defined error
*/
-int csre_wp_get_error_string(int error_code, const char** string);
+int csre_wp_get_error_string(int error_code, const char **string);
#ifdef __cplusplus
}
namespace {
-const char* GREEN_BEGIN = "\033[0;32m";
-const char* RED_BEGIN = "\033[0;31m";
-const char* CYAN_BEGIN = "\033[0;36m";
-const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
-const char* COLOR_END = "\033[m";
+const char *GREEN_BEGIN = "\033[0;32m";
+const char *RED_BEGIN = "\033[0;31m";
+const char *CYAN_BEGIN = "\033[0;36m";
+const char *BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char *COLOR_END = "\033[m";
const_string
test_phase_identifier()
{
return framework::is_initialized()
- ? const_string(framework::current_test_case().p_name.get())
- : BOOST_TEST_L("Test setup");
+ ? const_string(framework::current_test_case().p_name.get())
+ : BOOST_TEST_L("Test setup");
}
const_string
-get_basename(const const_string &file_name) {
+get_basename(const const_string &file_name)
+{
return basename(file_name.begin());
}
std::string
-get_basename(const std::string &file_name) {
+get_basename(const std::string &file_name)
+{
return basename(file_name.c_str());
}
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 "
//____________________________________________________________________________//
void
-colour_log_formatter::log_finish( std::ostream& ostr )
+colour_log_formatter::log_finish(std::ostream &ostr)
{
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 << std::endl
- << "Compiler: " << BOOST_COMPILER << std::endl
- << "STL : " << BOOST_STDLIB << std::endl
- << "Boost : " << BOOST_VERSION/100000 << "."
- << BOOST_VERSION/100 % 1000 << "."
- << BOOST_VERSION % 100 << std::endl;
+ << "Compiler: " << BOOST_COMPILER << std::endl
+ << "STL : " << BOOST_STDLIB << std::endl
+ << "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;
+ 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;
+ 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;
+ output << "Finished test " << tu.p_type_name << " \"" << tu.p_name << "\"" <<
+ std::endl;
return;
}
output << "\t" << "[ " << color << status << COLOR_END << " ]";
output << ", " << CYAN_BEGIN << "time: ";
+
if (elapsed > 0) {
- if( elapsed % 1000 == 0 )
- output << elapsed/1000 << "ms";
+ if (elapsed % 1000 == 0)
+ output << elapsed / 1000 << "ms";
else
output << elapsed << "mks";
} else {
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();
+ boost::execution_exception::location const &loc = ex.where();
output << '\t' << BOLD_YELLOW_BEGIN << get_basename(loc.m_file_name)
- << '(' << loc.m_line_num << "), ";
+ << '(' << loc.m_line_num << "), ";
output << "fatal error in \""
- << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function ) << "\": ";
+ << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function) <<
+ "\": ";
output << 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 << ")";
+ << '(' << checkpoint_data.m_line_num << ")";
+
if (!checkpoint_data.m_message.empty())
output << ": " << checkpoint_data.m_message;
}
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 << '\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 << '\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' << BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name)
- << '(' << entry_data.m_line_num << "), ";
+ << '(' << entry_data.m_line_num << "), ";
output << "error in \"" << test_phase_identifier() << "\": ";
m_isTestCaseFailed = true;
break;
+
case BOOST_UTL_ET_FATAL_ERROR:
output << '\t' << BOLD_YELLOW_BEGIN << get_basename(entry_data.m_file_name)
- << '(' << entry_data.m_line_num << "), ";
+ << '(' << entry_data.m_line_num << "), ";
output << " fatal error in \"" << test_phase_identifier() << "\": ";
m_isTestCaseFailed = true;
break;
}
+
output << COLOR_END;
}
void
colour_log_formatter::log_entry_value(
- std::ostream& output,
- const_string value)
+ std::ostream &output,
+ const_string 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;
}
void
colour_log_formatter::log_entry_finish(
- std::ostream& output)
+ std::ostream &output)
{
output << std::endl;
}
// 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&);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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&);
+ std::ostream &,
+ boost::unit_test::lazy_ostream const &value);
+ void log_entry_finish(std::ostream &);
private:
bool m_isTestCaseFailed;
struct TestConfig {
TestConfig()
{
- boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_test_units);
+ 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 Csr::Test::colour_log_formatter);
+ boost::unit_test::unit_test_log.set_formatter(new
+ Csr::Test::colour_log_formatter);
}
};
std::cout << "###################################################" << std::endl;
bool isValid = true;
+
switch (response) {
case CsResponse::REMOVE:
std::cout << "############## REMOVE BUTTON PRESSED #############" << std::endl;
break;
+
case CsResponse::IGNORE:
std::cout << "############## IGNORE BUTTON PRESSED #############" << std::endl;
break;
+
case CsResponse::SKIP:
std::cout << "############## SKIP BUTTON PRESSED #############" << std::endl;
break;
+
default:
std::cout << "############## Invalid Response!!! #############" << std::endl;
isValid = false;
std::cout << "###################################################" << std::endl;
bool isValid = true;
+
switch (response) {
case WpResponse::ALLOW:
std::cout << "############## ALLOW BUTTON PRESSED #############" << std::endl;
break;
+
case WpResponse::DENY:
std::cout << "############## DENY BUTTON PRESSED #############" << std::endl;
break;
+
case WpResponse::CONFIRM:
std::cout << "############## CONFIRM BUTTON PRESSED #############" << std::endl;
break;
+
default:
std::cout << "############## Invalid Response!!! #############" << std::endl;
isValid = false;
item.risk = CSR_WP_RISK_MEDIUM;
item.url = "http://csr.test.dummyurl.com";
- auto response = askuser.wpAskPermission("Message for wp_ask_permission tc", item);
+ auto response = askuser.wpAskPermission("Message for wp_ask_permission tc",
+ item);
printPressed(response);
} catch (...) {
BOOST_REQUIRE_MESSAGE(0, "exception shouldn't be thrown.");
csr_cs_detected_list_h detected_list;
size_t cnt = 0;
- ASSERT_IF(csr_cs_get_detected_malwares(context, "dummy_dir_path", &detected_list, &cnt),
+ ASSERT_IF(csr_cs_get_detected_malwares(context, "dummy_dir_path",
+ &detected_list, &cnt),
CSR_ERROR_NONE);
// no malware detected
csr_cs_detected_list_h ignored_list;
size_t cnt = 0;
- ASSERT_IF(csr_cs_get_ignored_malwares(context, "dummy_dir_path", &ignored_list, &cnt),
+ ASSERT_IF(csr_cs_get_ignored_malwares(context, "dummy_dir_path", &ignored_list,
+ &cnt),
CSR_ERROR_NONE);
CHECK_IS_NOT_NULL(ignored_list);
CSR_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
- ASSERT_IF(csr_cs_judge_detected_malware(context, detected, CSR_CS_ACTION_REMOVE),
+ ASSERT_IF(csr_cs_judge_detected_malware(context, detected,
+ CSR_CS_ACTION_REMOVE),
CSR_ERROR_NONE);
EXCEPTION_GUARD_END
namespace {
inline void checkDetected(csre_cs_detected_h detected,
- csre_cs_severity_level_e expected_severity,
- csre_cs_threat_type_e expected_threat_type,
- const char *expected_malware_name,
- const char *expected_detailed_url,
- long expected_timestamp)
+ csre_cs_severity_level_e expected_severity,
+ csre_cs_threat_type_e expected_threat_type,
+ const char *expected_malware_name,
+ const char *expected_detailed_url,
+ long expected_timestamp)
{
EXCEPTION_GUARD_START
csre_cs_severity_level_e severity;
ASSERT_IF(csre_cs_detected_get_severity(detected, &severity), CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(severity == expected_severity,
- "severity isn't expected value. "
- "val: " << severity << " expected: " << expected_severity);
+ "severity isn't expected value. "
+ "val: " << severity << " expected: " << expected_severity);
csre_cs_threat_type_e threat_type;
- ASSERT_IF(csre_cs_detected_get_threat_type(detected, &threat_type), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_detected_get_threat_type(detected, &threat_type),
+ CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(threat_type == expected_threat_type,
- "threat type isn't expected value. "
- "val: " << threat_type << " expected: " << expected_threat_type);
+ "threat type isn't expected value. "
+ "val: " << threat_type << " expected: " << expected_threat_type);
const char *malware_name = nullptr;
- ASSERT_IF(csre_cs_detected_get_malware_name(detected, &malware_name), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_detected_get_malware_name(detected, &malware_name),
+ CSRE_ERROR_NONE);
if (expected_malware_name != nullptr) {
CHECK_IS_NOT_NULL(malware_name);
BOOST_REQUIRE_MESSAGE(
(strlen(malware_name) == strlen(expected_malware_name) &&
- memcmp(malware_name, expected_malware_name, strlen(malware_name)) == 0),
+ memcmp(malware_name, expected_malware_name, strlen(malware_name)) == 0),
"malware_name isn't expected value. "
- "val: " << malware_name << " expected: " << expected_malware_name);
+ "val: " << malware_name << " expected: " << expected_malware_name);
}
const char *detailed_url = nullptr;
- ASSERT_IF(csre_cs_detected_get_detailed_url(detected, &detailed_url), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_detected_get_detailed_url(detected, &detailed_url),
+ CSRE_ERROR_NONE);
if (expected_detailed_url != nullptr) {
CHECK_IS_NOT_NULL(detailed_url);
BOOST_REQUIRE_MESSAGE(
(strlen(detailed_url) == strlen(expected_detailed_url) &&
- memcmp(detailed_url, expected_detailed_url, strlen(detailed_url)) == 0),
+ memcmp(detailed_url, expected_detailed_url, strlen(detailed_url)) == 0),
"detailed_url isn't expected value. "
- "val: " << detailed_url << " expected: " << expected_detailed_url);
-
+ "val: " << detailed_url << " expected: " << expected_detailed_url);
}
long timestamp;
- ASSERT_IF(csre_cs_detected_get_timestamp(detected, ×tamp), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_detected_get_timestamp(detected, ×tamp),
+ CSRE_ERROR_NONE);
if (expected_timestamp != 0)
BOOST_REQUIRE_MESSAGE(timestamp == expected_timestamp,
- "timestamp isn't expected value. "
- "val: " << timestamp << " expected: " << expected_timestamp);
+ "timestamp isn't expected value. "
+ "val: " << timestamp << " expected: " << expected_timestamp);
EXCEPTION_GUARD_END
}
auto c = Test::Context<csre_cs_context_h>();
auto context = c.get();
- const char *data = "abcd1234dfdfdf334dfdi8ffndsfdfdsfdasfagdfvdfdfafadfasdfsdfe";
+ const char *data =
+ "abcd1234dfdfdf334dfdi8ffndsfdfdsfdasfagdfvdfdfafadfasdfsdfe";
csre_cs_detected_h detected;
ASSERT_IF(csre_cs_scan_data(
- context,
- reinterpret_cast<const unsigned char *>(data),
- strlen(data),
- &detected), CSRE_ERROR_NONE);
+ context,
+ reinterpret_cast<const unsigned char *>(data),
+ strlen(data),
+ &detected), CSRE_ERROR_NONE);
CHECK_IS_NULL(detected);
csre_cs_detected_h detected;
ASSERT_IF(csre_cs_scan_data(
- context,
- reinterpret_cast<const unsigned char *>(data),
- strlen(data),
- &detected), CSRE_ERROR_NONE);
+ context,
+ reinterpret_cast<const unsigned char *>(data),
+ strlen(data),
+ &detected), CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
checkDetected(detected,
- CSRE_CS_SEVERITY_HIGH,
- CSRE_CS_THREAT_MALWARE,
- "test_malware",
- "http://high.malware.com",
- 0);
+ CSRE_CS_SEVERITY_HIGH,
+ CSRE_CS_THREAT_MALWARE,
+ "test_malware",
+ "http://high.malware.com",
+ 0);
EXCEPTION_GUARD_END
}
csre_cs_detected_h detected;
ASSERT_IF(csre_cs_scan_data(
- context,
- reinterpret_cast<const unsigned char *>(data),
- strlen(data),
- &detected), CSRE_ERROR_NONE);
+ context,
+ reinterpret_cast<const unsigned char *>(data),
+ strlen(data),
+ &detected), CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
checkDetected(detected,
- CSRE_CS_SEVERITY_MEDIUM,
- CSRE_CS_THREAT_RISKY,
- "test_risk",
- nullptr,
- 0);
+ CSRE_CS_SEVERITY_MEDIUM,
+ CSRE_CS_THREAT_RISKY,
+ "test_risk",
+ nullptr,
+ 0);
EXCEPTION_GUARD_END
}
auto context = c.get();
csre_cs_detected_h detected;
- ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_NORMAL, &detected), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_NORMAL, &detected),
+ CSRE_ERROR_NONE);
CHECK_IS_NULL(detected);
auto context = c.get();
csre_cs_detected_h detected;
- ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_MALWARE, &detected), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_MALWARE, &detected),
+ CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
checkDetected(detected,
- CSRE_CS_SEVERITY_HIGH,
- CSRE_CS_THREAT_MALWARE,
- "test_malware",
- "http://high.malware.com",
- 0);
+ CSRE_CS_SEVERITY_HIGH,
+ CSRE_CS_THREAT_MALWARE,
+ "test_malware",
+ "http://high.malware.com",
+ 0);
EXCEPTION_GUARD_END
}
auto context = c.get();
csre_cs_detected_h detected;
- ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_RISKY, &detected), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_scan_file(context, TEST_FILE_RISKY, &detected),
+ CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
checkDetected(detected,
- CSRE_CS_SEVERITY_MEDIUM,
- CSRE_CS_THREAT_RISKY,
- "test_risk",
- "http://medium.malware.com",
- 0);
+ CSRE_CS_SEVERITY_MEDIUM,
+ CSRE_CS_THREAT_RISKY,
+ "test_risk",
+ "http://medium.malware.com",
+ 0);
EXCEPTION_GUARD_END
}
auto context = c.get();
csre_cs_detected_h detected;
- ASSERT_IF(csre_cs_scan_app_on_cloud(context, TEST_APP_ROOT,&detected), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_scan_app_on_cloud(context, TEST_APP_ROOT, &detected),
+ CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(detected);
checkDetected(detected,
- CSRE_CS_SEVERITY_HIGH,
- CSRE_CS_THREAT_MALWARE,
- "test_malware",
- "http://high.malware.com",
- 0);
+ CSRE_CS_SEVERITY_HIGH,
+ CSRE_CS_THREAT_MALWARE,
+ "test_malware",
+ "http://high.malware.com",
+ 0);
EXCEPTION_GUARD_END
}
const char *string = nullptr;
- ASSERT_IF(csre_cs_get_error_string(CSRE_ERROR_UNKNOWN, &string), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_get_error_string(CSRE_ERROR_UNKNOWN, &string),
+ CSRE_ERROR_NONE);
CHECK_IS_NOT_NULL(string);
unsigned char *vendor_logo_image = nullptr;
unsigned int size = 0;
- ASSERT_IF(csre_cs_engine_get_vendor_logo(handle, &vendor_logo_image, &size), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_engine_get_vendor_logo(handle, &vendor_logo_image, &size),
+ CSRE_ERROR_NONE);
EXCEPTION_GUARD_END
}
auto handle = c.get();
time_t time = 0;
- ASSERT_IF(csre_cs_engine_get_latest_update_time(handle, &time), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_cs_engine_get_latest_update_time(handle, &time),
+ CSRE_ERROR_NONE);
struct tm t;
BOOST_MESSAGE(asctime(gmtime_r(&time, &t)));
csre_wp_risk_level_e risk_level;
std::string detailed_url;
- Result(csre_wp_risk_level_e r, const char* durl) : risk_level(r), detailed_url(durl) {}
+ Result(csre_wp_risk_level_e r, const char *durl) : risk_level(r),
+ detailed_url(durl) {}
};
std::unordered_map<std::string, Result> ExpectedResult = {
{"http://lowrisky.test.com", Result(CSRE_WP_RISK_LOW, "")}
};
-inline void checkResult(const std::string &url, csre_wp_check_result_h &result, const Result &expected)
+inline void checkResult(const std::string &url, csre_wp_check_result_h &result,
+ const Result &expected)
{
EXCEPTION_GUARD_START
csre_wp_risk_level_e risk_level;
ASSERT_IF(csre_wp_result_get_risk_level(result, &risk_level), CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(risk_level == expected.risk_level,
- "url[" << url << "] risk level isn't expected value. "
- "val: " << risk_level << " expected: " << expected.risk_level);
+ "url[" << url << "] risk level isn't expected value. "
+ "val: " << risk_level << " expected: " << expected.risk_level);
const char *detailed_url = nullptr;
- ASSERT_IF(csre_wp_result_get_detailed_url(result, &detailed_url), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_wp_result_get_detailed_url(result, &detailed_url),
+ CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(expected.detailed_url.compare(detailed_url) == 0,
- "url[" << url << "] detailed url isn't expected value. "
- "val: " << detailed_url <<" expected: " << expected.detailed_url);
+ "url[" << url << "] detailed url isn't expected value. "
+ "val: " << detailed_url << " expected: " << expected.detailed_url);
EXCEPTION_GUARD_END
}
for (const auto &pair : ExpectedResult) {
csre_wp_check_result_h result;
- ASSERT_IF(csre_wp_check_url(context, pair.first.c_str(), &result), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_wp_check_url(context, pair.first.c_str(), &result),
+ CSRE_ERROR_NONE);
checkResult(pair.first, result, pair.second);
}
unsigned char *vendor_logo_image = nullptr;
unsigned int size = 0;
ASSERT_IF(csre_wp_engine_get_vendor_logo(handle, &vendor_logo_image, &size),
- CSRE_ERROR_NONE);
+ CSRE_ERROR_NONE);
EXCEPTION_GUARD_END
}
auto handle = c.get();
time_t time = 0;
- ASSERT_IF(csre_wp_engine_get_latest_update_time(handle, &time), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_wp_engine_get_latest_update_time(handle, &time),
+ CSRE_ERROR_NONE);
struct tm t;
BOOST_MESSAGE(asctime(gmtime_r(&time, &t)));
namespace Test {
template <typename T, typename U>
-void _assert(const T &value, const U &expected, const std::string &filename, const std::string &funcname, unsigned int line)
+void _assert(const T &value, const U &expected, const std::string &filename,
+ const std::string &funcname, unsigned int line)
{
BOOST_REQUIRE_MESSAGE(value == expected,
- "[" << filename << " > " << funcname << " : " << line << "]"
- << " returned code: " << value
- << " expected: " << expected);
+ "[" << filename << " > " << funcname << " : " << line << "]"
+ << " returned code: " << value
+ << " expected: " << expected);
}
void exceptionGuard(const std::function<void()> &);
Context() : m_context(nullptr)
{
BOOST_REQUIRE_MESSAGE(0, "Type[" << typeid(T).name()
- << "] isn't specialized for context template");
+ << "] isn't specialized for context template");
}
virtual ~Context()
{
BOOST_REQUIRE_MESSAGE(0, "Type[" << typeid(T).name()
- << "] isn't specialized for context template");
+ << "] isn't specialized for context template");
}
T get(void) const
{
BOOST_REQUIRE_MESSAGE(0, "Type[" << typeid(T).name()
- << "] isn't specialized for context template");
+ << "] isn't specialized for context template");
return nullptr;
}
memcmp(detailed_url, expected_detailed_url, strlen(detailed_url)) == 0),
"detailed_url isn't expected value. "
"val: " << detailed_url << " expected: " << expected_detailed_url);
-
}
long timestamp;
* @version 1.0
* @brief CSR Content screening DB internal test
*/
-
#include "service/core-usage.h"
+
#include <iostream>
#include <fstream>
#include <string>
-
#include <boost/test/unit_test.hpp>
+#include "test-common.h"
BOOST_AUTO_TEST_SUITE(INTERNAL_CORE_USAGE)
BOOST_AUTO_TEST_CASE(set_core_usage)
{
- Csr::CpuUsageManager *inst = Csr::CpuUsageManager::getInstance();
+ EXCEPTION_GUARD_START
+
+ auto inst = Csr::CpuUsageManager::getInstance();
int total = inst->getCoreCnt();
- inst->setThreadCoreUsage(Csr::USAGE_SINGLE);
- BOOST_REQUIRE_MESSAGE(total == inst->getCoreCnt(),
- "Failed. setThreadCoreUsage. Total=" << inst->getCoreCnt() << ", expectd=" << total);
- BOOST_REQUIRE_MESSAGE((1 * 100) / total == inst->getCoreUsage(),
- "Failed. setThreadCoreUsage. Usage=" << inst->getCoreUsage() << ", expectd=" << (1 * 100) / total);
+ ASSERT_IF(inst->setThreadCoreUsage(Csr::USAGE_SINGLE), true);
+ ASSERT_IF(total, inst->getCoreCnt());
+ ASSERT_IF((1 * 100) / total, inst->getCoreUsage());
+
+ ASSERT_IF(inst->setThreadCoreUsage(Csr::USAGE_HALF), true);
+ ASSERT_IF(total, inst->getCoreCnt());
+ ASSERT_IF(((total > 1) ? (total / 2) : 1) * 100 / total, inst->getCoreUsage());
- inst->setThreadCoreUsage(Csr::USAGE_HALF);
- BOOST_REQUIRE_MESSAGE(total == inst->getCoreCnt(),
- "Failed. setThreadCoreUsage. Total=" << inst->getCoreCnt() << ", expectd=" << total);
- BOOST_REQUIRE_MESSAGE(((total > 1) ? total / 2 : 1) * 100 / total == inst->getCoreUsage(),
- "Failed. setThreadCoreUsage. Usage=" << inst->getCoreUsage()
- << ", expectd=" << ((total > 1) ? total / 2 : 1) * 100 / total);
+ ASSERT_IF(inst->setThreadCoreUsage(Csr::USAGE_FULL), true);
+ ASSERT_IF(total, inst->getCoreCnt());
+ ASSERT_IF(100, inst->getCoreUsage());
- inst->setThreadCoreUsage(Csr::USAGE_FULL);
- BOOST_REQUIRE_MESSAGE(total == inst->getCoreCnt(),
- "Failed. setThreadCoreUsage. Total=" << inst->getCoreCnt() << ", expectd=" << total);
- BOOST_REQUIRE_MESSAGE(100 == inst->getCoreUsage(),
- "Failed. setThreadCoreUsage. Usage=" << inst->getCoreUsage() << ", expectd=" << 100);
+ ASSERT_IF(inst->setThreadCoreUsage(Csr::USAGE_DEFAULT), true);
+ ASSERT_IF(total, inst->getCoreCnt());
+ ASSERT_IF(100, inst->getCoreUsage());
- inst->setThreadCoreUsage(Csr::USAGE_DEFAULT);
- BOOST_REQUIRE_MESSAGE(total == inst->getCoreCnt(),
- "Failed. setThreadCoreUsage. Total=" << inst->getCoreCnt() << ", expectd=" << total);
- BOOST_REQUIRE_MESSAGE(100 == inst->getCoreUsage(),
- "Failed. setThreadCoreUsage. Usage=" << inst->getCoreUsage() << ", expectd=" << 100);
+ EXCEPTION_GUARD_END
}
BOOST_AUTO_TEST_SUITE_END()
(void) data;
installed = false;
+
if (key && strncmp(key, "end", strlen("end")) == 0) {
if (strncmp(val, "ok", strlen("ok")) == 0) {
installed = true;
g_main_loop_unref(mainLoop);
}
}
+
return 0;
}
return TRUE;
}
-void __assertFile(const Csr::File &file, const std::string &path, const std::string &user,
+void __assertFile(const Csr::File &file, const std::string &path,
+ const std::string &user,
const std::string &pkgId, const std::string &pkgPath, bool inApp)
{
- BOOST_REQUIRE_MESSAGE(file.getPath() == path,
- "expected=" << path << ",actual=" << file.getPath());
- BOOST_REQUIRE_MESSAGE(file.getAppUser() == user,
- "expected=" << user << ",actual=" << file.getAppUser());
- BOOST_REQUIRE_MESSAGE(file.getAppPkgId() == pkgId,
- "expected=" << pkgId << ",actual=" << file.getAppPkgId());
- BOOST_REQUIRE_MESSAGE(file.getAppPkgPath() == pkgPath,
- "expected=" << pkgPath << ",actual=" << file.getAppPkgPath());
- BOOST_REQUIRE_MESSAGE(file.isInApp() == inApp,
- "expected=" << ((inApp) ? "APP" : "FILE") << ",actual=" << ((file.isInApp()) ? "APP" : "FILE"));
+ ASSERT_IF(file.getPath(), path);
+ ASSERT_IF(file.getAppUser(), user);
+ ASSERT_IF(file.getAppPkgId(), pkgId);
+ ASSERT_IF(file.getAppPkgPath(), pkgPath);
+ ASSERT_IF(file.isInApp(), inApp);
}
void __createFile(const std::string &path)
void __writeFile(const std::string &path)
{
auto fp = fopen(path.c_str(), "w");
- BOOST_REQUIRE(fp != nullptr);
+ CHECK_IS_NOT_NULL(fp);
char buffer[] = { 't', 'e', 's', 't' };
fwrite(buffer , sizeof(char), sizeof(buffer), fp);
fclose(fp);
{
std::string path1("/sdcard/text.txt");
Csr::File file1(path1);
- __assertFile(file1, path1, "", "", "", false);
+ __assertFile(file1, path1, std::string(), std::string(), std::string(), false);
std::string path2("/usr/apps1/testpkg/test.txt");
Csr::File file2(path2);
- __assertFile(file2, path2, "", "", "", false);
+ __assertFile(file2, path2, std::string(), std::string(), std::string(), false);
std::string path3("/opt/usr/apps1/testpkg/test.txt");
Csr::File file3(path3);
- __assertFile(file3, path3, "", "", "", false);
+ __assertFile(file3, path3, std::string(), std::string(), std::string(), false);
std::string path4("/sdcard1/apps/testpkg/test.txt");
Csr::File file4(path4);
- __assertFile(file4, path4, "", "", "", false);
+ __assertFile(file4, path4, std::string(), std::string(), std::string(), false);
std::string pkgid("testpkg");
std::string appPath1("/usr/apps/" + pkgid);
std::string appFilePath1(appPath1 + "/test.txt");
Csr::File app1(appFilePath1);
- __assertFile(app1, appFilePath1, "", pkgid, appPath1, true);
+ __assertFile(app1, appFilePath1, std::string(), pkgid, appPath1, true);
std::string appPath2("/opt/usr/apps/" + pkgid);
std::string appFilePath2(appPath2 + "/test.txt");
Csr::File app2(appFilePath2);
- __assertFile(app2, appFilePath2, "", pkgid, appPath2, true);
+ __assertFile(app2, appFilePath2, std::string(), pkgid, appPath2, true);
std::string appPath3("/sdcard/apps/" + pkgid);
std::string appFilePath3(appPath3 + "/test.txt");
Csr::File app3(appFilePath3);
- __assertFile(app3, appFilePath3, "", pkgid, appPath3, true);
+ __assertFile(app3, appFilePath3, std::string(), pkgid, appPath3, true);
std::string appPath4("/sdcard/app2sd/" + pkgid);
std::string appFilePath4(appPath4 + "/test.txt");
Csr::File app4(appFilePath4);
- __assertFile(app4, appFilePath4, "", pkgid, appPath4, true);
+ __assertFile(app4, appFilePath4, std::string(), pkgid, appPath4, true);
}
BOOST_AUTO_TEST_CASE(remove_file)
BOOST_AUTO_TEST_CASE(remove_app)
{
- std::string fpath = "/opt/usr/apps/org.example.maliciousapp/shared/res/malicious.txt";
+ std::string fpath =
+ "/opt/usr/apps/org.example.maliciousapp/shared/res/malicious.txt";
std::string appPath = TEST_APP_PKG;
// install the test app
auto pkgmgr = pkgmgr_client_new(PC_REQUEST);
- BOOST_REQUIRE(pkgmgr != nullptr);
+ CHECK_IS_NOT_NULL(pkgmgr);
int ret = pkgmgr_client_install(pkgmgr, nullptr, nullptr,
- appPath.c_str(), nullptr, PM_QUIET, ::__app_install_cb, nullptr);
- BOOST_REQUIRE_MESSAGE(ret > PKGMGR_R_OK, std::string("expected>") << PKGMGR_R_OK << ", actual=" << ret);
+ appPath.c_str(), nullptr, PM_QUIET, ::__app_install_cb, nullptr);
+ BOOST_REQUIRE_MESSAGE(ret > PKGMGR_R_OK,
+ std::string("expected>") << PKGMGR_R_OK << ", actual=" << ret);
g_timeout_add_seconds(30, __app_uninstall_timeout, this);
mainLoop = g_main_loop_new(nullptr, false);
g_main_loop_run(mainLoop);
pkgmgr_client_free(pkgmgr);
- BOOST_REQUIRE_MESSAGE(installed == true, "fail to install test app");
+ BOOST_REQUIRE_MESSAGE(installed, "fail to install test app");
// remove the app
Csr::File app(fpath);
CHECK_IS_NOT_NULL(visitor);
int cnt = 0;
+
while (visitor->next())
cnt++;
CHECK_IS_NOT_NULL(visitor);
int cnt = 0;
+
while (visitor->next())
cnt++;
CHECK_IS_NOT_NULL(visitor);
int cnt = 0;
+
while (visitor->next())
cnt++;
CHECK_IS_NOT_NULL(visitor);
int cnt = 0;
+
while (visitor->next())
cnt++;
struct TestConfig {
TestConfig()
{
- boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_test_units);
+ 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 Csr::Test::colour_log_formatter);
+ boost::unit_test::unit_test_log.set_formatter(new
+ Csr::Test::colour_log_formatter);
}
};
{
if (!isEngineInitialized) {
int ret = csre_cs_global_initialize(
- SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
+ SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
if (ret != CSRE_ERROR_NONE)
throw std::logic_error("Failed to init content screening engine.");
ret = csre_wp_global_initialize(
- SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
+ SAMPLE_ENGINE_RO_RES_DIR, SAMPLE_ENGINE_RW_WORKING_DIR);
if (ret != CSRE_ERROR_NONE)
throw std::logic_error("Failed to init web protection engine.");
return;
int ret = csre_cs_global_deinitialize();
+
if (ret != CSRE_ERROR_NONE)
throw std::logic_error("Failed to deinit content screening engine.");
ret = csre_wp_global_deinitialize();
+
if (ret != CSRE_ERROR_NONE)
throw std::logic_error("Failed to deinit web protection engine.");
csre_wp_risk_level_e risk_level;
std::string detailed_url;
- Result(csre_wp_risk_level_e r, const char* durl) : risk_level(r), detailed_url(durl) {}
+ Result(csre_wp_risk_level_e r, const char *durl) : risk_level(r),
+ detailed_url(durl) {}
};
std::unordered_map<std::string, Result> ExpectedResult = {
{"http://lowrisky.test.com", Result(CSRE_WP_RISK_LOW, "")}
};
-inline void checkResult(const std::string &url, csre_wp_check_result_h &result, const Result &expected)
+inline void checkResult(const std::string &url, csre_wp_check_result_h &result,
+ const Result &expected)
{
EXCEPTION_GUARD_START
csre_wp_risk_level_e risk_level;
ASSERT_IF(csre_wp_result_get_risk_level(result, &risk_level), CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(risk_level == expected.risk_level,
- "url[" << url << "] risk level isn't expected value. "
- "val: " << risk_level << " expected: " << expected.risk_level);
+ "url[" << url << "] risk level isn't expected value. "
+ "val: " << risk_level << " expected: " << expected.risk_level);
const char *detailed_url = nullptr;
- ASSERT_IF(csre_wp_result_get_detailed_url(result, &detailed_url), CSRE_ERROR_NONE);
+ ASSERT_IF(csre_wp_result_get_detailed_url(result, &detailed_url),
+ CSRE_ERROR_NONE);
BOOST_REQUIRE_MESSAGE(expected.detailed_url.compare(detailed_url) == 0,
- "url[" << url << "] detailed url isn't expected value. "
- "val: " << detailed_url <<" expected: " << expected.detailed_url);
+ "url[" << url << "] detailed url isn't expected value. "
+ "val: " << detailed_url << " expected: " << expected.detailed_url);
EXCEPTION_GUARD_END
for (const auto &pair : ExpectedResult) {
csre_wp_check_result_h result;
- ASSERT_IF(h.loader.checkUrl(h.context, pair.first.c_str(), &result), CSRE_ERROR_NONE);
+ ASSERT_IF(h.loader.checkUrl(h.context, pair.first.c_str(), &result),
+ CSRE_ERROR_NONE);
checkResult(pair.first, result, pair.second);
}
struct TestConfig {
TestConfig()
{
- boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_test_units);
+ 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 Csr::Test::colour_log_formatter);
+ boost::unit_test::unit_test_log.set_formatter(new
+ Csr::Test::colour_log_formatter);
}
};
namespace {
-auto exceptionGuard = [&](std::function<void()> &&func) {
+auto exceptionGuard = [&](std::function<void()> && func)
+{
try {
func();
} catch (...) {
inline long long int END_TIME(void)
{
- return duration_cast<milliseconds>(high_resolution_clock::now() - _start).count();
+ return duration_cast<milliseconds>(high_resolution_clock::now() -
+ _start).count();
}
inline void INC_EXPECTED_TIME(long long int t)
std::lock_guard<std::mutex> l(_m);
BOOST_MESSAGE("Elapsed time[" << END_TIME() << "]. "
- "Expected scope: (" << _expected << ", " << _expected + PoolLogicUnit << ")");
+ "Expected scope: (" << _expected << ", " << _expected + PoolLogicUnit << ")");
- BOOST_REQUIRE_MESSAGE(END_TIME() < _expected + PoolLogicUnit, "Too much time elapsed");
+ BOOST_REQUIRE_MESSAGE(END_TIME() < _expected + PoolLogicUnit,
+ "Too much time elapsed");
BOOST_REQUIRE_MESSAGE(END_TIME() >= _expected, "Too less time elapsed");
}
Csr::ThreadPool pool(cnt, cnt);
BOOST_REQUIRE_MESSAGE(pool.size() == cnt,
- "Thread pool isn't initialized well. "
- "Pool size[" << pool.size() << "] and correct size[" << cnt << "]");
+ "Thread pool isn't initialized well. "
+ "Pool size[" << pool.size() << "] and correct size[" << cnt << "]");
for (size_t i = 0; i < cnt; i++)
pool.submit(task);
Csr::ThreadPool pool(min, max);
BOOST_REQUIRE_MESSAGE(pool.size() == min,
- "Thread pool isn't initialized well. "
- "Pool size[" << pool.size() << "] and corret min size[" << min << "]");
+ "Thread pool isn't initialized well. "
+ "Pool size[" << pool.size() << "] and corret min size[" << min << "]");
// Task assigned to already existing workers
for (size_t i = 0; i < min; i++)
INC_EXPECTED_TIME(PoolLogicUnit);
std::this_thread::sleep_for(milliseconds(TaskSleepUnit + PoolLogicUnit));
BOOST_REQUIRE_MESSAGE(pool.size() == min,
- "To dtor idle threads in pool doesn't work well. "
- "Pool size[" << pool.size() << "] shouldn't exceed given min[" << min << "]");
+ "To dtor idle threads in pool doesn't work well. "
+ "Pool size[" << pool.size() << "] shouldn't exceed given min[" << min << "]");
// make all(maximum) workers busy
INC_EXPECTED_TIME(TaskSleepUnit);
+
for (size_t i = 0; i < max; i++)
pool.submit(task);
INC_EXPECTED_TIME(TaskSleepUnit);
pool.submit(task); // One more task than maximum workers at the time
BOOST_REQUIRE_MESSAGE(pool.size() == max,
- "Upper bound to make thread dynamically to pool doesn't work well. "
- "Pool size[" << pool.size() << "] shouldn't exceed given max[" << max << "]");
+ "Upper bound to make thread dynamically to pool doesn't work well. "
+ "Pool size[" << pool.size() << "] shouldn't exceed given max[" << max << "]");
});
CHECK_TIME();