From 6cc9e146ee853e5d3a37659f46b5631ebc056245 Mon Sep 17 00:00:00 2001 From: Eduardo Arias Date: Mon, 3 Jun 2024 15:09:36 +0000 Subject: [PATCH] Use fmt to format strings --- headers/modsecurity/rules_set_properties.h | 1 - src/actions/accuracy.cc | 6 +- src/actions/ctl/audit_engine.cc | 13 +- src/actions/ctl/request_body_access.cc | 5 +- src/actions/ctl/rule_engine.cc | 5 +- src/actions/ctl/rule_remove_by_id.cc | 11 +- src/actions/ctl/rule_remove_target_by_id.cc | 7 +- src/actions/ctl/rule_remove_target_by_tag.cc | 3 +- src/actions/data/status.cc | 3 +- src/actions/disruptive/allow.cc | 7 +- src/actions/exec.cc | 7 +- src/actions/expire_var.cc | 3 +- src/actions/init_col.cc | 5 +- src/actions/maturity.cc | 6 +- src/actions/msg.cc | 3 +- src/actions/phase.cc | 4 +- src/actions/rule_id.cc | 12 +- src/actions/set_env.cc | 5 +- src/actions/set_rsc.cc | 5 +- src/actions/set_sid.cc | 5 +- src/actions/set_uid.cc | 5 +- src/actions/set_var.cc | 5 +- src/actions/severity.cc | 5 +- src/actions/skip.cc | 5 +- src/actions/skip_after.cc | 3 +- src/actions/tag.cc | 3 +- src/actions/xmlns.cc | 5 +- src/anchored_set_variable.cc | 9 +- src/audit_log/audit_log.cc | 10 +- src/debug_log/debug_log.cc | 11 +- src/engine/lua.cc | 28 +- src/modsecurity.cc | 9 +- src/operators/detect_sqli.cc | 14 +- src/operators/detect_xss.cc | 11 +- src/operators/fuzzy_hash.cc | 18 +- src/operators/inspect_file.cc | 10 +- src/operators/operator.cc | 30 +- src/operators/pm.cc | 5 +- src/operators/pm_from_file.cc | 3 +- src/operators/rbl.cc | 71 +-- src/operators/rx.cc | 9 +- src/operators/rx_global.cc | 7 +- src/operators/validate_byte_range.cc | 25 +- src/operators/validate_dtd.cc | 10 +- src/operators/validate_schema.cc | 7 +- src/operators/validate_url_encoding.cc | 16 +- src/operators/validate_utf8_encoding.cc | 39 +- src/operators/verify_cc.cc | 10 +- src/operators/verify_cpf.cc | 5 +- src/operators/verify_ssn.cc | 5 +- src/operators/verify_svnr.cc | 5 +- src/parser/driver.cc | 33 +- src/request_body_processor/json.cc | 7 +- src/request_body_processor/multipart.cc | 438 +++++++++---------- src/request_body_processor/xml.cc | 21 +- src/rule_message.cc | 71 ++- src/rule_script.cc | 5 +- src/rule_unconditional.cc | 7 +- src/rule_with_actions.cc | 43 +- src/rule_with_operator.cc | 50 +-- src/rules_exceptions.cc | 11 +- src/rules_set.cc | 44 +- src/rules_set_properties.cc | 13 +- src/transaction.cc | 120 ++--- src/utils/https_client.cc | 7 +- src/utils/ip_tree.cc | 3 +- src/utils/shared_files.cc | 9 +- src/utils/string.h | 13 +- src/utils/system.cc | 5 +- src/variables/variable.cc | 24 +- src/variables/variable.h | 19 +- 71 files changed, 722 insertions(+), 735 deletions(-) diff --git a/headers/modsecurity/rules_set_properties.h b/headers/modsecurity/rules_set_properties.h index 386a252d75..39f926ee1f 100644 --- a/headers/modsecurity/rules_set_properties.h +++ b/headers/modsecurity/rules_set_properties.h @@ -226,7 +226,6 @@ class RulesSetProperties { PropertyNotSetConfigBoolean }; - /** * * The RuleEngine enumerator consists in mapping the different states diff --git a/src/actions/accuracy.cc b/src/actions/accuracy.cc index ace9f1c5c4..031e445427 100644 --- a/src/actions/accuracy.cc +++ b/src/actions/accuracy.cc @@ -15,6 +15,8 @@ #include "src/actions/accuracy.h" +#include + #include "modsecurity/rule_with_actions.h" @@ -25,8 +27,8 @@ bool Accuracy::init(std::string *error) { try { m_accuracy = std::stoi(m_parser_payload); } catch (...) { - error->assign("Accuracy: The input \"" + m_parser_payload + "\" is " \ - "not a number."); + error->assign(fmt::format("Accuracy: The input \"{}\" is " \ + "not a number.", m_parser_payload)); return false; } return true; diff --git a/src/actions/ctl/audit_engine.cc b/src/actions/ctl/audit_engine.cc index d3d6650d3c..81c04e5a66 100644 --- a/src/actions/ctl/audit_engine.cc +++ b/src/actions/ctl/audit_engine.cc @@ -16,6 +16,7 @@ #include "src/actions/ctl/audit_engine.h" #include +#include #include "modsecurity/rules_set_properties.h" #include "modsecurity/rules_set.h" @@ -37,8 +38,8 @@ bool AuditEngine::init(std::string *error) { } else if (what == "relevantonly") { m_auditEngine = audit_log::AuditLog::AuditLogStatus::RelevantOnlyAuditLogStatus; } else { - error->assign("Internal error. Expected: On, Off or RelevantOnly; " \ - "got: " + m_parser_payload); + error->assign(fmt::format("Internal error. Expected: On, Off or RelevantOnly; " \ + "got: {}", m_parser_payload)); return false; } @@ -46,12 +47,8 @@ bool AuditEngine::init(std::string *error) { } bool AuditEngine::evaluate(RuleWithActions *rule, Transaction *transaction) { - std::stringstream a; - a << "Setting SecAuditEngine to "; - a << std::to_string(m_auditEngine); - a << " as requested by a ctl:auditEngine action"; - - ms_dbg_a(transaction, 8, a.str()); + ms_dbg_a(transaction, 8, fmt::format("Setting SecAuditEngine to {} " \ + " as requested by a ctl:auditEngine action", (int)m_auditEngine)); transaction->m_ctlAuditEngine = m_auditEngine; return true; diff --git a/src/actions/ctl/request_body_access.cc b/src/actions/ctl/request_body_access.cc index 0d3415551f..4e8e006cc0 100644 --- a/src/actions/ctl/request_body_access.cc +++ b/src/actions/ctl/request_body_access.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set_properties.h" #include "modsecurity/transaction.h" @@ -34,8 +35,8 @@ bool RequestBodyAccess::init(std::string *error) { } else if (what == "false") { m_request_body_access = false; } else { - error->assign("Internal error. Expected: true or false, got: " \ - + m_parser_payload); + error->assign(fmt::format("Internal error. Expected: true or false, got: {}", + m_parser_payload)); return false; } diff --git a/src/actions/ctl/rule_engine.cc b/src/actions/ctl/rule_engine.cc index 66809f4b1c..8738b0b355 100644 --- a/src/actions/ctl/rule_engine.cc +++ b/src/actions/ctl/rule_engine.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set_properties.h" #include "modsecurity/rules_set.h" @@ -37,8 +38,8 @@ bool RuleEngine::init(std::string *error) { } else if (what == "detectiononly") { m_ruleEngine = RulesSetProperties::DetectionOnlyRuleEngine; } else { - error->assign("Internal error. Expected: On, Off or DetectionOnly; " \ - "got: " + m_parser_payload); + error->assign(fmt::format("Internal error. Expected: On, Off or DetectionOnly; " \ + "got: {}", m_parser_payload)); return false; } diff --git a/src/actions/ctl/rule_remove_by_id.cc b/src/actions/ctl/rule_remove_by_id.cc index 869dc4f945..d35f297727 100644 --- a/src/actions/ctl/rule_remove_by_id.cc +++ b/src/actions/ctl/rule_remove_by_id.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/transaction.h" #include "src/utils/string.h" @@ -46,19 +47,19 @@ bool RuleRemoveById::init(std::string *error) { n1n = std::stoi(n1s); added = true; } catch (...) { - error->assign("Not a number: " + n1s); + error->assign(fmt::format("Not a number: {}", n1s)); return false; } try { n2n = std::stoi(n2s); added = true; } catch (...) { - error->assign("Not a number: " + n2s); + error->assign(fmt::format("Not a number: {}", n2s)); return false; } if (n1n > n2n) { - error->assign("Invalid range: " + b); + error->assign(fmt::format("Invalid range: {}", b)); return false; } m_ranges.push_back(std::make_pair(n1n, n2n)); @@ -69,7 +70,7 @@ bool RuleRemoveById::init(std::string *error) { m_ids.push_back(num); added = true; } catch (...) { - error->assign("Not a number or range: " + b); + error->assign(fmt::format("Not a number or range: {}", b)); return false; } } @@ -79,7 +80,7 @@ bool RuleRemoveById::init(std::string *error) { return true; } - error->assign("Not a number or range: " + what); + error->assign(fmt::format("Not a number or range: {}", what)); return false; } diff --git a/src/actions/ctl/rule_remove_target_by_id.cc b/src/actions/ctl/rule_remove_target_by_id.cc index 0776e34486..714db75d5e 100644 --- a/src/actions/ctl/rule_remove_target_by_id.cc +++ b/src/actions/ctl/rule_remove_target_by_id.cc @@ -19,6 +19,7 @@ #include #include #include +#include #include "modsecurity/transaction.h" #include "src/utils/string.h" @@ -34,15 +35,15 @@ bool RuleRemoveTargetById::init(std::string *error) { std::vector param = utils::string::split(what, ';'); if (param.size() < 2) { - error->assign(what + " is not a valid `ID;VARIABLE'"); + error->assign(fmt::format("{} is not a valid `ID;VARIABLE'", what)); return false; } try { m_id = std::stoi(param[0]); } catch(...) { - error->assign("Not able to convert '" + param[0] + - "' into a number"); + error->assign(fmt::format("Not able to convert '{}' into a number", + param[0])); return false; } diff --git a/src/actions/ctl/rule_remove_target_by_tag.cc b/src/actions/ctl/rule_remove_target_by_tag.cc index 1be6603fd8..261261cee7 100644 --- a/src/actions/ctl/rule_remove_target_by_tag.cc +++ b/src/actions/ctl/rule_remove_target_by_tag.cc @@ -19,6 +19,7 @@ #include #include #include +#include #include "modsecurity/transaction.h" #include "src/utils/string.h" @@ -34,7 +35,7 @@ bool RuleRemoveTargetByTag::init(std::string *error) { std::vector param = utils::string::split(what, ';'); if (param.size() < 2) { - error->assign(what + " is not a valid `TAG;VARIABLE'"); + error->assign(fmt::format("{} is not a valid `TAG;VARIABLE'", what)); return false; } diff --git a/src/actions/data/status.cc b/src/actions/data/status.cc index ed9cd0ed6e..b9e0b6c985 100644 --- a/src/actions/data/status.cc +++ b/src/actions/data/status.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/transaction.h" @@ -30,7 +31,7 @@ bool Status::init(std::string *error) { try { m_status = std::stoi(m_parser_payload); } catch (...) { - error->assign("Not a valid number: " + m_parser_payload); + error->assign(fmt::format("Not a valid number: {}", m_parser_payload)); return false; } diff --git a/src/actions/disruptive/allow.cc b/src/actions/disruptive/allow.cc index 59e17374a1..209584256f 100644 --- a/src/actions/disruptive/allow.cc +++ b/src/actions/disruptive/allow.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/transaction.h" @@ -50,9 +51,9 @@ bool Allow::init(std::string *error) { bool Allow::evaluate(RuleWithActions *rule, Transaction *transaction) { - ms_dbg_a(transaction, 4, "Dropping the evaluation of upcoming rules " \ - "in favor of an `allow' action of type: " \ - + allowTypeToName(m_allowType)); + ms_dbg_a(transaction, 4, fmt::format("Dropping the evaluation of upcoming rules " \ + "in favor of an `allow' action of type: {}", + allowTypeToName(m_allowType))); transaction->m_allowType = m_allowType; diff --git a/src/actions/exec.cc b/src/actions/exec.cc index 8ed21d73ea..b93f803a01 100644 --- a/src/actions/exec.cc +++ b/src/actions/exec.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/actions/action.h" @@ -36,12 +37,12 @@ bool Exec::init(std::string *error) { m_script = utils::find_resource(m_parser_payload, "", &err); if (m_script.size() == 0) { - error->assign("exec: Script not found: " + err); + error->assign(fmt::format("exec: Script not found: {}", err)); return false; } if (engine::Lua::isCompatible(m_script, &m_lua, &err) == false) { - error->assign("exec: " + err); + error->assign(fmt::format("exec: {}", err)); return false; } @@ -50,7 +51,7 @@ bool Exec::init(std::string *error) { bool Exec::evaluate(RuleWithActions *rule, Transaction *t) { - ms_dbg_a(t, 8, "Running script... " + m_script); + ms_dbg_a(t, 8, fmt::format("Running script... {}", m_script)); m_lua.run(t); return true; } diff --git a/src/actions/expire_var.cc b/src/actions/expire_var.cc index ffc89f4779..d1ec6f258c 100644 --- a/src/actions/expire_var.cc +++ b/src/actions/expire_var.cc @@ -16,6 +16,7 @@ #include "src/actions/expire_var.h" #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/transaction.h" @@ -81,7 +82,7 @@ bool ExpireVar::evaluate(RuleWithActions *rule, Transaction *t) { } else { ms_dbg_a(t, 5, "Invalid collection found in expirevar expression: collection must be `ip', `global', `resource', `user' or `session'"); } - ms_dbg_a(t, 9, "Setting variable `" + variable_name + "' to expire in " + std::to_string(expirySeconds) + " seconds."); + ms_dbg_a(t, 9, fmt::format("Setting variable `{}' to expire in {} seconds.", variable_name, expirySeconds)); return true; } diff --git a/src/actions/init_col.cc b/src/actions/init_col.cc index 0c6fafe95f..7aff99c68c 100644 --- a/src/actions/init_col.cc +++ b/src/actions/init_col.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/actions/action.h" #include "modsecurity/transaction.h" @@ -67,8 +68,8 @@ bool InitCol::evaluate(RuleWithActions *rule, Transaction *t) { return false; } - ms_dbg_a(t, 5, "Collection `" + m_collection_key + "' initialized with " \ - "value: " + collectionName); + ms_dbg_a(t, 5, fmt::format("Collection `{}' initialized with " \ + "value: {}", m_collection_key, collectionName)); return true; } diff --git a/src/actions/maturity.cc b/src/actions/maturity.cc index fca6aaa4aa..15f988a5e8 100644 --- a/src/actions/maturity.cc +++ b/src/actions/maturity.cc @@ -15,6 +15,8 @@ #include "src/actions/maturity.h" +#include + #include "modsecurity/rule_with_actions.h" @@ -25,8 +27,8 @@ bool Maturity::init(std::string *error) { try { m_maturity = std::stoi(m_parser_payload); } catch (...) { - error->assign("Maturity: The input \"" + m_parser_payload + "\" is " \ - "not a number."); + error->assign(fmt::format("Maturity: The input \"{}\" is " \ + "not a number.", m_parser_payload)); return false; } return true; diff --git a/src/actions/msg.cc b/src/actions/msg.cc index fecab53858..97bb0dc3fc 100644 --- a/src/actions/msg.cc +++ b/src/actions/msg.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/actions/action.h" #include "modsecurity/transaction.h" @@ -49,7 +50,7 @@ namespace actions { bool Msg::evaluate(RuleWithActions *rule, Transaction *transaction, RuleMessage &ruleMessage) { const auto msg = data(transaction); ruleMessage.m_message = msg; - ms_dbg_a(transaction, 9, "Saving msg: " + msg); + ms_dbg_a(transaction, 9, fmt::format("Saving msg: {}", msg)); return true; } diff --git a/src/actions/phase.cc b/src/actions/phase.cc index 1d17ec33c8..bcb94b2eaf 100644 --- a/src/actions/phase.cc +++ b/src/actions/phase.cc @@ -15,6 +15,8 @@ #include "src/actions/phase.h" +#include + #include "modsecurity/rule_with_actions.h" #include "src/utils/string.h" @@ -47,7 +49,7 @@ bool Phase::init(std::string *error) { m_phase = modsecurity::Phases::LoggingPhase; m_secRulesPhase = 5; } else { - error->assign("Unknown phase: " + m_parser_payload); + error->assign(fmt::format("Unknown phase: {}", m_parser_payload)); return false; } } catch (...) { diff --git a/src/actions/rule_id.cc b/src/actions/rule_id.cc index c7864707b7..bdad94a301 100644 --- a/src/actions/rule_id.cc +++ b/src/actions/rule_id.cc @@ -15,6 +15,8 @@ #include "src/actions/rule_id.h" +#include + #include "modsecurity/rule_with_actions.h" @@ -22,22 +24,22 @@ namespace modsecurity::actions { bool RuleId::init(std::string *error) { - std::string a = m_parser_payload; + const auto &a = m_parser_payload; try { m_ruleId = std::stod(a); } catch (...) { m_ruleId = 0; - error->assign("The input \"" + a + "\" does not " \ - "seems to be a valid rule id."); + error->assign(fmt::format("The input \"{}\" does not " \ + "seems to be a valid rule id.", a)); return false; } std::ostringstream oss; oss << std::setprecision(40) << m_ruleId; if (a != oss.str() || m_ruleId < 0) { - error->assign("The input \"" + a + "\" does not seems " \ - "to be a valid rule id."); + error->assign(fmt::format("The input \"{}\" does not seems " \ + "to be a valid rule id.", a)); return false; } return true; diff --git a/src/actions/set_env.cc b/src/actions/set_env.cc index a14c0ad309..e9e7a6ba78 100644 --- a/src/actions/set_env.cc +++ b/src/actions/set_env.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/transaction.h" #include "modsecurity/rule.h" @@ -30,8 +31,8 @@ bool SetENV::evaluate(RuleWithActions *rule, Transaction *t) { std::string colNameExpanded(m_string->evaluate(t)); auto pair = utils::string::ssplit_pair(colNameExpanded, '='); - ms_dbg_a(t, 8, "Setting environment variable: " - + pair.first + " to " + pair.second); + ms_dbg_a(t, 8, fmt::format("Setting environment variable: {} to {}", + pair.first, pair.second)); #ifndef WIN32 setenv(pair.first.c_str(), pair.second.c_str(), /*overwrite*/ 1); #else diff --git a/src/actions/set_rsc.cc b/src/actions/set_rsc.cc index 5b31c0a163..4473c7494a 100644 --- a/src/actions/set_rsc.cc +++ b/src/actions/set_rsc.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/transaction.h" #include "modsecurity/rule.h" @@ -28,8 +29,8 @@ namespace actions { bool SetRSC::evaluate(RuleWithActions *rule, Transaction *t) { std::string colNameExpanded(m_string->evaluate(t)); - ms_dbg_a(t, 8, "RESOURCE initiated with value: \'" - + colNameExpanded + "\'."); + ms_dbg_a(t, 8, fmt::format("RESOURCE initiated with value: \'{}\'.", + colNameExpanded)); t->m_collections.m_resource_collection_key = colNameExpanded; t->m_variableResource.set(colNameExpanded, t->m_variableOffset); diff --git a/src/actions/set_sid.cc b/src/actions/set_sid.cc index 4117d35120..9223f45990 100644 --- a/src/actions/set_sid.cc +++ b/src/actions/set_sid.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/transaction.h" #include "modsecurity/rule.h" @@ -28,8 +29,8 @@ namespace actions { bool SetSID::evaluate(RuleWithActions *rule, Transaction *t) { std::string colNameExpanded(m_string->evaluate(t)); - ms_dbg_a(t, 8, "Session ID initiated with value: \'" - + colNameExpanded + "\'."); + ms_dbg_a(t, 8, fmt::format("Session ID initiated with value: \'{}\'.", + colNameExpanded)); t->m_collections.m_session_collection_key = colNameExpanded; t->m_variableSessionID.set(colNameExpanded, t->m_variableOffset); diff --git a/src/actions/set_uid.cc b/src/actions/set_uid.cc index 01f74b84b1..cf528789bb 100644 --- a/src/actions/set_uid.cc +++ b/src/actions/set_uid.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/transaction.h" #include "modsecurity/rule.h" @@ -28,8 +29,8 @@ namespace actions { bool SetUID::evaluate(RuleWithActions *rule, Transaction *t) { std::string colNameExpanded(m_string->evaluate(t)); - ms_dbg_a(t, 8, "User collection initiated with value: \'" - + colNameExpanded + "\'."); + ms_dbg_a(t, 8, fmt::format("User collection initiated with value: \'{}\'.", + colNameExpanded)); t->m_collections.m_user_collection_key = colNameExpanded; t->m_variableUserID.set(colNameExpanded, t->m_variableOffset); diff --git a/src/actions/set_var.cc b/src/actions/set_var.cc index 70c07d065d..c11cd9a847 100644 --- a/src/actions/set_var.cc +++ b/src/actions/set_var.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/transaction.h" @@ -122,8 +123,8 @@ bool SetVar::evaluate(RuleWithActions *rule, Transaction *t) { } } - ms_dbg_a(t, 8, "Saving variable: " + m_variable->m_collectionName \ - + ":" + m_variableNameExpanded + " with value: " + targetValue); + ms_dbg_a(t, 8, fmt::format("Saving variable: {}:{} with value: {}", + m_variable->m_collectionName, m_variableNameExpanded, targetValue)); if (tx) { tx->storeOrUpdateFirst(t, m_variableNameExpanded, targetValue); diff --git a/src/actions/severity.cc b/src/actions/severity.cc index 26c5056e71..c341e0f392 100644 --- a/src/actions/severity.cc +++ b/src/actions/severity.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/actions/action.h" @@ -62,8 +63,8 @@ bool Severity::init(std::string *error) { m_severity = std::stoi(a); return true; } catch (...) { - error->assign("Severity: The input \"" + a + "\" is " \ - "not a number."); + error->assign(fmt::format("Severity: The input \"{}\" is " \ + "not a number.", a)); } } diff --git a/src/actions/skip.cc b/src/actions/skip.cc index fd2abfe219..26c3f9eae6 100644 --- a/src/actions/skip.cc +++ b/src/actions/skip.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/actions/action.h" @@ -30,8 +31,8 @@ bool Skip::init(std::string *error) { try { m_skip_next = std::stoi(m_parser_payload); } catch (...) { - error->assign("Skip: The input \"" + m_parser_payload + "\" is " \ - "not a number."); + error->assign(fmt::format("Skip: The input \"{}\" is " \ + "not a number.", m_parser_payload)); return false; } return true; diff --git a/src/actions/skip_after.cc b/src/actions/skip_after.cc index 64cccb48d0..388ab186a8 100644 --- a/src/actions/skip_after.cc +++ b/src/actions/skip_after.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/actions/action.h" @@ -28,7 +29,7 @@ namespace actions { bool SkipAfter::evaluate(RuleWithActions *rule, Transaction *transaction) { - ms_dbg_a(transaction, 5, "Setting skipAfter for: " + *m_skipName); + ms_dbg_a(transaction, 5, fmt::format("Setting skipAfter for: {}", *m_skipName)); transaction->addMarker(m_skipName); return true; } diff --git a/src/actions/tag.cc b/src/actions/tag.cc index 120aba18dc..33745129a1 100644 --- a/src/actions/tag.cc +++ b/src/actions/tag.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/actions/action.h" #include "modsecurity/transaction.h" @@ -59,7 +60,7 @@ std::string Tag::getName(Transaction *transaction) { bool Tag::evaluate(RuleWithActions *rule, Transaction *transaction, RuleMessage &ruleMessage) { std::string tag = getName(transaction); - ms_dbg_a(transaction, 9, "Rule tag: " + tag); + ms_dbg_a(transaction, 9, fmt::format("Rule tag: {}", tag)); ruleMessage.m_tags.push_back(tag); diff --git a/src/actions/xmlns.cc b/src/actions/xmlns.cc index cb4044d839..d0364556ff 100644 --- a/src/actions/xmlns.cc +++ b/src/actions/xmlns.cc @@ -17,6 +17,7 @@ #include #include +#include #include "modsecurity/actions/action.h" #include "modsecurity/transaction.h" @@ -49,8 +50,8 @@ bool XmlNS::init(std::string *error) { } if (m_href.compare(0, http.length(), http) != 0) { - error->assign("XMLS: Missing xmlns href for prefix: " \ - "`" + m_href + "'."); + error->assign(fmt::format("XMLS: Missing xmlns href for prefix: " \ + "`{}'.", m_href)); return false; } diff --git a/src/anchored_set_variable.cc b/src/anchored_set_variable.cc index 6d7a5aa5ac..b0d3434811 100644 --- a/src/anchored_set_variable.cc +++ b/src/anchored_set_variable.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/anchored_set_variable.h" #include "modsecurity/modsecurity.h" @@ -81,8 +82,8 @@ void AnchoredSetVariable::resolve( if (!ke.toOmit(x.first)) { l->insert(l->begin(), new VariableValue(x.second)); } else { - ms_dbg_a(m_transaction, 7, "Excluding key: " + x.first - + " from target value."); + ms_dbg_a(m_transaction, 7, fmt::format("Excluding key: {} " \ + "from target value.", x.first)); } } } @@ -131,8 +132,8 @@ void AnchoredSetVariable::resolveRegularExpression(Utils::Regex *r, if (!ke.toOmit(x.first)) { l->insert(l->begin(), new VariableValue(x.second)); } else { - ms_dbg_a(m_transaction, 7, "Excluding key: " + x.first - + " from target value."); + ms_dbg_a(m_transaction, 7, fmt::format("Excluding key: {} " \ + " from target value.", x.first)); } } } diff --git a/src/audit_log/audit_log.cc b/src/audit_log/audit_log.cc index b0362c3378..9cc0b3d267 100644 --- a/src/audit_log/audit_log.cc +++ b/src/audit_log/audit_log.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include @@ -299,10 +300,9 @@ bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) { if ((transactionAuditLogStatus == RelevantOnlyAuditLogStatus && this->isRelevant(transaction->m_httpCodeReturned) == false) && saveAnyway == false) { - ms_dbg_a(transaction, 9, "Return code `" + - std::to_string(transaction->m_httpCodeReturned) + "'" \ - " is not interesting to audit logs, relevant code(s): `" + - m_relevant + "'."); + ms_dbg_a(transaction, 9, fmt::format("Return code `{}'" \ + " is not interesting to audit logs, relevant code(s): `{}'.", + transaction->m_httpCodeReturned, m_relevant)); return false; } @@ -318,7 +318,7 @@ bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) { std::string error; bool a = m_writer->write(transaction, parts, &error); if (a == false) { - ms_dbg_a(transaction, 1, "Cannot save the audit log: " + error); + ms_dbg_a(transaction, 1, fmt::format("Cannot save the audit log: {}", error)); return false; } } diff --git a/src/debug_log/debug_log.cc b/src/debug_log/debug_log.cc index e883177ca4..2e44274e69 100644 --- a/src/debug_log/debug_log.cc +++ b/src/debug_log/debug_log.cc @@ -15,6 +15,8 @@ #include "modsecurity/debug_log.h" +#include + #include "src/debug_log/debug_log_writer.h" #include "src/debug_log_writer_agent.h" @@ -71,20 +73,17 @@ int DebugLog::getDebugLogLevel() { void DebugLog::write(int level, const std::string &id, const std::string &uri, const std::string &msg) { if (level <= m_debugLevel) { - std::string msgf = "[" + std::to_string(level) + "] " + msg; - msgf = "[" + id + "] [" + uri + "] " + msgf; - DebugLogWriter &d = DebugLogWriter::getInstance(); - d.write_log(m_fileName, msgf); + d.write_log(m_fileName, fmt::format("[{}] [{}] [{}] {}", + id, uri, level, msg)); } } void DebugLog::write(int level, const std::string &msg) { if (level <= m_debugLevel) { - std::string msgf = "[" + std::to_string(level) + "] " + msg; DebugLogWriter &d = DebugLogWriter::getInstance(); - d.write_log(m_fileName, msgf); + d.write_log(m_fileName, fmt::format("[{}] {}", level, msg)); } } diff --git a/src/engine/lua.cc b/src/engine/lua.cc index 76d6a7194d..363e2f9cb5 100644 --- a/src/engine/lua.cc +++ b/src/engine/lua.cc @@ -25,6 +25,7 @@ #include #include #include +#include #include "modsecurity/variable_value.h" #include "modsecurity/modsecurity.h" @@ -46,12 +47,12 @@ bool Lua::isCompatible(const std::string &script, Lua *l, std::string *error) { if (!(script.size() >= lua.size() && script.compare(script.size() - lua.size(), lua.size(), lua) == 0)) { - error->assign("Expecting a Lua script: " + script); + error->assign(fmt::format("Expecting a Lua script: {}", script)); return false; } if (l->load(script, &err) == false) { - error->assign("Problems load script: " + err); + error->assign(fmt::format("Problems load script: {}", err)); return false; } @@ -71,7 +72,7 @@ bool Lua::load(const std::string &script, std::string *err) { m_scriptName = script; if (luaL_loadfile(L, script.c_str())) { const char *luaerr = lua_tostring(L, -1); - err->assign("Failed to compile script '" + script + ""); + err->assign(fmt::format("Failed to compile script '{}'", script)); if (luaerr) { err->append(": " + std::string(luaerr)); } @@ -87,7 +88,7 @@ bool Lua::load(const std::string &script, std::string *err) { if (lua_dump(L, Lua::blob_keeper, reinterpret_cast(&m_blob), 0)) { #endif const char *luaerr = lua_tostring(L, -1); - err->assign("Failed to compile script '" + script + ""); + err->assign(fmt::format("Failed to compile script '{}'", script)); if (luaerr) { err->append(": " + std::string(luaerr)); } @@ -146,7 +147,7 @@ int Lua::run(Transaction *t, const std::string &str) { // cppcheck-suppress cons #endif if (rc != LUA_OK) { std::string e; - e.assign("Failed to execute lua script: " + m_scriptName + ". "); + e.assign(fmt::format("Failed to execute lua script {}. ", m_scriptName)); switch (rc) { case LUA_ERRSYNTAX: e.assign("Syntax error. "); @@ -169,8 +170,8 @@ int Lua::run(Transaction *t, const std::string &str) { // cppcheck-suppress cons if (lua_pcall(L, 0, 0, 0)) { std::string e; const char *luaerr = lua_tostring(L, -1); - e.assign("Failed to execute lua script: " + m_scriptName \ - + " (before main)"); + e.assign(fmt::format("Failed to execute lua script {} (before main)", + m_scriptName)); if (luaerr != NULL) { e.append(" - "); e.append(luaerr); @@ -195,7 +196,8 @@ int Lua::run(Transaction *t, const std::string &str) { // cppcheck-suppress cons if (lua_pcall(L, ((!str.empty()) ? 1 : 0), 1, 0)) { std::string e; const char *luaerr = lua_tostring(L, -1); - e.assign("Failed to execute lua script: " + m_scriptName + " (main)"); + e.assign(fmt::format("Failed to execute lua script {} (main)", + m_scriptName)); if (luaerr != NULL) { e.append(" - "); e.append(luaerr); @@ -211,7 +213,7 @@ int Lua::run(Transaction *t, const std::string &str) { // cppcheck-suppress cons luaRet.assign(a); } - ms_dbg_a(t, 9, "Returning from lua script: " + luaRet); + ms_dbg_a(t, 9, fmt::format("Returning from lua script: {}", luaRet)); if (luaRet.size() == 0) { ret = false; @@ -438,8 +440,8 @@ void Lua::applyTransformations(lua_State *L, const Transaction *t, tfn->transform(var, t); } else { ms_dbg_a(t, 1, - "SecRuleScript: Invalid transformation function: " \ - + std::string(name)); + fmt::format("SecRuleScript: Invalid transformation function: {}", + name)); } delete tfn; } @@ -460,8 +462,8 @@ void Lua::applyTransformations(lua_State *L, const Transaction *t, tfn->transform(var, t); delete tfn; } else { - ms_dbg_a(t, 1, "SecRuleScript: Invalid transformation function: " \ - + std::string(name)); + ms_dbg_a(t, 1, fmt::format("SecRuleScript: Invalid transformation function: {}", + name)); } return; } diff --git a/src/modsecurity.cc b/src/modsecurity.cc index e1b29857e1..067442247a 100644 --- a/src/modsecurity.cc +++ b/src/modsecurity.cc @@ -32,6 +32,7 @@ #include #include +#include #include "modsecurity/rule.h" #include "modsecurity/rule_message.h" @@ -147,7 +148,8 @@ const std::string& ModSecurity::whoAmI() { #endif if (m_whoami.empty()) { - m_whoami = "ModSecurity v" MODSECURITY_VERSION " (" + platform + ")"; + m_whoami = fmt::format("ModSecurity v{} ({})", + MODSECURITY_VERSION, platform); } return m_whoami; @@ -275,10 +277,9 @@ int ModSecurity::processContentOffset(const char *content, size_t len, const auto value = std::string(content, stoi(startingAt), stoi(size)); if (varValue.size() > 0) { - varValue.append(" " + value); - } else { - varValue.append(value); + varValue.push_back(' '); } + varValue.append(value); } yajl_gen_array_close(g); diff --git a/src/operators/detect_sqli.cc b/src/operators/detect_sqli.cc index 49cef935c1..09e7a80c71 100644 --- a/src/operators/detect_sqli.cc +++ b/src/operators/detect_sqli.cc @@ -17,6 +17,7 @@ #include #include +#include #include "src/operators/operator.h" #include "libinjection/src/libinjection.h" @@ -38,18 +39,17 @@ bool DetectSQLi::evaluate(Transaction *t, RuleWithActions *rule, if (issqli) { t->m_matched.push_back(fingerprint); - ms_dbg_a(t, 4, "detected SQLi using libinjection with " \ - "fingerprint '" + std::string(fingerprint) + "' at: '" + - input + "'"); + ms_dbg_a(t, 4, fmt::format("detected SQLi using libinjection with " \ + "fingerprint '{}' at: '{}'", fingerprint, input)); if (rule && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", std::string(fingerprint)); - ms_dbg_a(t, 7, "Added DetectSQLi match TX.0: " + \ - std::string(fingerprint)); + ms_dbg_a(t, 7, fmt::format("Added DetectSQLi match TX.0: {}", + fingerprint)); } } else { - ms_dbg_a(t, 9, "detected SQLi: not able to find an " \ - "inject on '" + input + "'"); + ms_dbg_a(t, 9, fmt::format("detected SQLi: not able to find an " \ + "inject on '{}'", input)); } tisempty: diff --git a/src/operators/detect_xss.cc b/src/operators/detect_xss.cc index 014202e731..6af2142a89 100644 --- a/src/operators/detect_xss.cc +++ b/src/operators/detect_xss.cc @@ -16,6 +16,7 @@ #include "src/operators/detect_xss.h" #include +#include #include "src/operators/operator.h" #include "libinjection/src/libinjection.h" @@ -37,13 +38,13 @@ bool DetectXSS::evaluate(Transaction *t, RuleWithActions *rule, if (rule && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", std::string(input)); - ms_dbg_a(t, 7, "Added DetectXSS match TX.0: " + \ - std::string(input)); + ms_dbg_a(t, 7, fmt::format("Added DetectXSS match TX.0: {}", + input)); } } else { - ms_dbg_a(t, 9, "libinjection was not able to " \ - "find any XSS in: " + input); - } + ms_dbg_a(t, 9, fmt::format("libinjection was not able to " \ + "find any XSS in: {}", input)); + } } return is_xss != 0; } diff --git a/src/operators/fuzzy_hash.cc b/src/operators/fuzzy_hash.cc index df31a98c2b..414f95b995 100644 --- a/src/operators/fuzzy_hash.cc +++ b/src/operators/fuzzy_hash.cc @@ -16,6 +16,7 @@ #include "src/operators/fuzzy_hash.h" #include +#include #include "src/operators/operator.h" #include "src/utils/system.h" @@ -27,7 +28,6 @@ bool FuzzyHash::init(const std::string ¶m2, std::string *error) { #ifdef WITH_SSDEEP std::string digit; std::string file; - std::istream *iss; struct fuzzy_hash_chunk *chunk, *t; std::string err; @@ -41,20 +41,19 @@ bool FuzzyHash::init(const std::string ¶m2, std::string *error) { try { m_threshold = std::stoi(digit); } catch (...) { - error->assign("Expecting a digit, got: " + digit); + error->assign(fmt::format("Expecting a digit, got: {}", digit)); return false; } std::string resource = utils::find_resource(file, param2, &err); - iss = new std::ifstream(resource, std::ios::in); + std::ifstream iss(resource, std::ios::in); - if (((std::ifstream *)iss)->is_open() == false) { - error->assign("Failed to open file: " + m_param + ". " + err); - delete iss; + if (iss.is_open() == false) { + error->assign(fmt::format("Failed to open file: {}. {}", m_param, err)); return false; } - for (std::string line; std::getline(*iss, line); ) { + for (std::string line; std::getline(iss, line); ) { chunk = (struct fuzzy_hash_chunk *)calloc(1, sizeof(struct fuzzy_hash_chunk)); @@ -74,7 +73,6 @@ bool FuzzyHash::init(const std::string ¶m2, std::string *error) { } } - delete iss; return true; #else error->assign("@fuzzyHash: SSDEEP support was not enabled " \ @@ -110,8 +108,8 @@ bool FuzzyHash::evaluate(Transaction *t, const std::string &str) { while (chunk != NULL) { int i = fuzzy_compare(chunk->data, result); if (i >= m_threshold) { - ms_dbg_a(t, 4, "Fuzzy hash: matched " \ - "with score: " + std::to_string(i) + "."); + ms_dbg_a(t, 4, fmt::format("Fuzzy hash: matched " \ + "with score: {}.", i)); return true; } chunk = chunk->next; diff --git a/src/operators/inspect_file.cc b/src/operators/inspect_file.cc index 3796d26e62..4d3e3b39f4 100644 --- a/src/operators/inspect_file.cc +++ b/src/operators/inspect_file.cc @@ -19,6 +19,7 @@ #include #include +#include #include "src/operators/operator.h" #include "src/utils/system.h" @@ -31,16 +32,14 @@ namespace modsecurity { namespace operators { bool InspectFile::init(const std::string ¶m2, std::string *error) { - std::istream *iss; std::string err; std::string err_lua; m_file = utils::find_resource(m_param, param2, &err); - iss = new std::ifstream(m_file, std::ios::in); + std::ifstream iss(m_file, std::ios::in); - if (((std::ifstream *)iss)->is_open() == false) { - error->assign("Failed to open file: " + m_param + ". " + err); - delete iss; + if (iss.is_open() == false) { + error->assign(fmt::format("Failed to open file: {}. {}", m_param, err)); return false; } @@ -48,7 +47,6 @@ bool InspectFile::init(const std::string ¶m2, std::string *error) { m_isScript = true; } - delete iss; return true; } diff --git a/src/operators/operator.cc b/src/operators/operator.cc index 674e82d3dc..dd523ea8ad 100644 --- a/src/operators/operator.cc +++ b/src/operators/operator.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/transaction.h" #include "src/run_time_string.h" @@ -110,31 +111,28 @@ std::string Operator::resolveMatchMessage(Transaction *t, if (ret.empty() == true) { if (m_couldContainsMacro == false) { - ret = "Matched \"Operator `" + m_op + "' with parameter `" + - utils::string::limitTo(200, m_param) + - "' against variable `" + key + "' (Value: `" + - utils::string::limitTo(100, - utils::string::toHexIfNeeded(value)) + \ - "' )"; + ret = fmt::format("Matched \"Operator `{}' with parameter `{}' " \ + "against variable `{}' (Value: `{}' )", + m_op, utils::string::limitTo(200, m_param), + key, utils::string::limitTo(100, + utils::string::toHexIfNeeded(value))); } else { - std::string p(m_string->evaluate(t)); - ret = "Matched \"Operator `" + m_op + "' with parameter `" + - utils::string::limitTo(200, p) + - "' against variable `" + key + "' (Value: `" + - utils::string::limitTo(100, - utils::string::toHexIfNeeded(value)) + - "' )"; + const auto p = m_string->evaluate(t); + ret = fmt::format("Matched \"Operator `{}' with parameter `{}' " \ + "against variable `{}' (Value: `{}' )", + m_op, utils::string::limitTo(200, p), + key, utils::string::limitTo(100, + utils::string::toHexIfNeeded(value))); } } - return ret; } bool Operator::evaluate(Transaction *transaction, const std::string& a) { - ms_dbg_a(transaction, 2, "Operator: " + m_op + \ - " is not implemented or malfunctioning."); + ms_dbg_a(transaction, 2, fmt::format("Operator: {}" \ + " is not implemented or malfunctioning.", m_op)); return true; } diff --git a/src/operators/pm.cc b/src/operators/pm.cc index 46013e166f..14ad3e34c2 100644 --- a/src/operators/pm.cc +++ b/src/operators/pm.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "src/utils/acmp.h" #include "src/utils/string.h" @@ -162,8 +163,8 @@ bool Pm::evaluate(Transaction *transaction, RuleWithActions *rule, if (rule && rule->hasCaptureAction()) { transaction->m_collections.m_tx_collection->storeOrUpdateFirst("0", match_); - ms_dbg_a(transaction, 7, "Added pm match TX.0: " + \ - match_); + ms_dbg_a(transaction, 7, fmt::format("Added pm match TX.0: {}", + match_)); } } diff --git a/src/operators/pm_from_file.cc b/src/operators/pm_from_file.cc index f70677cdc6..79da393cc9 100644 --- a/src/operators/pm_from_file.cc +++ b/src/operators/pm_from_file.cc @@ -16,6 +16,7 @@ #include "src/operators/pm_from_file.h" #include +#include #include "src/operators/operator.h" #include "src/utils/https_client.h" @@ -60,7 +61,7 @@ bool PmFromFile::init(const std::string &config, std::string *error) { iss = new std::ifstream(resource, std::ios::in); if (((std::ifstream *)iss)->is_open() == false) { - error->assign("Failed to open file: " + m_param + ". " + err); + error->assign(fmt::format("Failed to open file: {}. {}", m_param, err)); delete iss; return false; } diff --git a/src/operators/rbl.cc b/src/operators/rbl.cc index 4b06f337ae..d5b2a0a04a 100644 --- a/src/operators/rbl.cc +++ b/src/operators/rbl.cc @@ -27,6 +27,7 @@ #endif #include +#include #include "modsecurity/rules_set.h" #include "src/operators/operator.h" @@ -44,28 +45,24 @@ std::string Rbl::mapIpToAddress(const std::string &ipStr, Transaction *trans) co } if (sscanf(ipStr.c_str(), "%d.%d.%d.%d", &h0, &h1, &h2, &h3) != 4) { - ms_dbg_a(trans, 0, std::string("Failed to understand `" + ipStr + - "' as a valid IP address, assuming domain format input")); + ms_dbg_a(trans, 0, fmt::format("Failed to understand `{}' " + "as a valid IP address, assuming domain format input", ipStr)); addr = ipStr + "." + m_service; return addr; } if (m_demandsPassword && key.empty()) { - ms_dbg_a(trans, 0, std::string("Missing RBL key, cannot continue " \ + ms_dbg_a(trans, 0, "Missing RBL key, cannot continue " \ "with the operator execution, please set the key using: " \ - "SecHttpBlKey")); + "SecHttpBlKey"); return addr; } - addr = std::to_string(h3) + "." + - std::to_string(h2) + "." + - std::to_string(h1) + "." + - std::to_string(h0) + "." + - m_service; + addr = fmt::format("{}.{}.{}.{}.{}", h3, h2, h1, h0, m_service); if (m_demandsPassword) { - addr = key + "." + addr; + addr = fmt::format("{}.{}", key, addr); } return addr; @@ -83,12 +80,12 @@ void Rbl::futherInfo_httpbl(struct sockaddr_in *sin, const std::string &ipStr, respBl = inet_ntoa(sin->sin_addr); if (sscanf(respBl, "%d.%d.%d.%d", &first, &days, &score, &type) != 4) { - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " failed: bad response"); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} failed: bad response", ipStr)); return; } if (first != 127) { - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " failed: bad response"); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} failed: bad response", ipStr)); return; } @@ -123,10 +120,9 @@ void Rbl::futherInfo_httpbl(struct sockaddr_in *sin, const std::string &ipStr, } #endif - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded. %s: " \ - + std::to_string(days) + " " \ - "days since last activity, threat score " \ - + std::to_string(score) + ". Case: " + ptype); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded. %s: {} " \ + "days since last activity, threat score {}. Case: {}", + ipStr, days, score, ptype)); } @@ -135,23 +131,24 @@ void Rbl::futherInfo_spamhaus(unsigned int high8bits, const std::string &ipStr, switch (high8bits) { case 2: case 3: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded " \ - "(Static UBE sources)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded " \ + "(Static UBE sources).", ipStr)); break; case 4: case 5: case 6: case 7: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded " \ - "(Illegal 3rd party exploits)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded " \ + "(Illegal 3rd party exploits).", ipStr)); break; case 10: case 11: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded " \ - "(Delivering unauthenticated SMTP email)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded " \ + "(Delivering unauthenticated SMTP email).", ipStr)); break; default: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded "); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded ", + ipStr)); break; } } @@ -161,24 +158,28 @@ void Rbl::futherInfo_uribl(unsigned int high8bits, const std::string &ipStr, const Transaction *trans) { switch (high8bits) { case 2: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded (BLACK)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded (BLACK).", + ipStr)); break; case 4: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded (GREY)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded (GREY).", + ipStr)); break; case 8: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded (RED)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded (RED).", + ipStr)); break; case 14: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded " \ - "(BLACK,GREY,RED)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded " \ + "(BLACK,GREY,RED).", ipStr)); break; case 255: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded " \ - "(DNS IS BLOCKED)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded " \ + "(DNS IS BLOCKED).", ipStr)); break; default: - ms_dbg_a(trans, 4, "RBL lookup of " + ipStr + " succeeded (WHITE)."); + ms_dbg_a(trans, 4, fmt::format("RBL lookup of {} succeeded (WHITE).", + ipStr)); break; } } @@ -190,7 +191,8 @@ void Rbl::furtherInfo(struct sockaddr_in *sin, const std::string &ipStr, switch (provider) { case RblProvider::UnknownProvider: - ms_dbg_a(trans, 2, "RBL lookup of " + ipStr + " succeeded."); + ms_dbg_a(trans, 2, fmt::format("RBL lookup of {} succeeded.", + ipStr)); break; case RblProvider::httpbl: futherInfo_httpbl(sin, ipStr, trans); @@ -222,7 +224,7 @@ bool Rbl::evaluate(Transaction *t, RuleWithActions *rule, if (info != NULL) { freeaddrinfo(info); } - ms_dbg_a(t, 5, "RBL lookup of " + ipStr + " failed."); + ms_dbg_a(t, 5, fmt::format("RBL lookup of {} failed.", ipStr)); return false; } @@ -234,8 +236,7 @@ bool Rbl::evaluate(Transaction *t, RuleWithActions *rule, if (rule && t && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", std::string(ipStr)); - ms_dbg_a(t, 7, "Added RXL match TX.0: " + \ - std::string(ipStr)); + ms_dbg_a(t, 7, fmt::format("Added RXL match TX.0: {}", ipStr)); } return true; diff --git a/src/operators/rx.cc b/src/operators/rx.cc index ce6526356f..3b7f0e9489 100644 --- a/src/operators/rx.cc +++ b/src/operators/rx.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "src/operators/operator.h" #include "modsecurity/rule.h" @@ -52,7 +53,7 @@ bool Rx::evaluate(Transaction *transaction, RuleWithActions *rule, } if (re->hasError()) { - ms_dbg_a(transaction, 3, "Error with regular expression: \"" + re->pattern + "\""); + ms_dbg_a(transaction, 3, fmt::format("Error with regular expression: \"{}\"", re->pattern)); return false; } @@ -78,7 +79,7 @@ bool Rx::evaluate(Transaction *transaction, RuleWithActions *rule, ms_dbg_a(transaction, 7, "Set TX.MSC_PCRE_LIMITS_EXCEEDED to 1"); } - ms_dbg_a(transaction, 1, "rx: regex error '" + regex_error_str + "' for pattern '" + re->pattern + "'"); + ms_dbg_a(transaction, 1, fmt::format("rx: regex error '{}' for pattern '{}'", regex_error_str, re->pattern)); return false; @@ -89,8 +90,8 @@ bool Rx::evaluate(Transaction *transaction, RuleWithActions *rule, const std::string capture_substring(input.substr(capture.m_offset,capture.m_length)); transaction->m_collections.m_tx_collection->storeOrUpdateFirst( std::to_string(capture.m_group), capture_substring); - ms_dbg_a(transaction, 7, "Added regex subexpression TX." + - std::to_string(capture.m_group) + ": " + capture_substring); + ms_dbg_a(transaction, 7, fmt::format("Added regex subexpression TX.{}: {}", + capture.m_group, capture_substring)); transaction->m_matched.push_back(capture_substring); } } diff --git a/src/operators/rx_global.cc b/src/operators/rx_global.cc index 6aeda76132..cde84de8d6 100644 --- a/src/operators/rx_global.cc +++ b/src/operators/rx_global.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "src/operators/operator.h" #include "modsecurity/rule.h" @@ -72,7 +73,7 @@ bool RxGlobal::evaluate(Transaction *transaction, RuleWithActions *rule, ms_dbg_a(transaction, 7, "Set TX.MSC_PCRE_LIMITS_EXCEEDED to 1"); } - ms_dbg_a(transaction, 1, "rxGlobal: regex error '" + regex_error_str + "' for pattern '" + re->pattern + "'"); + ms_dbg_a(transaction, 1, fmt::format("rxGlobal: regex error '{}' for pattern '{}'", regex_error_str, re->pattern)); return false; } @@ -83,8 +84,8 @@ bool RxGlobal::evaluate(Transaction *transaction, RuleWithActions *rule, const std::string capture_substring(input.substr(capture.m_offset,capture.m_length)); transaction->m_collections.m_tx_collection->storeOrUpdateFirst( std::to_string(capture.m_group), capture_substring); - ms_dbg_a(transaction, 7, "Added regex subexpression TX." + - std::to_string(capture.m_group) + ": " + capture_substring); + ms_dbg_a(transaction, 7, fmt::format("Added regex subexpression TX.{}: {}", + capture.m_group, capture_substring)); transaction->m_matched.push_back(capture_substring); } } diff --git a/src/operators/validate_byte_range.cc b/src/operators/validate_byte_range.cc index 2553b9c1a4..17d736650b 100644 --- a/src/operators/validate_byte_range.cc +++ b/src/operators/validate_byte_range.cc @@ -17,6 +17,7 @@ #include #include +#include #include "src/operators/operator.h" @@ -33,8 +34,8 @@ bool ValidateByteRange::getRange(const std::string &rangeRepresentation, try { start = std::stoi(rangeRepresentation); } catch(...) { - error->assign("Not able to convert '" + rangeRepresentation + - "' into a number"); + error->assign(fmt::format("Not able to convert '{}' into a number", + rangeRepresentation)); return false; } table[start >> 3] = (table[start >> 3] | (1 << (start & 0x7))); @@ -44,9 +45,8 @@ bool ValidateByteRange::getRange(const std::string &rangeRepresentation, try { start = std::stoi(std::string(rangeRepresentation, 0, pos)); } catch (...) { - error->assign("Not able to convert '" + - std::string(rangeRepresentation, 0, pos) + - "' into a number"); + error->assign(fmt::format("Not able to convert '{}' into a number", + std::string(rangeRepresentation, 0, pos))); return false; } @@ -54,24 +54,23 @@ bool ValidateByteRange::getRange(const std::string &rangeRepresentation, end = std::stoi(std::string(rangeRepresentation, pos + 1, rangeRepresentation.length() - (pos + 1))); } catch (...) { - error->assign("Not able to convert '" + std::string(rangeRepresentation, - pos + 1, rangeRepresentation.length() - (pos + 1)) + - "' into a number"); + error->assign(fmt::format("Not able to convert '{}' into a number", + std::string(rangeRepresentation, + pos + 1, rangeRepresentation.length() - (pos + 1)))); return false; } if ((start < 0) || (start > 255)) { - error->assign("Invalid range start value: " + - std::to_string(start)); + error->assign(fmt::format("Invalid range start value: {}", + start)); return false; } if ((end < 0) || (end > 255)) { - error->assign("Invalid range end value: " + std::to_string(end)); + error->assign(fmt::format("Invalid range end value: {}", end)); return false; } if (start > end) { - error->assign("Invalid range: " + std::to_string(start) + "-" + - std::to_string(end)); + error->assign(fmt::format("Invalid range: {}-{}", start, end)); return false; } diff --git a/src/operators/validate_dtd.cc b/src/operators/validate_dtd.cc index 138c707801..9a242156be 100644 --- a/src/operators/validate_dtd.cc +++ b/src/operators/validate_dtd.cc @@ -16,6 +16,7 @@ #include "src/operators/validate_dtd.h" #include +#include #include "src/request_body_processor/xml.h" #include "src/utils/system.h" @@ -29,7 +30,7 @@ bool ValidateDTD::init(const std::string &file, std::string *error) { std::string err; m_resource = utils::find_resource(m_param, file, &err); if (m_resource == "") { - error->assign("XML: File not found: " + m_param + ". " + err); + error->assign(fmt::format("XML: File not found: {}. {}", m_param, err)); return false; } @@ -47,8 +48,7 @@ bool ValidateDTD::evaluate(Transaction *transaction, const std::string &str) { XmlDtdPtrManager dtd(xmlParseDTD(NULL, (const xmlChar *)m_resource.c_str())); if (dtd.get() == NULL) { - std::string err = std::string("XML: Failed to load DTD: ") \ - + m_resource; + const auto err = fmt::format("XML: Failed to load DTD: {}", m_resource); ms_dbg_a(transaction, 4, err); return true; } @@ -92,8 +92,8 @@ bool ValidateDTD::evaluate(Transaction *transaction, const std::string &str) { return true; } - ms_dbg_a(transaction, 4, std::string("XML: Successfully validated " \ - "payload against DTD: ") + m_resource); + ms_dbg_a(transaction, 4, fmt::format("XML: Successfully validated " \ + "payload against DTD: {}", m_resource)); xmlFreeValidCtxt(cvp); diff --git a/src/operators/validate_schema.cc b/src/operators/validate_schema.cc index 1c38ac2405..fff82187af 100644 --- a/src/operators/validate_schema.cc +++ b/src/operators/validate_schema.cc @@ -16,6 +16,7 @@ #include "src/operators/validate_schema.h" #include +#include #include "src/operators/operator.h" #include "src/request_body_processor/xml.h" @@ -31,7 +32,7 @@ bool ValidateSchema::init(const std::string &file, std::string *error) { std::string err; m_resource = utils::find_resource(m_param, file, &err); if (m_resource == "") { - error->assign("XML: File not found: " + m_param + ". " + err); + error->assign(fmt::format("XML: File not found: {}. {}", m_param, err)); return false; } @@ -117,8 +118,8 @@ bool ValidateSchema::evaluate(Transaction *transaction, ms_dbg_a(transaction, 4, "XML: Schema validation failed."); return true; /* No match. */ } else { - ms_dbg_a(transaction, 4, "XML: Successfully validated payload against " \ - "Schema: " + m_resource); + ms_dbg_a(transaction, 4, fmt::format("XML: Successfully validated payload against " \ + "Schema: {}", m_resource)); return false; } } diff --git a/src/operators/validate_url_encoding.cc b/src/operators/validate_url_encoding.cc index 7ca71b221c..ff1db23f78 100644 --- a/src/operators/validate_url_encoding.cc +++ b/src/operators/validate_url_encoding.cc @@ -16,6 +16,7 @@ #include "src/operators/validate_url_encoding.h" #include +#include #include "src/operators/operator.h" @@ -82,22 +83,22 @@ bool ValidateUrlEncoding::evaluate(Transaction *transaction, RuleWithActions *ru case 1 : /* Encoding is valid */ if (transaction) { - ms_dbg_a(transaction, 7, "Valid URL Encoding at '" +input + "'"); + ms_dbg_a(transaction, 7, fmt::format("Valid URL Encoding at '{}'", input)); } res = false; break; case -2 : if (transaction) { - ms_dbg_a(transaction, 7, "Invalid URL Encoding: Non-hexadecimal " - "digits used at '" + input + "'"); + ms_dbg_a(transaction, 7, fmt::format("Invalid URL Encoding: Non-hexadecimal " \ + "digits used at '{}'", input)); logOffset(ruleMessage, offset, input.size()); } res = true; /* Invalid match. */ break; case -3 : if (transaction) { - ms_dbg_a(transaction, 7, "Invalid URL Encoding: Not enough " \ - "characters at the end of input at '" + input + "'"); + ms_dbg_a(transaction, 7, fmt::format("Invalid URL Encoding: Not enough " \ + "characters at the end of input at '{}'", input)); logOffset(ruleMessage, offset, input.size()); } res = true; /* Invalid match. */ @@ -105,9 +106,8 @@ bool ValidateUrlEncoding::evaluate(Transaction *transaction, RuleWithActions *ru case -1 : default : if (transaction) { - ms_dbg_a(transaction, 7, "Invalid URL Encoding: Internal " \ - "Error (rc = " + std::to_string(rc) + ") at '" + - input + "'"); + ms_dbg_a(transaction, 7, fmt::format("Invalid URL Encoding: Internal " \ + "Error (rc = {}) at '{}'", rc, input)); logOffset(ruleMessage, offset, input.size()); } res = true; diff --git a/src/operators/validate_utf8_encoding.cc b/src/operators/validate_utf8_encoding.cc index 1a166efb69..89db4ad39e 100644 --- a/src/operators/validate_utf8_encoding.cc +++ b/src/operators/validate_utf8_encoding.cc @@ -16,6 +16,7 @@ #include "src/operators/validate_utf8_encoding.h" #include +#include #include "src/operators/operator.h" @@ -134,44 +135,39 @@ bool ValidateUtf8Encoding::evaluate(Transaction *transaction, RuleWithActions *r switch (rc) { case UNICODE_ERROR_CHARACTERS_MISSING : if (transaction) { - ms_dbg_a(transaction, 8, "Invalid UTF-8 encoding: " - "not enough bytes in character " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Invalid UTF-8 encoding: " \ + "not enough bytes in character " \ + "at {}. [offset \"{}\"]", str, i)); } return true; case UNICODE_ERROR_INVALID_ENCODING : if (transaction) { - ms_dbg_a(transaction, 8, "Invalid UTF-8 encoding: " - "invalid byte value in character " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Invalid UTF-8 encoding: " \ + "invalid byte value in character " \ + "at {}. [offset \"{}\"]", str, i)); logOffset(ruleMessage, i, str.size()); } return true; case UNICODE_ERROR_OVERLONG_CHARACTER : if (transaction) { - ms_dbg_a(transaction, 8, "Invalid UTF-8 encoding: " - "overlong character detected " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Invalid UTF-8 encoding: " \ + "overlong character detected " \ + "at {}. [offset \"{}\"]", str, i)); logOffset(ruleMessage, i, str.size()); } return true; case UNICODE_ERROR_RESTRICTED_CHARACTER : if (transaction) { - ms_dbg_a(transaction, 8, "Invalid UTF-8 encoding: " - "use of restricted character " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Invalid UTF-8 encoding: " \ + "use of restricted character " \ + "at {}. [offset \"{}\"]", str, i)); logOffset(ruleMessage, i, str.size()); } return true; case UNICODE_ERROR_DECODING_ERROR : if (transaction) { - ms_dbg_a(transaction, 8, "Error validating UTF-8 decoding " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Error validating UTF-8 decoding " \ + "at {}. [offset \"{}\"]", str, i)); logOffset(ruleMessage, i, str.size()); } return true; @@ -179,9 +175,8 @@ bool ValidateUtf8Encoding::evaluate(Transaction *transaction, RuleWithActions *r if (rc <= 0) { if (transaction) { - ms_dbg_a(transaction, 8, "Internal error during UTF-8 validation " - "at " + str + ". [offset \"" + - std::to_string(i) + "\"]"); + ms_dbg_a(transaction, 8, fmt::format("Internal error during UTF-8 validation " \ + "at {}. [offset \"{}\"]", str, i)); logOffset(ruleMessage, i, str.size()); } return true; diff --git a/src/operators/verify_cc.cc b/src/operators/verify_cc.cc index 66f2e91178..a4e4ec956b 100644 --- a/src/operators/verify_cc.cc +++ b/src/operators/verify_cc.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "src/operators/operator.h" @@ -185,12 +186,11 @@ bool VerifyCC::evaluate(Transaction *t, RuleWithActions *rule, if (rule && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", std::string(match)); - ms_dbg_a(t, 7, "Added VerifyCC match TX.0: " + \ - std::string(match)); + ms_dbg_a(t, 7, fmt::format("Added VerifyCC match TX.0: {}", + match)); } - ms_dbg_a(t, 9, "CC# match \"" + m_param + - "\" at " + i + ". [offset " + - std::to_string(offset) + "]"); + ms_dbg_a(t, 9, fmt::format("CC# match \"{}\" at {}. [offset {}]", + m_param, i, offset)); } #ifdef WITH_PCRE2 pcre2_match_data_free(match_data); diff --git a/src/operators/verify_cpf.cc b/src/operators/verify_cpf.cc index 3163109cef..0c60ea6341 100644 --- a/src/operators/verify_cpf.cc +++ b/src/operators/verify_cpf.cc @@ -17,6 +17,7 @@ #include #include +#include #include "src/operators/operator.h" @@ -127,8 +128,8 @@ bool VerifyCPF::evaluate(Transaction *t, RuleWithActions *rule, if (rule && t && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", m.str()); - ms_dbg_a(t, 7, "Added VerifyCPF match TX.0: " + \ - m.str()); + ms_dbg_a(t, 7, fmt::format("Added VerifyCPF match TX.0: {}", + m.str())); } goto out; diff --git a/src/operators/verify_ssn.cc b/src/operators/verify_ssn.cc index eabeb1a4ec..a5f790fe08 100644 --- a/src/operators/verify_ssn.cc +++ b/src/operators/verify_ssn.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "src/operators/operator.h" @@ -129,8 +130,8 @@ bool VerifySSN::evaluate(Transaction *t, RuleWithActions *rule, if (rule && t && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", j.str()); - ms_dbg_a(t, 7, "Added VerifySSN match TX.0: " + \ - j.str()); + ms_dbg_a(t, 7, fmt::format("Added VerifySSN match TX.0: {}", + j.str())); } goto out; diff --git a/src/operators/verify_svnr.cc b/src/operators/verify_svnr.cc index 210e920112..1d0fb4b012 100644 --- a/src/operators/verify_svnr.cc +++ b/src/operators/verify_svnr.cc @@ -2,6 +2,7 @@ #include "src/operators/verify_svnr.h" #include +#include #include "src/operators/operator.h" @@ -97,8 +98,8 @@ bool VerifySVNR::evaluate(Transaction *t, RuleWithActions *rule, if (rule && t && rule->hasCaptureAction()) { t->m_collections.m_tx_collection->storeOrUpdateFirst( "0", j.str()); - ms_dbg_a(t, 7, "Added VerifySVNR match TX.0: " + \ - j.str()); + ms_dbg_a(t, 7, fmt::format("Added VerifySVNR match TX.0: {}", + j.str())); } goto out; diff --git a/src/parser/driver.cc b/src/parser/driver.cc index b86f4c57f8..75f373deb0 100644 --- a/src/parser/driver.cc +++ b/src/parser/driver.cc @@ -15,6 +15,8 @@ #include "src/parser/driver.h" +#include + #include "modsecurity/rules_set_properties.h" #include "src/parser/seclang-parser.hh" #include "modsecurity/audit_log.h" @@ -56,8 +58,8 @@ int Driver::addSecMarker(const std::string& marker, const std::string &fileName, int Driver::addSecAction(std::unique_ptr rule) { if (rule->getPhase() >= modsecurity::Phases::NUMBER_OF_PHASES) { - m_parserError << "Unknown phase: " << std::to_string(rule->getPhase()); - m_parserError << std::endl; + m_parserError << fmt::format("Unknown phase: {}", rule->getPhase()) + << std::endl; return false; } @@ -75,8 +77,8 @@ int Driver::addSecRuleScript(std::unique_ptr rule) { int Driver::addSecRule(std::unique_ptr r) { if (r->getPhase() >= modsecurity::Phases::NUMBER_OF_PHASES) { - m_parserError << "Unknown phase: " << std::to_string(r->getPhase()); - m_parserError << std::endl; + m_parserError << fmt::format("Unknown phase: {}", r->getPhase()) + << std::endl; return false; } @@ -84,8 +86,8 @@ int Driver::addSecRule(std::unique_ptr r) { if (m_lastRule != nullptr && m_lastRule->isChained()) { r->setPhase(m_lastRule->getPhase()); if (r->hasDisruptiveAction()) { - m_parserError << "Disruptive actions can only be specified by"; - m_parserError << " chain starter rules."; + m_parserError << "Disruptive actions can only be specified by " \ + "chain starter rules."; return false; } m_lastRule->m_chainedRuleChild = std::move(r); @@ -100,9 +102,8 @@ int Driver::addSecRule(std::unique_ptr r) { * by other rule */ if (rule->m_ruleId == 0) { - m_parserError << "Rules must have an ID. File: "; - m_parserError << rule->getFileName() << " at line: "; - m_parserError << std::to_string(rule->getLineNumber()) << std::endl; + m_parserError << fmt::format("Rules must have an ID. File: {} at line: {}", + rule->getFileName(), rule->getLineNumber()) << std::endl; return false; } @@ -111,8 +112,8 @@ int Driver::addSecRule(std::unique_ptr r) { for (int j = 0; j < rules->size(); j++) { const RuleWithOperator *lr = dynamic_cast(rules->at(j).get()); if (lr && lr->m_ruleId == rule->m_ruleId) { - m_parserError << "Rule id: " << std::to_string(rule->m_ruleId) \ - << " is duplicated" << std::endl; + m_parserError << fmt::format("Rule id: {} is duplicated", + rule->m_ruleId) << std::endl; return false; } } @@ -177,7 +178,7 @@ int Driver::parseFile(const std::string &f) { std::string str; if (utils::isFile(f) == false) { - m_parserError << "Failed to open the file: " << f << std::endl; + m_parserError << fmt::format("Failed to open the file: {}", f) << std::endl; return false; } @@ -200,14 +201,12 @@ void Driver::error(const yy::location& l, const std::string& m) { void Driver::error(const yy::location& l, const std::string& m, const std::string& c) { if (m_parserError.tellp() == 0) { - m_parserError << "Rules error. "; - m_parserError << "File: " << *l.end.filename << ". "; - m_parserError << "Line: " << l.end.line << ". "; - m_parserError << "Column: " << l.end.column - 1 << ". "; + m_parserError << fmt::format("Rules error. File: {}. Line: {}. Column: {}. ", + *l.end.filename, l.end.line, l.end.column - 1); } if (m.empty() == false) { - m_parserError << "" << m << " "; + m_parserError << m << " "; } if (c.empty() == false) { diff --git a/src/request_body_processor/json.cc b/src/request_body_processor/json.cc index f56704effa..d489a59212 100644 --- a/src/request_body_processor/json.cc +++ b/src/request_body_processor/json.cc @@ -21,6 +21,7 @@ #include #include #include +#include namespace modsecurity { @@ -133,11 +134,11 @@ int JSON::addArgument(const std::string& value) { for (size_t i = 0; i < m_containers.size(); i++) { const JSONContainerArray *a = dynamic_cast( m_containers[i]); - path = path + m_containers[i]->m_name; + path.append(m_containers[i]->m_name); if (a != NULL) { - path = path + ".array_" + std::to_string(a->m_elementCounter); + path.append(fmt::format(".array_{}", a->m_elementCounter)); } else { - path = path + "."; + path.push_back('.'); } } diff --git a/src/request_body_processor/multipart.cc b/src/request_body_processor/multipart.cc index fd140329b8..b082602797 100644 --- a/src/request_body_processor/multipart.cc +++ b/src/request_body_processor/multipart.cc @@ -31,6 +31,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/collection/collections.h" @@ -52,15 +53,14 @@ MultipartPartTmpFile::~MultipartPartTmpFile() { const int unlink_rc = unlink(m_tmp_file_name.c_str()); if (unlink_rc < 0) { - ms_dbg_a(m_transaction, 1, "Multipart: Failed to delete file (part) \"" \ - + m_tmp_file_name + "\" because " \ - + std::to_string(errno) + "(" \ - + strerror(errno) + ")"); + ms_dbg_a(m_transaction, 1, fmt::format("Multipart: " \ + "Failed to delete file (part) \"{}\" because {}({})", + m_tmp_file_name, errno, strerror(errno))); } else { - ms_dbg_a(m_transaction, 4, "Multipart: file deleted successfully (part) \"" \ - + m_tmp_file_name + "\""); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "file deleted successfully (part) \"{}\"", + m_tmp_file_name)); } - } } @@ -74,8 +74,7 @@ void MultipartPartTmpFile::Open() { strftime(tstr, std::size(tstr), "/%Y%m%d-%H%M%S", &timeinfo); std::string path = m_transaction->m_rules->m_uploadDirectory.m_value; - path = path + tstr + "-" + m_transaction->m_id; - path += "-file-XXXXXX"; + path.append(fmt::format("{}-{}-file-XXXXXX", tstr, m_transaction->m_id)); #ifndef WIN32 m_tmp_file_fd = mkstemp(path.data()); @@ -84,7 +83,8 @@ void MultipartPartTmpFile::Open() { m_tmp_file_fd = _open(path.c_str(), _O_CREAT | _O_EXCL | _O_RDWR); #endif m_tmp_file_name = path; - ms_dbg_a(m_transaction, 4, "MultipartPartTmpFile: Create filename= " + m_tmp_file_name); + ms_dbg_a(m_transaction, 4, fmt::format("MultipartPartTmpFile: " \ + "Create filename= {}", m_tmp_file_name)); int mode = m_transaction->m_rules->m_uploadFileMode.m_value; if ((m_tmp_file_fd != -1) && (mode != 0)) { @@ -140,11 +140,10 @@ Multipart::Multipart(const std::string &header, Transaction *transaction) Multipart::~Multipart() { - ms_dbg_a(m_transaction, 4, - "Multipart: Cleanup started (keep files set to " \ - + RulesSetProperties::configBooleanString( - m_transaction->m_rules->m_uploadKeepFiles) \ - + ")"); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Cleanup started (keep files set to {})", + RulesSetProperties::configBooleanString( + m_transaction->m_rules->m_uploadKeepFiles))); if (m_transaction->m_rules->m_uploadKeepFiles != RulesSetProperties::TrueConfigBoolean) { @@ -152,8 +151,9 @@ Multipart::~Multipart() { if ((m->m_type == MULTIPART_FILE) && (m->m_tmp_file)) { // only mark for deletion for now; the file should stay on disk until // the transaction is complete - ms_dbg_a(m_transaction, 9, "Multipart: Marking temporary file for deletion: " \ - + m->m_tmp_file->getFilename()); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Marking temporary file for deletion: {}", + m->m_tmp_file->getFilename())); m->m_tmp_file->setDelete(); } @@ -257,10 +257,9 @@ void Multipart::validate_quotes(const char *data, char quote) { for (int i = 0;i < len;i++) { if (data[i] == '\'') { - ms_dbg_a(m_transaction, 9, - "Multipart: Invalid quoting detected: " \ - + std::string(data) + " length " \ - + std::to_string(len) + " bytes"); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Invalid quoting detected: {} length {} bytes", + data, len)); m_flag_invalid_quoting = 1; } } @@ -435,41 +434,41 @@ int Multipart::parse_content_disposition(const char *c_d_value, int offset) { offset + ((p - c_d_value) - value.size())); if (!m_mpp->m_name.empty()) { - ms_dbg_a(m_transaction, 4, - "Multipart: Warning: Duplicate Content-Disposition " \ - "name: " + value + ". Previously: " + m_mpp->m_name + ""); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Warning: Duplicate Content-Disposition name: {}. Previously: {}", + value, m_mpp->m_name)); return -14; } m_mpp->m_name.assign(value); m_mpp->m_nameOffset = offset + ((p - c_d_value) - value.size()); - ms_dbg_a(m_transaction, 9, - "Multipart: Content-Disposition name: " + value + "."); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Content-Disposition name: {}.", value)); } else if (name == "filename") { validate_quotes(value.c_str(), quote); m_transaction->m_variableMultipartFileName.set(value, value, \ offset + ((p - c_d_value) - value.size())); if (!m_mpp->m_filename.empty()) { - ms_dbg_a(m_transaction, 4, - "Multipart: Warning: Duplicate Content-Disposition " \ - "filename: " + value + "."); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Warning: Duplicate Content-Disposition filename: {}.", + value)); return -15; } m_mpp->m_filename.assign(value); m_mpp->m_filenameOffset = offset + ((p - c_d_value) - value.size()); - ms_dbg_a(m_transaction, 9, - "Multipart: Content-Disposition filename: " + value + "."); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Content-Disposition filename: {}.", value)); } else if (name == "filename*") { if (!filenameStar.empty()) { - ms_dbg_a(m_transaction, 4, - "Multipart: Warning: Duplicate Content-Disposition " \ - "filename*: " + value + "."); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Warning: Duplicate Content-Disposition filename: {}.", + value)); return -20; } filenameStar.assign(value); - ms_dbg_a(m_transaction, 9, - "Multipart: Content-Disposition filename*: " + value + "."); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Content-Disposition filename*: {}.", value)); } else { return -11; } @@ -486,10 +485,9 @@ int Multipart::parse_content_disposition(const char *c_d_value, int offset) { if (*p != ';') { p--; if (*p == '\'' || *p == '\"') { - ms_dbg_a(m_transaction, 9, - "Multipart: Invalid quoting detected: " \ - + std::string(p) + " length " \ - + std::to_string(strlen(p)) + " bytes"); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Invalid quoting detected: {} length {} bytes", + p, strlen(p))); m_flag_invalid_quoting = 1; } /* p++; */ @@ -503,9 +501,9 @@ int Multipart::parse_content_disposition(const char *c_d_value, int offset) { } if (!filenameStar.empty() && m_mpp->m_filename.empty()) { - ms_dbg_a(m_transaction, 4, - "Multipart: Warning: no filename= but filename*:" \ - + filenameStar + "."); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Warning: no filename= but filename*:{}.", + filenameStar)); return -21; } @@ -556,15 +554,11 @@ int Multipart::process_part_data(std::string *error, size_t offset) { && (m_nfiles >= m_transaction->m_rules->m_uploadFileLimit.m_value)) { if (m_flag_file_limit_exceeded == 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Upload file limit exceeded " \ - + std::to_string( - m_transaction->m_rules->m_uploadFileLimit.m_value) \ - + ". Use SecUploadFileLimit to change the limit."); - error->assign("Multipart: Upload file limit exceeded " \ - + std::to_string( - m_transaction->m_rules->m_uploadFileLimit.m_value) \ - + ". Use SecUploadFileLimit to change the limit."); + const auto err = fmt::format("Multipart: Upload file limit exceeded {}. " \ + "Use SecUploadFileLimit to change the limit.", + m_transaction->m_rules->m_uploadFileLimit.m_value); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); m_flag_file_limit_exceeded = 1; } extract = 0; @@ -581,32 +575,30 @@ int Multipart::process_part_data(std::string *error, size_t offset) { /* do we have an opened file? */ if (!m_mpp->m_tmp_file || m_mpp->m_tmp_file->getFd() < 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Failed to create file: " \ - + m_mpp->m_tmp_file->getFilename()); - error->assign("Multipart: Failed to create file: " \ - + m_mpp->m_tmp_file->getFilename()); + const auto err = fmt::format("Multipart: Failed to create file: {}", + m_mpp->m_tmp_file->getFilename()); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return -1; } /* keep track of the files count */ m_nfiles++; - ms_dbg_a(m_transaction, 4, - "Multipart: Created temporary file " \ - + std::to_string(m_nfiles) + " (mode o" + std::to_string(m_transaction->m_rules->m_uploadFileMode.m_value) + "): " \ - + m_mpp->m_tmp_file->getFilename()); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Created temporary file {} (mode o{}): {}", + m_nfiles, m_transaction->m_rules->m_uploadFileMode.m_value, + m_mpp->m_tmp_file->getFilename())); } /* write the reserve first */ if (m_reserve[0] != 0) { if (write(m_mpp->m_tmp_file->getFd(), &m_reserve[1], m_reserve[0]) != m_reserve[0]) { - ms_dbg_a(m_transaction, 1, - "Multipart: writing to \"" \ - + m_mpp->m_tmp_file->getFilename() + "\" failed"); - error->assign("Multipart: writing to \"" \ - + m_mpp->m_tmp_file->getFilename() + "\" failed"); + const auto err = fmt::format("Multipart: writing to \"{}\" failed", + m_mpp->m_tmp_file->getFilename()); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return -1; } @@ -623,11 +615,10 @@ int Multipart::process_part_data(std::string *error, size_t offset) { if (write(m_mpp->m_tmp_file->getFd(), m_buf, MULTIPART_BUF_SIZE - m_bufleft) != (MULTIPART_BUF_SIZE - m_bufleft)) { - ms_dbg_a(m_transaction, 1, - "Multipart: writing to \"" \ - + m_mpp->m_tmp_file->getFilename() + "\" failed"); - error->assign("Multipart: writing to \"" \ - + m_mpp->m_tmp_file->getFilename() + "\" failed"); + const auto err = fmt::format("Multipart: writing to \"{}\" failed", + m_mpp->m_tmp_file->getFilename()); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return -1; } @@ -679,15 +670,13 @@ int Multipart::process_part_data(std::string *error, size_t offset) { m_mpp->m_value_parts.push_back(std::make_pair(d, m_buf_offset)); - ms_dbg_a(m_transaction, 9, - "Multipart: Added data to variable: " + d); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Added data to variable: {}", d)); } else { - ms_dbg_a(m_transaction, 1, - "Multipart: unknown part type: " \ - + std::to_string(m_mpp->m_type)); - - error->assign("Multipart: unknown part type: " \ - + std::to_string(m_mpp->m_type)); + const auto err = fmt::format("Multipart: unknown part type: {}", + m_mpp->m_type); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } @@ -716,10 +705,9 @@ int Multipart::process_part_header(std::string *error, int offset) { int len_without_termination = len - 1; for (i = 0; i < len; i++) { if (m_buf[i] == '\0') { - ms_dbg_a(m_transaction, 1, - "Multipart: Nul byte in part headers."); - - error->assign("Multipart: Nul byte in part headers."); + const auto err = "Multipart: Nul byte in part headers."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } } @@ -753,11 +741,9 @@ int Multipart::process_part_header(std::string *error, int offset) { } if (m_mpp->m_headers.count("Content-Disposition") == 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Part missing Content-Disposition header."); - - error->assign("Multipart: Part missing " \ - "Content-Disposition header."); + const auto err = "Multipart: Part missing Content-Disposition header."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } header_value = m_mpp->m_headers.at("Content-Disposition").second; @@ -771,23 +757,18 @@ int Multipart::process_part_header(std::string *error, int offset) { rc = -99; } if (rc < 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Invalid Content-Disposition header (" - + std::to_string(rc) + "): " + header_value); - - error->assign("Multipart: Invalid Content-Disposition header (" - + std::to_string(rc) + "): " + header_value); + const auto err = fmt::format("Multipart: " \ + "Invalid Content-Disposition header ({}): {}", rc, header_value); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } if (m_mpp->m_name.empty()) { - ms_dbg_a(m_transaction, 1, - "Multipart: Content-Disposition header missing " \ - "name field."); - - error->assign("Multipart: Content-Disposition header missing " \ - "name field."); - + const auto err = "Multipart: Content-Disposition header missing " \ + "name field."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } @@ -797,12 +778,10 @@ int Multipart::process_part_header(std::string *error, int offset) { * didn't understand C-D but we did. */ if (strstr(header_value.c_str(), "filename=") == NULL) { - ms_dbg_a(m_transaction, 1, - "Multipart: Invalid Content-Disposition " \ - "header (filename)."); - - error->assign("Multipart: Invalid Content-Disposition " \ - "header (filename)."); + const auto err = "Multipart: Invalid Content-Disposition " \ + "header (filename)."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } @@ -833,11 +812,9 @@ int Multipart::process_part_header(std::string *error, int offset) { if (m_mpp->m_last_header_name.empty()) { /* we are not building a header at this moment */ - ms_dbg_a(m_transaction, 1, - "Multipart: Invalid part header (folding error)."); - - error->assign("Multipart: Invalid part header " \ - "(folding error)."); + const auto err = "Multipart: Invalid part header (folding error)."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } @@ -863,19 +840,18 @@ int Multipart::process_part_header(std::string *error, int offset) { new_value = header_value + " " + new_value; m_mpp->m_headers.at(m_mpp->m_last_header_name).second = new_value; - ms_dbg_a(m_transaction, 9, - "Multipart: Continued folder header \"" \ - + m_mpp->m_last_header_name + "\" with \"" \ - + std::string(data) + "\""); - + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Continued folder header \"{}\" with \"{}\"", + m_mpp->m_last_header_name, data)); if (new_value.size() > MULTIPART_BUF_SIZE) { - ms_dbg_a(m_transaction, 1, "Multipart: Part header too long."); - - error->assign("Multipart: Part header too long."); + const auto err = "Multipart: Part header too long."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } - m_mpp->m_last_header_line = m_mpp->m_last_header_name + ": " + new_value; + m_mpp->m_last_header_line = fmt::format("{}: {}", + m_mpp->m_last_header_name, new_value); } else { char *data; std::string header_value; @@ -895,25 +871,21 @@ int Multipart::process_part_header(std::string *error, int offset) { i++; } if (*data == '\0') { - ms_dbg_a(m_transaction, 1, - "Multipart: Invalid part header (colon missing): " \ - + std::string(m_buf)); - - error->assign("Multipart: Invalid part header " \ - "(colon missing): " + std::string(m_buf)); + const auto err = fmt::format("Multipart: " \ + "Invalid part header (colon missing): {}", m_buf); + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } /* extract header name */ header_name = std::string(m_buf, data - m_buf); if (data == m_buf) { - ms_dbg_a(m_transaction, 1, - "Multipart: Invalid part header " \ - "(header name missing)."); - - error->assign("Multipart: Invalid part header " \ - "(header name missing)."); - return false; + const auto err = "Multipart: Invalid part header " \ + "(header name missing)."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); + return false; } /* check if multipart header contains any invalid characters */ @@ -940,9 +912,9 @@ int Multipart::process_part_header(std::string *error, int offset) { /* error if the name already exists */ if (m_mpp->m_headers.count(header_name) > 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Duplicate part header: " \ - + header_name + "."); + ms_dbg_a(m_transaction, 1, fmt::format("Multipart: " \ + "Duplicate part header: {}.", + header_name)); return false; } @@ -954,9 +926,9 @@ int Multipart::process_part_header(std::string *error, int offset) { std::string(header_name), std::make_pair(offset - len + i, std::string(header_value))); - ms_dbg_a(m_transaction, 9, - "Multipart: Added part header \"" + header_name \ - + "\" \"" + header_value + "\"."); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Added part header \"{}\" \"{}\".", + header_name, header_value)); if (len_without_termination > 0) { m_mpp->m_last_header_line.assign(m_buf, len_without_termination); } else { @@ -976,7 +948,8 @@ int Multipart::process_boundary(int last_part) { for (const auto& header_line : m_mpp->m_header_lines) { m_transaction->m_variableMultipartPartHeaders.set(m_mpp->m_name, header_line.second, header_line.first); - ms_dbg_a(m_transaction, 9, "Multipart: Added part header line:" + header_line.second ); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Added part header line:{}", header_line.second)); } /* close the temp file */ @@ -1000,25 +973,23 @@ int Multipart::process_boundary(int last_part) { m_parts.push_back(m_mpp); if (m_mpp->m_type == MULTIPART_FILE) { - ms_dbg_a(m_transaction, 9, - "Multipart: Added file part to the list: name \"" \ - + m_mpp->m_name + "\" " - "file name \"" + m_mpp->m_filename + "\" (offset " \ - + std::to_string(m_mpp->m_offset) + - ", length " + std::to_string(m_mpp->m_length) + ")"); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Added file part to the list: name \"{}\" " \ + "file name \"{}\" (offset {}, length {})", + m_mpp->m_name, m_mpp->m_filename, + m_mpp->m_offset, m_mpp->m_length)); } else { - ms_dbg_a(m_transaction, 9, - "Multipart: Added part to the list: name \"" \ - + m_mpp->m_name + "\" " - "(offset " + std::to_string(m_mpp->m_offset) \ - + ", length " + std::to_string(m_mpp->m_length) + ")"); + ms_dbg_a(m_transaction, 9, fmt::format("Multipart: " \ + "Added part to the list: name \"{}\" " \ + "(offset {}, length {})", + m_mpp->m_name, m_mpp->m_offset, m_mpp->m_length)); } } else { m_flag_invalid_part = true; - ms_dbg_a(m_transaction, 3, - "Multipart: Skipping invalid part (part name missing): " - "(offset " + std::to_string(m_mpp->m_offset) + ", length " - + std::to_string(m_mpp->m_length) + ")"); + ms_dbg_a(m_transaction, 3, fmt::format("Multipart: " \ + "Skipping invalid part (part name missing): " \ + "(offset {}, length {}", + m_mpp->m_offset, m_mpp->m_length)); delete m_mpp; } @@ -1198,15 +1169,15 @@ int Multipart::multipart_complete(std::string *error) { } if (m_is_complete == 0) { - ms_dbg_a(m_transaction, 1, - "Multipart: Final boundary missing."); - error->assign("Multipart: Final boundary missing."); + const auto err = "Multipart: Final boundary missing."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } } else { - ms_dbg_a(m_transaction, 1, - "Multipart: No boundaries found in payload."); - error->assign("Multipart: No boundaries found in payload."); + const auto err = "Multipart: No boundaries found in payload."; + ms_dbg_a(m_transaction, 1, err); + error->assign(err); return false; } } @@ -1246,9 +1217,8 @@ int Multipart::multipart_complete(std::string *error) { std::to_string(file_combined_size), m->m_tmp_file_size.second, m->m_tmp_file_size.first); } else { - ms_dbg_a(m_transaction, 4, - "Adding request argument (BODY): name \"" + - m->m_name + "\", value \"" + m->m_value + "\""); + ms_dbg_a(m_transaction, 4, fmt::format("Adding request argument (BODY): " \ + "name \"{}\", value \"{}\"", m->m_name, m->m_value)); m_transaction->m_variableArgs.set(m->m_name, m->m_value, offset + m->m_valueOffset); m_transaction->m_variableArgsPost.set(m->m_name, m->m_value, @@ -1306,33 +1276,34 @@ bool Multipart::init(std::string *error) { if (m_header.empty()) { m_flag_error = true; - ms_dbg_a(m_transaction, 4, - "Multipart: Content-Type header not available."); - error->assign("Multipart: Content-Type header not available."); + const auto err = "Multipart: Content-Type header not available."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } if (m_header.size() > 1024) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (length)."); - error->assign("Multipart: Invalid boundary in C-T (length)."); + const auto err = "Multipart: Invalid boundary in C-T (length)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } if (strncasecmp(m_header.c_str(), "multipart/form-data", 19) != 0) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, "Multipart: Invalid MIME type."); - error->assign("Multipart: Invalid MIME type."); + const auto err = "Multipart: Invalid MIME type."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } /* Count how many times the word "boundary" appears in the C-T header. */ if (count_boundary_params(m_header) > 1) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Multiple boundary parameters in C-T."); - error->assign("Multipart: Multiple boundary parameters in C-T."); + const auto err = "Multipart: Multiple boundary parameters in C-T."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1352,11 +1323,9 @@ bool Multipart::init(std::string *error) { seen_semicolon = 1; /* It is OK to have one semicolon. */ } else { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T " \ - "(malformed)."); - error->assign("Multipart: Invalid boundary in C-T " \ - "(malformed)."); + const auto err = "Multipart: Invalid boundary in C-T (malformed)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } } @@ -1370,9 +1339,9 @@ bool Multipart::init(std::string *error) { b = strchr(m_boundary_tmp + 8, '='); if (b == NULL) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (malformed)."); - error->assign("Multipart: Invalid boundary in C-T (malformed)."); + const auto err = "Multipart: Invalid boundary in C-T (malformed)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1387,11 +1356,10 @@ bool Multipart::init(std::string *error) { m_flag_boundary_whitespace = 1; } else { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T " \ - "(parameter name)."); - error->assign("Multipart: Invalid boundary in C-T " \ - "(parameter name)."); + const auto err = "Multipart: Invalid boundary in C-T " \ + "(parameter name)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } } @@ -1420,9 +1388,9 @@ bool Multipart::init(std::string *error) { if ((*b == '"') || ((len >= 2) && (*(b + len - 1) == '"'))) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (quote)."); - error->assign("Multipart: Invalid boundary in C-T (quote)."); + const auto err = "Multipart: Invalid boundary in C-T (quote)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1437,9 +1405,9 @@ bool Multipart::init(std::string *error) { /* Case-insensitive test for the string "boundary" in the boundary. */ if (count_boundary_params(m_boundary) != 0) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (content)."); - error->assign("Multipart: Invalid boundary in C-T (content)."); + const auto err = "Multipart: Invalid boundary in C-T (content)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1456,9 +1424,9 @@ bool Multipart::init(std::string *error) { /* Validate the characters used in the boundary. */ if (boundary_characters_valid(m_boundary.c_str()) != 1) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (characters)."); - error->assign("Multipart: Invalid boundary in C-T (characters)."); + const auto err = "Multipart: Invalid boundary in C-T (characters)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1469,9 +1437,9 @@ bool Multipart::init(std::string *error) { if (m_boundary.size() == 0) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (empty)."); - error->assign("Multipart: Invalid boundary in C-T (empty)."); + const auto err = "Multipart: Invalid boundary in C-T (empty)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } } else { /* Could not find boundary in the C-T header. */ @@ -1480,15 +1448,15 @@ bool Multipart::init(std::string *error) { /* Test for case-insensitive boundary. Allowed by the RFC but * highly unusual. */ if (count_boundary_params(m_header) > 0) { - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary in C-T (case sensitivity)."); - error->assign("Multipart: Invalid boundary in C-T " \ - "(case sensitivity)."); + const auto err = "Multipart: Invalid boundary in C-T (case sensitivity)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } - ms_dbg_a(m_transaction, 4, "Multipart: Boundary not found in C-T."); - error->assign("Multipart: Boundary not found in C-T."); + const auto err = "Multipart: Boundary not found in C-T."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1512,9 +1480,9 @@ bool Multipart::process(const std::string& data, std::string *error, if (m_is_complete) { m_flag_data_before = true; - ms_dbg_a(m_transaction, 4, - "Multipart: Ignoring data after last boundary (received " \ - + std::to_string(data.size()) + " bytes)"); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Ignoring data after last boundary (received {} bytes)", + data.size())); return true; } @@ -1592,12 +1560,10 @@ bool Multipart::process(const std::string& data, std::string *error, if (m_is_complete != 0) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary " \ - "(final duplicate)."); - - error->assign("Multipart: Invalid boundary " \ - "(final duplicate)."); + const auto err = "Multipart: Invalid boundary " \ + "(final duplicate)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } } @@ -1628,11 +1594,10 @@ bool Multipart::process(const std::string& data, std::string *error, } else { /* error */ m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary: " \ - + std::string(m_buf)); - error->assign("Multipart: Invalid boundary: " \ - + std::string(m_buf)); + const auto err = fmt::format("Multipart: " \ + "Invalid boundary: {}", m_buf); + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } } @@ -1648,9 +1613,9 @@ bool Multipart::process(const std::string& data, std::string *error, && (strncmp(m_buf + 3, m_boundary.c_str(), m_boundary.size()) == 0)) { m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary (quotes)."); - error->assign("Multipart: Invalid boundary (quotes)."); + const auto err = "Multipart: Invalid boundary (quotes)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1665,10 +1630,9 @@ bool Multipart::process(const std::string& data, std::string *error, m_boundary.size()) == 0)) { /* Found whitespace in front of a boundary. */ m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Invalid boundary (whitespace)."); - error->assign("Multipart: Invalid boundary " \ - "(whitespace)."); + const auto err = "Multipart: Invalid boundary (whitespace)."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1709,13 +1673,11 @@ bool Multipart::process(const std::string& data, std::string *error, * MULTIPART_BUF_SIZE bytes */ m_flag_error = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Part header line over " \ - + std::to_string(MULTIPART_BUF_SIZE) \ - + " bytes long"); - error->assign("Multipart: Part header line over " \ - + std::to_string(MULTIPART_BUF_SIZE) \ - + " bytes long"); + const auto err = fmt::format("Multipart: " \ + "Part header line over {} bytes long", + MULTIPART_BUF_SIZE); + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -1766,9 +1728,9 @@ bool Multipart::process(const std::string& data, std::string *error, if ((m_is_complete) && (inleft != 0)) { m_flag_data_after = 1; - ms_dbg_a(m_transaction, 4, - "Multipart: Ignoring data after last boundary (" \ - + std::to_string(inleft) + "bytes left)"); + ms_dbg_a(m_transaction, 4, fmt::format("Multipart: " \ + "Ignoring data after last boundary ({} bytes left)", + inleft)); return true; } } diff --git a/src/request_body_processor/xml.cc b/src/request_body_processor/xml.cc index 6d8a5ec13b..5f237fb449 100644 --- a/src/request_body_processor/xml.cc +++ b/src/request_body_processor/xml.cc @@ -18,6 +18,7 @@ #include #include #include +#include namespace modsecurity { @@ -94,9 +95,9 @@ bool XML::processChunk(const char *buf, unsigned int size, buf, size, "body.xml"); if (m_data.parsing_ctx == NULL) { - ms_dbg_a(m_transaction, 4, - "XML: Failed to create parsing context."); - error->assign("XML: Failed to create parsing context."); + const auto err = "XML: Failed to create parsing context."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -108,8 +109,9 @@ bool XML::processChunk(const char *buf, unsigned int size, /* Not a first invocation. */ xmlParseChunk(m_data.parsing_ctx, buf, size, 0); if (m_data.parsing_ctx->wellFormed != 1) { - error->assign("XML: Failed to create parsing context."); - ms_dbg_a(m_transaction, 4, "XML: Failed parsing document."); + const auto err = "XML: Failed to create parsing context."; + ms_dbg_a(m_transaction, 4, err); + error->assign(err); return false; } @@ -130,12 +132,13 @@ bool XML::complete(std::string *error) { /* Clean up everything else. */ xmlFreeParserCtxt(m_data.parsing_ctx); m_data.parsing_ctx = NULL; - ms_dbg_a(m_transaction, 4, "XML: Parsing complete (well_formed " \ - + std::to_string(m_data.well_formed) + ")."); + ms_dbg_a(m_transaction, 4, fmt::format("XML: Parsing complete " \ + "(well_formed {}).", m_data.well_formed)); if (m_data.well_formed != 1) { - error->assign("XML: Failed parsing document."); - ms_dbg_a(m_transaction, 4, "XML: Failed parsing document."); + const auto err = "XML: Failed parsing document."; + error->assign(err); + ms_dbg_a(m_transaction, 4, err); return false; } } diff --git a/src/rule_message.cc b/src/rule_message.cc index 7c021d17eb..ae19dffeee 100644 --- a/src/rule_message.cc +++ b/src/rule_message.cc @@ -15,6 +15,8 @@ #include "modsecurity/rule_message.h" +#include + #include "modsecurity/rules_set.h" #include "modsecurity/modsecurity.h" #include "modsecurity/transaction.h" @@ -24,42 +26,38 @@ namespace modsecurity { std::string RuleMessage::_details(const RuleMessage &rm) { - std::string msg; - - msg.append(" [file \"" + rm.m_rule.getFileName() + "\"]"); - msg.append(" [line \"" + std::to_string(rm.m_rule.getLineNumber()) + "\"]"); - msg.append(" [id \"" + std::to_string(rm.m_rule.m_ruleId) + "\"]"); - msg.append(" [rev \"" + utils::string::toHexIfNeeded(rm.m_rule.m_rev, true) + "\"]"); - msg.append(" [msg \"" + rm.m_message + "\"]"); - msg.append(" [data \"" + utils::string::toHexIfNeeded(utils::string::limitTo(200, rm.m_data), true) + "\"]"); - msg.append(" [severity \"" + - std::to_string(rm.m_severity) + "\"]"); - msg.append(" [ver \"" + utils::string::toHexIfNeeded(rm.m_rule.m_ver, true) + "\"]"); - msg.append(" [maturity \"" + std::to_string(rm.m_rule.m_maturity) + "\"]"); - msg.append(" [accuracy \"" + std::to_string(rm.m_rule.m_accuracy) + "\"]"); + auto msg = fmt::format(R"( [file "{}"] [line "{}"] [id "{}"] [rev "{}"] [msg "{}"])" \ + R"( [data "{}"] [severity "{}"] [ver "{}"] [maturity "{}"] [accuracy "{}"])", + rm.m_rule.getFileName(), + rm.m_rule.getLineNumber(), + rm.m_rule.m_ruleId, + utils::string::toHexIfNeeded(rm.m_rule.m_rev, true), + rm.m_message, + utils::string::toHexIfNeeded(utils::string::limitTo(200, rm.m_data), true), + rm.m_severity, + utils::string::toHexIfNeeded(rm.m_rule.m_ver, true), + rm.m_rule.m_maturity, + rm.m_rule.m_accuracy); for (const auto &a : rm.m_tags) { - msg.append(" [tag \"" + utils::string::toHexIfNeeded(a, true) + "\"]"); + msg.append(fmt::format(R"( [tag "{}"])", utils::string::toHexIfNeeded(a, true))); } - msg.append(" [hostname \"" + rm.m_transaction.m_requestHostName \ - + "\"]"); - msg.append(" [uri \"" + utils::string::limitTo(200, rm.m_transaction.m_uri_no_query_string_decoded) + "\"]"); - msg.append(" [unique_id \"" + rm.m_transaction.m_id + "\"]"); - msg.append(" [ref \"" + utils::string::limitTo(200, rm.m_reference) + "\"]"); + msg.append(fmt::format(R"( [hostname "{}"] [uri "{}"] [unique_id "{}"] [ref "{}"])", + rm.m_transaction.m_requestHostName, + utils::string::limitTo(200, rm.m_transaction.m_uri_no_query_string_decoded), + rm.m_transaction.m_id, + utils::string::limitTo(200, rm.m_reference))); return msg; } std::string RuleMessage::_errorLogTail(const RuleMessage &rm) { - std::string msg; - - msg.append("[hostname \"" + rm.m_transaction.m_serverIpAddress + "\"]"); - msg.append(" [uri \"" + utils::string::limitTo(200, rm.m_transaction.m_uri_no_query_string_decoded) + "\"]"); - msg.append(" [unique_id \"" + rm.m_transaction.m_id + "\"]"); - - return msg; + return fmt::format(R"([hostname "{}"] [uri "{}"] [unique_id "{}"])", + rm.m_transaction.m_serverIpAddress, + utils::string::limitTo(200, rm.m_transaction.m_uri_no_query_string_decoded), + rm.m_transaction.m_id); } @@ -68,27 +66,24 @@ std::string RuleMessage::log(const RuleMessage &rm, int props, int code) { msg.reserve(2048); if (props & ClientLogMessageInfo) { - msg.append("[client " + rm.m_transaction.m_clientIpAddress + "] "); + msg.append(fmt::format(R"([client {}])", rm.m_transaction.m_clientIpAddress)); } if (rm.m_isDisruptive) { - msg.append("ModSecurity: Access denied with code "); - if (code == -1) { - msg.append("%d"); - } else { - msg.append(std::to_string(code)); - } - msg.append(" (phase "); - msg.append(std::to_string(rm.getPhase()) + "). "); + msg.append( + (code == -1) ? + fmt::format("ModSecurity: Access denied with code %d (phase {})", + rm.getPhase()) : + fmt::format("ModSecurity: Access denied with code {} (phase {})", + code, rm.getPhase())); } else { msg.append("ModSecurity: Warning. "); } - msg.append(rm.m_match); - msg.append(_details(rm)); + msg.append(fmt::format("{}{}", rm.m_match, _details(rm))); if (props & ErrorLogTailLogMessageInfo) { - msg.append(" " + _errorLogTail(rm)); + msg.append(fmt::format(" {}", _errorLogTail(rm))); } return modsecurity::utils::string::toHexIfNeeded(msg); diff --git a/src/rule_script.cc b/src/rule_script.cc index ca4e5ae8bc..58adac96d9 100644 --- a/src/rule_script.cc +++ b/src/rule_script.cc @@ -15,6 +15,8 @@ #include "src/rule_script.h" +#include + namespace modsecurity { @@ -25,7 +27,8 @@ bool RuleScript::init(std::string *err) { bool RuleScript::evaluate(Transaction *trans, RuleMessage &ruleMessage) { - ms_dbg_a(trans, 4, " Executing script: " + m_name + "."); + ms_dbg_a(trans, 4, fmt::format(" Executing script: {}.", + m_name)); bool containsDisruptive = false; diff --git a/src/rule_unconditional.cc b/src/rule_unconditional.cc index 0bbef40e80..e0c587d9ad 100644 --- a/src/rule_unconditional.cc +++ b/src/rule_unconditional.cc @@ -15,6 +15,8 @@ #include "modsecurity/rule_unconditional.h" +#include + namespace modsecurity { @@ -26,8 +28,9 @@ bool RuleUnconditional::evaluate(Transaction *trans, // FIXME: This needs to be romeved on the runtime exeption review. bool containsBlock = false; - ms_dbg_a(trans, 4, "(Rule: " + std::to_string(m_ruleId) \ - + ") Executing unconditional rule..."); + ms_dbg_a(trans, 4, fmt::format("(Rule: {}) " \ + "Executing unconditional rule...", + m_ruleId)); executeActionsIndependentOfChainedRuleResult(trans, &containsBlock, ruleMessage); diff --git a/src/rule_with_actions.cc b/src/rule_with_actions.cc index 0595b04b65..134fd22627 100644 --- a/src/rule_with_actions.cc +++ b/src/rule_with_actions.cc @@ -26,6 +26,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "src/operators/operator.h" @@ -203,8 +204,8 @@ void RuleWithActions::executeActionsIndependentOfChainedRuleResult(Transaction * bool *containsBlock, RuleMessage &ruleMessage) { for (actions::SetVar *a : m_actionsSetVar) { - ms_dbg_a(trans, 4, "Running [independent] (non-disruptive) " \ - "action: " + *a->m_name.get()); + ms_dbg_a(trans, 4, fmt::format("Running [independent] (non-disruptive) " \ + "action: {}", *a->m_name.get())); a->evaluate(this, trans); } @@ -219,8 +220,8 @@ void RuleWithActions::executeActionsIndependentOfChainedRuleResult(Transaction * ms_dbg_a(trans, 9, "Rule contains a `block' action"); *containsBlock = true; } else if (*a->m_name.get() == "setvar") { - ms_dbg_a(trans, 4, "Running [independent] (non-disruptive) " \ - "action: " + *a->m_name.get()); + ms_dbg_a(trans, 4, fmt::format("Running [independent] (non-disruptive) " \ + "action: {}", *a->m_name.get())); a->evaluate(this, trans, ruleMessage); } } @@ -257,8 +258,8 @@ void RuleWithActions::executeActionsAfterFullMatch(Transaction *trans, } for (actions::Tag *a : this->m_actionsTag) { - ms_dbg_a(trans, 4, "Running (non-disruptive) action: " \ - + *a->m_name.get()); + ms_dbg_a(trans, 4, fmt::format("Running (non-disruptive) action: {}", + *a->m_name.get())); a->evaluate(this, trans, ruleMessage); } @@ -300,27 +301,29 @@ void RuleWithActions::executeAction(Transaction *trans, bool containsBlock, RuleMessage &ruleMessage, Action *a, bool defaultContext) { if (a->isDisruptive() == false && *a->m_name.get() != "block") { - ms_dbg_a(trans, 9, "Running " \ - "action: " + *a->m_name.get()); + ms_dbg_a(trans, 9, fmt::format("Running action: {}", + *a->m_name.get())); a->evaluate(this, trans, ruleMessage); return; } if (defaultContext && !containsBlock) { - ms_dbg_a(trans, 4, "Ignoring action: " + *a->m_name.get() + \ - " (rule does not cotains block)"); + ms_dbg_a(trans, 4, fmt::format("Ignoring action: {}" \ + " (rule does not cotains block)", + *a->m_name.get())); return; } if (trans->getRuleEngineState() == RulesSet::EnabledRuleEngine) { - ms_dbg_a(trans, 4, "Running (disruptive) action: " + *a->m_name.get() + \ - "."); + ms_dbg_a(trans, 4, fmt::format("Running (disruptive) action: {}.", + *a->m_name.get())); a->evaluate(this, trans, ruleMessage); return; } - ms_dbg_a(trans, 4, "Not running any disruptive action (or block): " \ - + *a->m_name.get() + ". SecRuleEngine is not On."); + ms_dbg_a(trans, 4, fmt::format("Not running any disruptive action " \ + "(or block): {}. SecRuleEngine is not On.", + *a->m_name.get())); } @@ -344,10 +347,8 @@ inline void RuleWithActions::executeTransformation( path.append("," + *a.m_name.get()); } - ms_dbg_a(trans, 9, " T (" + \ - std::to_string(nth) + ") " + \ - *a.m_name.get() + ": \"" + \ - utils::string::limitTo(80, value) +"\""); + ms_dbg_a(trans, 9, fmt::format(" T ({}) {}: \"{}\"", + nth, *a.m_name.get(), utils::string::limitTo(80, value))); } void RuleWithActions::executeTransformations( @@ -429,9 +430,9 @@ void RuleWithActions::executeTransformations( } if (m_containsMultiMatchAction == true) { - ms_dbg_a(trans, 9, "multiMatch is enabled. " \ - + std::to_string(ret.size()) + \ - " values to be tested."); + ms_dbg_a(trans, 9, fmt::format("multiMatch is enabled. " \ + "{} values to be tested.", + ret.size())); } if (!m_containsMultiMatchAction) { diff --git a/src/rule_with_operator.cc b/src/rule_with_operator.cc index 0333529b30..1c224a2eb9 100644 --- a/src/rule_with_operator.cc +++ b/src/rule_with_operator.cc @@ -24,6 +24,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "src/operators/operator.h" @@ -110,9 +111,10 @@ bool RuleWithOperator::executeOperatorAt(Transaction *trans, const std::string & #endif bool ret; - ms_dbg_a(trans, 9, "Target value: \"" + utils::string::limitTo(80, - utils::string::toHexIfNeeded(value)) \ - + "\" (Variable: " + key + ")"); + ms_dbg_a(trans, 9, fmt::format("Target value: \"{}\" (Variable: {})", + utils::string::limitTo(80, + utils::string::toHexIfNeeded(value)), + key)); ret = this->m_operator->evaluateInternal(trans, this, value, ruleMessage); @@ -124,8 +126,8 @@ bool RuleWithOperator::executeOperatorAt(Transaction *trans, const std::string & end = clock(); elapsed_s = static_cast(end - begin) / CLOCKS_PER_SEC; - ms_dbg_a(trans, 5, "Operator completed in " + \ - std::to_string(elapsed_s) + " seconds"); + ms_dbg_a(trans, 5, fmt::format("Operator completed in {} seconds", + elapsed_s)); #endif return ret; } @@ -176,7 +178,7 @@ inline void RuleWithOperator::getFinalVars(variables::Variables *vars, } if (std::find_if(trans->m_ruleRemoveTargetById.begin(), trans->m_ruleRemoveTargetById.end(), - [&, variable, this](std::pair &m) -> bool { + [&, variable, this](const auto &m) -> bool { return m.first == m_ruleId && m.second == *variable->m_fullName.get(); }) != trans->m_ruleRemoveTargetById.end()) { @@ -184,8 +186,7 @@ inline void RuleWithOperator::getFinalVars(variables::Variables *vars, } if (std::find_if(trans->m_ruleRemoveTargetByTag.begin(), trans->m_ruleRemoveTargetByTag.end(), - [&, variable, trans, this]( - std::pair &m) -> bool { + [&, variable, trans, this](const auto &m) -> bool { return containsTag(m.first, trans) && m.second == *variable->m_fullName.get(); }) != trans->m_ruleRemoveTargetByTag.end()) { @@ -219,16 +220,18 @@ bool RuleWithOperator::evaluate(Transaction *trans, if (m_ruleId != i) { continue; } - ms_dbg_a(trans, 9, "Rule id: " + std::to_string(m_ruleId) + - " was skipped due to a ruleRemoveById action..."); + ms_dbg_a(trans, 9, fmt::format("Rule id: {} was skipped " \ + "due to a ruleRemoveById action...", + m_ruleId)); return true; } for (const auto &i : trans->m_ruleRemoveByIdRange) { if (!(i.first <= m_ruleId && i.second >= m_ruleId)) { continue; } - ms_dbg_a(trans, 9, "Rule id: " + std::to_string(m_ruleId) + - " was skipped due to a ruleRemoveById action..."); + ms_dbg_a(trans, 9, fmt::format("Rule id: {} was skipped " \ + "due to a ruleRemoveById action...", + m_ruleId)); return true; } @@ -236,22 +239,19 @@ bool RuleWithOperator::evaluate(Transaction *trans, eparam = m_operator->m_string->evaluate(trans); if (m_operator->m_string->containsMacro()) { - eparam = "\"" + eparam + "\" Was: \"" \ - + m_operator->m_string->evaluate(NULL) + "\""; + eparam = fmt::format("\"{}\" Was \"{}\"", + eparam, m_operator->m_string->evaluate(NULL)); } else { - eparam = "\"" + eparam + "\""; + eparam = fmt::format("\"{}\"", eparam); } - ms_dbg_a(trans, 4, "(Rule: " + std::to_string(m_ruleId) \ - + ") Executing operator \"" + getOperatorName() \ - + "\" with param " \ - + eparam \ - + " against " \ - + variables + "."); + ms_dbg_a(trans, 4, fmt::format("(Rule: {}) " \ + "Executing operator \"{}\" with param {} against {}.", + m_ruleId, getOperatorName(), eparam, + variables->to_string())); } else { - ms_dbg_a(trans, 4, "(Rule: " + std::to_string(m_ruleId) \ - + ") Executing operator \"" + getOperatorName() \ - + " against " \ - + variables + "."); + ms_dbg_a(trans, 4, fmt::format("(Rule: {})" \ + "Executing operator \"{}\" against {}.", + m_ruleId, getOperatorName(), variables->to_string())); } diff --git a/src/rules_exceptions.cc b/src/rules_exceptions.cc index 71cf28c223..43a44ade9d 100644 --- a/src/rules_exceptions.cc +++ b/src/rules_exceptions.cc @@ -16,6 +16,7 @@ #include "modsecurity/rules_exceptions.h" #include +#include #include "src/utils/string.h" #include "src/variables/variable.h" @@ -138,19 +139,19 @@ bool RulesExceptions::load(const std::string &a, std::string *error) { n1n = std::stoi(n1s); added = true; } catch (...) { - error->assign("Not a number: " + n1s); + error->assign(fmt::format("Not a number: ", n1s)); return false; } try { n2n = std::stoi(n2s); added = true; } catch (...) { - error->assign("Not a number: " + n2s); + error->assign(fmt::format("Not a number: ", n2s)); return false; } if (n1s > n2s) { - error->assign("Invalid range: " + b); + error->assign(fmt::format("Invalid range: ", b)); return false; } addRange(n1n, n2n); @@ -161,7 +162,7 @@ bool RulesExceptions::load(const std::string &a, std::string *error) { addNumber(num); added = true; } catch (...) { - error->assign("Not a number or range: " + b); + error->assign(fmt::format("Not a number or range: {}", b)); return false; } } @@ -171,7 +172,7 @@ bool RulesExceptions::load(const std::string &a, std::string *error) { return true; } - error->assign("Not a number or range: " + a); + error->assign(fmt::format("Not a number or range: {}", a)); return false; } diff --git a/src/rules_set.cc b/src/rules_set.cc index 19f31d8952..c83244510e 100644 --- a/src/rules_set.cc +++ b/src/rules_set.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include "modsecurity/rules_set.h" #include "modsecurity/modsecurity.h" @@ -113,8 +114,8 @@ int RulesSet::evaluate(int phase, Transaction *t) { Rules *rules = m_rulesSetPhases[phase]; - ms_dbg_a(t, 9, "This phase consists of " \ - + std::to_string(rules->size()) + " rule(s)."); + ms_dbg_a(t, 9, fmt::format("This phase consists of {} rule(s).", + rules->size())); if (t->m_allowType == actions::disruptive::FromNowOnAllowType && phase != modsecurity::Phases::LoggingPhase) { @@ -137,36 +138,39 @@ int RulesSet::evaluate(int phase, Transaction *t) { // the shared pointer won't be used. auto rule = rules->at(i); if (t->isInsideAMarker() && !rule->isMarker()) { - ms_dbg_a(t, 9, "Skipped rule id '" + rule->getReference() \ - + "' due to a SecMarker: " + *t->getCurrentMarker()); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}' due to a " \ + "SecMarker: {}", + rule->getReference(), *t->getCurrentMarker())); } else if (rule->isMarker()) { rule->evaluate(t); } else if (t->m_skip_next > 0) { t->m_skip_next--; - ms_dbg_a(t, 9, "Skipped rule id '" + rule->getReference() \ - + "' due to a `skip' action. Still " + \ - std::to_string(t->m_skip_next) + " to be skipped."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}' due to a " \ + "`skip' action. Still {} to be skipped.", + rule->getReference(), t->m_skip_next)); } else if (t->m_allowType != actions::disruptive::NoneAllowType) { - ms_dbg_a(t, 9, "Skipped rule id '" + rule->getReference() \ - + "' as request trough the utilization of an `allow' action."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}' " \ + "as request trough the utilization of an `allow' action.", + rule->getReference())); } else { Rule *base = rule.get(); RuleWithActions *ruleWithActions = dynamic_cast(base); // FIXME: Those should be treated inside the rule itself if (ruleWithActions && m_exceptions.contains(ruleWithActions->m_ruleId)) { - ms_dbg_a(t, 9, "Skipped rule id '" + rule->getReference() \ - + "'. Removed by an SecRuleRemove directive."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}'. " \ + "Removed by an SecRuleRemove directive.", + rule->getReference())); continue; } bool remove_rule = false; if (ruleWithActions && m_exceptions.m_remove_rule_by_msg.empty() == false) { for (const auto &z : m_exceptions.m_remove_rule_by_msg) { if (ruleWithActions->containsMsg(z, t) == true) { - ms_dbg_a(t, 9, "Skipped rule id '" \ - + ruleWithActions->getReference() \ - + "'. Removed by a SecRuleRemoveByMsg directive."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}'. " \ + "Removed by a SecRuleRemoveByMsg directive.", + ruleWithActions->getReference())); remove_rule = true; break; } @@ -179,9 +183,9 @@ int RulesSet::evaluate(int phase, Transaction *t) { if (ruleWithActions && m_exceptions.m_remove_rule_by_tag.empty() == false) { for (const auto &z : m_exceptions.m_remove_rule_by_tag) { if (ruleWithActions->containsTag(z, t) == true) { - ms_dbg_a(t, 9, "Skipped rule id '" \ - + ruleWithActions->getReference() \ - + "'. Removed by a SecRuleRemoveByTag directive."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}'. " \ + "Removed by a SecRuleRemoveByTag directive.", + ruleWithActions->getReference())); remove_rule = true; break; } @@ -195,9 +199,9 @@ int RulesSet::evaluate(int phase, Transaction *t) { if (ruleWithActions) { for (const auto &z : t->m_ruleRemoveByTag) { if (ruleWithActions->containsTag(z, t) == true) { - ms_dbg_a(t, 9, "Skipped rule id '" \ - + ruleWithActions->getReference() \ - + "'. Skipped due to a ruleRemoveByTag action."); + ms_dbg_a(t, 9, fmt::format("Skipped rule id '{}'. " \ + "Skipped due to a ruleRemoveByTag action.", + ruleWithActions->getReference())); remove_rule = true; break; } diff --git a/src/rules_set_properties.cc b/src/rules_set_properties.cc index ab4bdeda4e..3ef18f63a8 100644 --- a/src/rules_set_properties.cc +++ b/src/rules_set_properties.cc @@ -14,6 +14,7 @@ */ #include +#include #include "modsecurity/rules_set_properties.h" #include "src/utils/string.h" @@ -61,24 +62,18 @@ void ConfigUnicodeMap::loadConfig(std::string f, double configCodePage, length = file_stream.tellg(); file_stream.seekg (0, file_stream.beg); } else { - std::stringstream ss; - ss << "Failed to open the unicode map file from: " << f << " "; - errg->assign(ss.str()); + errg->assign(fmt::format("Failed to open the unicode map file from: {}", f)); return; } if (length <= 0) { - std::stringstream ss; - ss << "Failed to open the unicode map file from: " << f << " "; - errg->assign(ss.str()); + errg->assign(fmt::format("Failed to open the unicode map file from: {}", f)); return; } buf = new char[length+1]; if (!buf) { - std::stringstream ss; - ss << "Failed to open the unicode map file from: " << f << " "; - errg->assign(ss.str()); + errg->assign(fmt::format("Failed to open the unicode map file from: {}", f)); return; } diff --git a/src/transaction.cc b/src/transaction.cc index 41ab1f5525..7081aed239 100644 --- a/src/transaction.cc +++ b/src/transaction.cc @@ -31,6 +31,7 @@ #include #include #include +#include #include "modsecurity/actions/action.h" #include "src/actions/disruptive/deny.h" @@ -371,12 +372,11 @@ bool Transaction::extractArguments(const std::string &orig, bool Transaction::addArgument(const std::string& orig, const std::string& key, const std::string& value, size_t offset) { - ms_dbg(4, "Adding request argument (" + orig + "): name \"" + \ - key + "\", value \"" + value + "\""); + ms_dbg(4, fmt::format(R"(Adding request argument ({}): name "{}", value "{}")", orig, key, value)); if (m_rules->m_argumentsLimit.m_set && m_variableArgs.size() >= m_rules->m_argumentsLimit.m_value) { - ms_dbg(4, "Skipping request argument, over limit (" + std::to_string(m_rules->m_argumentsLimit.m_value) + ")") + ms_dbg(4, fmt::format("Skipping request argument, over limit ({})", m_rules->m_argumentsLimit.m_value)) return false; } @@ -429,6 +429,8 @@ int Transaction::processURI(const char *uri, const char *method, ms_dbg(4, "Starting phase URI. (SecRules 0 + 1/2)"); + const auto method_size = strlen(method) + 1; + m_httpVersion = http_version; m_uri = uri; std::string uri_s(uri); @@ -437,42 +439,43 @@ int Transaction::processURI(const char *uri, const char *method, // - m_uri // - m_variableRequestURIRaw // - m_variableRequestLine - size_t pos_raw_fragment = uri_s.find("#"); + const auto pos_raw_fragment = uri_s.find("#"); if (pos_raw_fragment != std::string::npos) { uri_s = uri_s.substr(0, pos_raw_fragment); } - size_t pos_raw_query = uri_s.find("?"); + const auto pos_raw_query = uri_s.find("?"); - std::string path_info_raw; - if (pos_raw_query == std::string::npos) { - path_info_raw = std::string(uri_s, 0); - } else { - path_info_raw = std::string(uri_s, 0, pos_raw_query); - } - std::string path_info = utils::uri_decode(path_info_raw); + const auto path_info_raw = + (pos_raw_query == std::string::npos) + ? uri_s + : std::string(uri_s, 0, pos_raw_query); + + const auto path_info = utils::uri_decode(path_info_raw); m_uri_decoded = utils::uri_decode(uri_s); - size_t var_size = pos_raw_query; + auto var_size = pos_raw_query; m_variableRequestMethod.set(method, 0); - std::string requestLine(std::string(method) + " " + std::string(uri)); - m_variableRequestLine.set(requestLine \ - + " HTTP/" + std::string(http_version), m_variableOffset); + const auto requestLine = fmt::format("{} {}", method, uri); + m_variableRequestLine.set( + fmt::format("{} HTTP/{}", requestLine, http_version), + m_variableOffset); - m_variableRequestProtocol.set("HTTP/" + std::string(http_version), + m_variableRequestProtocol.set( + fmt::format("HTTP/{}", http_version), m_variableOffset + requestLine.size() + 1); m_uri_no_query_string_decoded = path_info; if (pos_raw_query != std::string::npos) { - std::string qry = std::string(uri_s, pos_raw_query + 1, + const auto qry = std::string(uri_s, pos_raw_query + 1, uri_s.length() - (pos_raw_query + 1)); m_variableQueryString.set(qry, pos_raw_query + 1 - + std::string(method).size() + 1); + + method_size); } @@ -480,39 +483,39 @@ int Transaction::processURI(const char *uri, const char *method, var_size = uri_s.size(); } - m_variablePathInfo.set(path_info, m_variableOffset + strlen(method) + - 1, var_size); + m_variablePathInfo.set(path_info, m_variableOffset + method_size, + var_size); m_variableRequestFilename.set(path_info, m_variableOffset + - strlen(method) + 1, var_size); + method_size, var_size); - size_t offset = path_info.find_last_of("/\\"); + const auto offset = path_info.find_last_of("/\\"); if (offset != std::string::npos && path_info.length() > offset + 1) { - std::string basename = std::string(path_info, offset + 1, + const auto basename = std::string(path_info, offset + 1, path_info.length() - (offset + 1)); m_variableRequestBasename.set(basename, m_variableOffset + - strlen(method) + 1 + offset + 1); + method_size + offset + 1); } m_variableOffset = m_variableRequestLine.m_value.size(); - std::string parsedURI = m_uri_decoded; + auto parsedURI = m_uri_decoded; // The more popular case is without domain if (!m_uri_decoded.empty() && m_uri_decoded[0] != '/') { bool fullDomain = true; - size_t scheme = m_uri_decoded.find(":")+1; + const auto scheme = m_uri_decoded.find(":")+1; if (scheme == std::string::npos) { fullDomain = false; } // Searching with a pos of -1 is undefined we also shortcut if (scheme != std::string::npos && fullDomain == true) { // Assuming we found a colon make sure its followed - size_t netloc = m_uri_decoded.find("//", scheme) + 2; + const auto netloc = m_uri_decoded.find("//", scheme) + 2; if (netloc == std::string::npos || (netloc != scheme + 2)) { fullDomain = false; } if (netloc != std::string::npos && fullDomain == true) { - size_t path = m_uri_decoded.find("/", netloc); + const auto path = m_uri_decoded.find("/", netloc); if (path != std::string::npos) { parsedURI = m_uri_decoded.substr(path); } @@ -520,9 +523,9 @@ int Transaction::processURI(const char *uri, const char *method, } } - m_variableRequestURI.set(parsedURI, std::string(method).size() + 1, + m_variableRequestURI.set(parsedURI, method_size, uri_s.size()); - m_variableRequestURIRaw.set(uri, std::string(method).size() + 1); + m_variableRequestURIRaw.set(uri, method_size); if (m_variableQueryString.m_value.empty() == false) { extractArguments("GET", m_variableQueryString.m_value, @@ -991,7 +994,7 @@ int Transaction::requestBodyFromFile(const char *path) { std::string str; if (request_body.is_open() == false) { - ms_dbg(3, "Failed to open request body at: " + std::string(path)); + ms_dbg(3, fmt::format("Failed to open request body at: {}", path)); return false; } @@ -1009,9 +1012,8 @@ int Transaction::requestBodyFromFile(const char *path) { const char *buf = str.c_str(); int len = request_body.tellg(); - ms_dbg(9, "Adding request body: " + std::to_string(len) + " bytes. " \ - "Limit set to: " - + std::to_string(this->m_rules->m_requestBodyLimit.m_value)); + ms_dbg(9, fmt::format("Adding request body: {} bytes. Limit set to: {}", + len, this->m_rules->m_requestBodyLimit.m_value)); return appendRequestBody(reinterpret_cast(buf), len); } @@ -1019,9 +1021,8 @@ int Transaction::requestBodyFromFile(const char *path) { int Transaction::appendRequestBody(const unsigned char *buf, size_t len) { int current_size = this->m_requestBody.tellp(); - ms_dbg(9, "Appending request body: " + std::to_string(len) + " bytes. " \ - "Limit set to: " - + std::to_string(this->m_rules->m_requestBodyLimit.m_value)); + ms_dbg(9, fmt::format("Appending request body: {} bytes. Limit set to: {}", + len, this->m_rules->m_requestBodyLimit.m_value)); if (this->m_rules->m_requestBodyLimit.m_value > 0 && this->m_rules->m_requestBodyLimit.m_value < len + current_size) { @@ -1213,25 +1214,24 @@ int Transaction::processResponseBody() { } if (m_rules->m_secResponseBodyAccess != RulesSetProperties::TrueConfigBoolean) { - ms_dbg(4, "Response body is disabled, returning... " + std::to_string(m_rules->m_secResponseBodyAccess)); + ms_dbg(4, fmt::format("Response body is disabled, returning... ", + (int)m_rules->m_secResponseBodyAccess)); return true; } - const std::set &bi = \ - m_rules->m_responseBodyTypeToBeInspected.m_value; - auto t = bi.find(m_variableResponseContentType.m_value); + const auto &bi = m_rules->m_responseBodyTypeToBeInspected.m_value; + const auto t = bi.find(m_variableResponseContentType.m_value); if (t == bi.end() && m_rules->m_responseBodyTypeToBeInspected.m_set == true) { - ms_dbg(5, "Response Content-Type is " \ - + m_variableResponseContentType.m_value \ - + ". It is not marked to be inspected."); - std::string validContetTypes(""); - for (std::set::iterator i = bi.begin(); - i != bi.end(); ++i) { - validContetTypes.append(*i + " "); + ms_dbg(5, fmt::format("Response Content-Type is {}" \ + ". It is not marked to be inspected.", + m_variableResponseContentType.m_value)); + std::string validContetTypes; + for (const auto &s : bi) { + validContetTypes.append(s + " "); } - ms_dbg(8, "Content-Type(s) marked to be inspected: " \ - + validContetTypes); + ms_dbg(8, fmt::format("Content-Type(s) marked to be inspected: {}", + validContetTypes)); return true; } if (m_variableOutboundDataError.m_value.empty() == true) { @@ -1272,16 +1272,16 @@ int Transaction::appendResponseBody(const unsigned char *buf, size_t len) { this->m_rules->m_responseBodyTypeToBeInspected.m_value; auto t = bi.find(m_variableResponseContentType.m_value); if (t == bi.end() && bi.empty() == false) { - ms_dbg(4, "Not appending response body. " \ - "Response Content-Type is " \ - + m_variableResponseContentType.m_value \ - + ". It is not marked to be inspected."); + ms_dbg(4, fmt::format("Not appending response body. " \ + "Response Content-Type is {}. " \ + "It is not marked to be inspected.", + m_variableResponseContentType.m_value)); return true; } - ms_dbg(9, "Appending response body: " + std::to_string(len + current_size) - + " bytes. Limit set to: " + - std::to_string(this->m_rules->m_responseBodyLimit.m_value)); + ms_dbg(9, fmt::format("Appending response body: {} bytes." \ + "Limit set to: {}", len + current_size, + this->m_rules->m_responseBodyLimit.m_value)); if (this->m_rules->m_responseBodyLimit.m_value > 0 && this->m_rules->m_responseBodyLimit.m_value < len + current_size) { @@ -1410,8 +1410,8 @@ int Transaction::processLogging() { if (!this->m_auditLogModifier.empty()) { ms_dbg(4, "There was an audit log modifier for this transaction."); std::list>::iterator it; - ms_dbg(7, "AuditLog parts before modification(s): " + - std::to_string(parts) + "."); + ms_dbg(7, fmt::format("AuditLog parts before modification(s): {}.", + parts)); for (it = m_auditLogModifier.begin(); it != m_auditLogModifier.end(); ++it) { std::pair p = *it; diff --git a/src/utils/https_client.cc b/src/utils/https_client.cc index f413e8ca07..6bfbbe1fae 100644 --- a/src/utils/https_client.cc +++ b/src/utils/https_client.cc @@ -32,6 +32,7 @@ #include #include +#include #include "modsecurity/modsecurity.h" #include "src/unique_id.h" @@ -67,8 +68,8 @@ void HttpsClient::setRequestType(const std::string& requestType) { bool HttpsClient::download(const std::string &uri) { CURL *curl; CURLcode res; - std::string uniqueId = "ModSec-unique-id: " + UniqueId::uniqueId(); - std::string status = "ModSec-status: " + std::to_string(MODSECURITY_VERSION_NUM); + const auto uniqueId = fmt::format("ModSec-unique-id: {}", UniqueId::uniqueId()); + const auto status = fmt::format("ModSec-status: {}", MODSECURITY_VERSION_NUM); curl = curl_easy_init(); if (!curl) { @@ -83,7 +84,7 @@ bool HttpsClient::download(const std::string &uri) { headers_chunk = curl_slist_append(headers_chunk, status.c_str()); if (m_requestType.empty() == false) { - std::string hdr = "Content-Type: " + m_requestType; + const auto hdr = fmt::format("Content-Type: {}", m_requestType); headers_chunk = curl_slist_append(headers_chunk, hdr.c_str()); } diff --git a/src/utils/ip_tree.cc b/src/utils/ip_tree.cc index 124bc47f30..5223354322 100644 --- a/src/utils/ip_tree.cc +++ b/src/utils/ip_tree.cc @@ -27,6 +27,7 @@ #include #include +#include #include "src/utils/geo_lookup.h" #include "src/utils/https_client.h" @@ -120,7 +121,7 @@ bool IpTree::addFromFile(const std::string& file, std::string *error) { std::ifstream myfile(file, std::ios::in); if (myfile.is_open() == false) { - error->assign("Failed to open file: " + file); + error->assign(fmt::format("Failed to open file: {}", file)); return false; } diff --git a/src/utils/shared_files.cc b/src/utils/shared_files.cc index 6982d0d6e9..4346205a56 100644 --- a/src/utils/shared_files.cc +++ b/src/utils/shared_files.cc @@ -20,6 +20,7 @@ #include #endif +#include namespace modsecurity { namespace utils { @@ -29,7 +30,7 @@ SharedFiles::handlers_map::iterator SharedFiles::add_new_handler( const std::string &fileName, std::string *error) { FILE *fp = fopen(fileName.c_str(), "a"); if (fp == 0) { - error->assign("Failed to open file: " + fileName); + error->assign(fmt::format("Failed to open file: {}", fileName)); return m_handlers.end(); } @@ -71,7 +72,7 @@ bool SharedFiles::open(const std::string& fileName, std::string *error) { } if (it == m_handlers.end()) { - error->assign("Not able to open: " + fileName); + error->assign(fmt::format("Not able to open: {}", fileName)); return false; } @@ -108,7 +109,7 @@ bool SharedFiles::write(const std::string& fileName, auto it = m_handlers.find(fileName); if (it == m_handlers.end()) { - error->assign("file is not open: " + fileName); + error->assign(fmt::format("file is not open: {}", fileName)); return false; } @@ -128,7 +129,7 @@ bool SharedFiles::write(const std::string& fileName, auto wrote = fwrite(msg.c_str(), 1, msg.size(), it->second.fp); if (wrote < msg.size()) { - error->assign("failed to write: " + fileName); + error->assign(fmt::format("failed to write: {}", fileName)); ret = false; } fflush(it->second.fp); diff --git a/src/utils/string.h b/src/utils/string.h index ca2967aa5f..4102e65128 100644 --- a/src/utils/string.h +++ b/src/utils/string.h @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ #include #include #include +#include #ifdef WIN32 #include "src/compat/msvc.h" @@ -88,14 +90,11 @@ inline std::string dash_if_empty(const std::string *str) { } -inline std::string limitTo(int amount, const std::string &str) { - std::string ret; - +inline std::string limitTo(const std::string::size_type amount, const std::string &str) { if (str.length() > amount) { - ret.assign(str, 0, amount); - ret = ret + " (" + std::to_string(str.length() - amount) + " " \ - "characters omitted)"; - return ret; + return fmt::format("{} ({} characters omitted)", + std::string_view{str.c_str(), amount}, + str.length() - amount); } return str; diff --git a/src/utils/system.cc b/src/utils/system.cc index f48afb7d6b..b7114649b3 100644 --- a/src/utils/system.cc +++ b/src/utils/system.cc @@ -32,6 +32,7 @@ #include #include #include +#include #if defined _MSC_VER #include "src/compat/msvc.h" @@ -194,8 +195,8 @@ bool createDir(const std::string& dir, int mode, std::string *error) { int ret = _mkdir(dir.c_str()); #endif if (ret != 0 && errno != EEXIST) { - error->assign("Not able to create directory: " + dir + ": " \ - + strerror(errno) + "."); + error->assign(fmt::format("Not able to create directory: {}: {}.", + dir, strerror(errno))); return false; } diff --git a/src/variables/variable.cc b/src/variables/variable.cc index caf8f6fd88..6247acfb2c 100644 --- a/src/variables/variable.cc +++ b/src/variables/variable.cc @@ -19,6 +19,7 @@ #include #include #include +#include #include "modsecurity/transaction.h" #include "src/utils/string.h" @@ -38,8 +39,8 @@ Variable::Variable(const std::string &name) if (a != std::string::npos) { m_collectionName = utils::string::toupper(std::string(m_name, 0, a)); m_name = std::string(m_name, a + 1, m_name.size()); - m_fullName = std::make_shared(m_collectionName - + ":" + m_name); + m_fullName = std::make_shared(fmt::format("{}:{}", + m_collectionName, m_name)); } else { m_fullName = std::make_shared(m_name); m_collectionName = m_name; @@ -76,24 +77,5 @@ void Variable::addsKeyExclusion(const Variable *v) { } -std::string operator+(const std::string &a, const Variable *v) { - return a + *v->m_fullName.get(); -} - - -std::string operator+(const std::string &a, const Variables *v) { - std::string test; - for (const auto &b : *v) { - if (test.empty()) { - test = std::string("") + b; - } else { - test = test + "|" + b; - } - } - - return a + test; -} - - } // namespace variables } // namespace modsecurity diff --git a/src/variables/variable.h b/src/variables/variable.h index 5d740e1097..b98bc0e2ed 100644 --- a/src/variables/variable.h +++ b/src/variables/variable.h @@ -618,7 +618,9 @@ class Variable : public VariableMonkeyResolution { } - std::string& operator+=(const char * p) { return m_name; } + const std::string& to_string() const { + return *m_fullName.get(); + } std::string m_name; @@ -664,6 +666,17 @@ class Variables : public std::vector { return v->getKeyWithCollection() == *m->m_fullName.get(); }) != end(); }; + + std::string to_string() const { + std::string s; + for (const auto &v : *this) { + if (!s.empty()) { + s.push_back('|'); + } + s.append(v->to_string()); + } + return s; + } }; @@ -718,10 +731,6 @@ class VariableModificatorCount : public Variable { }; -std::string operator+(const std::string &a, const modsecurity::variables::Variable *v); -std::string operator+(const std::string &a, const modsecurity::variables::Variables *v); - - } // namespace variables } // namespace modsecurity