Perform EscapeSeqDecode transformation in-place

- Removed ansi_c_sequences_decode_inplace helper function from the
  class, as it's only referenced by the implementation.
This commit is contained in:
Eduardo Arias 2024-08-19 08:28:04 -07:00
parent 727f2bf840
commit a520369da0
2 changed files with 14 additions and 28 deletions

View File

@ -26,12 +26,13 @@ EscapeSeqDecode::EscapeSeqDecode(const std::string &action)
} }
int EscapeSeqDecode::ansi_c_sequences_decode_inplace(unsigned char *input, static inline int ansi_c_sequences_decode_inplace(std::string &value) {
int input_len) { auto d = reinterpret_cast<unsigned char *>(value.data());
unsigned char *d = input; const unsigned char* input = d;
int i, count; const auto input_len = value.length();
i = count = 0; bool changed = false;
std::string::size_type i = 0;
while (i < input_len) { while (i < input_len) {
if ((input[i] == '\\') && (i + 1 < input_len)) { if ((input[i] == '\\') && (i + 1 < input_len)) {
int c = -1; int c = -1;
@ -109,43 +110,29 @@ int EscapeSeqDecode::ansi_c_sequences_decode_inplace(unsigned char *input,
if (c == -1) { if (c == -1) {
/* Didn't recognise encoding, copy raw bytes. */ /* Didn't recognise encoding, copy raw bytes. */
*d++ = input[i + 1]; *d++ = input[i + 1];
count++;
i += 2; i += 2;
} else { } else {
/* Converted the encoding. */ /* Converted the encoding. */
*d++ = c; *d++ = c;
count++;
} }
changed = true;
} else { } else {
/* Input character not a backslash, copy it. */ /* Input character not a backslash, copy it. */
*d++ = input[i++]; *d++ = input[i++];
count++;
} }
} }
*d = '\0'; *d = '\0';
return count; value.resize(d - input);
}
bool EscapeSeqDecode::transform(std::string &value, const Transaction *trans) const {
unsigned char *tmp = (unsigned char *) malloc(sizeof(char)
* value.size() + 1);
memcpy(tmp, value.c_str(), value.size() + 1);
tmp[value.size()] = '\0';
int size = ansi_c_sequences_decode_inplace(tmp, value.size());
std::string ret("");
ret.assign(reinterpret_cast<char *>(tmp), size);
free(tmp);
const auto changed = ret != value;
value = ret;
return changed; return changed;
} }
bool EscapeSeqDecode::transform(std::string &value, const Transaction *trans) const {
return ansi_c_sequences_decode_inplace(value);
}
} // namespace modsecurity::actions::transformations } // namespace modsecurity::actions::transformations

View File

@ -25,7 +25,6 @@ class EscapeSeqDecode : public Transformation {
explicit EscapeSeqDecode(const std::string &action); explicit EscapeSeqDecode(const std::string &action);
bool transform(std::string &value, const Transaction *trans) const override; bool transform(std::string &value, const Transaction *trans) const override;
static int ansi_c_sequences_decode_inplace(unsigned char *input, int input_len);
}; };
} // namespace modsecurity::actions::transformations } // namespace modsecurity::actions::transformations