1
0

utils: simplify/optimize escaping

Este cometimento está contido em:
Albert S. 2020-04-19 22:45:51 +02:00
ascendente e435e84bfa
cometimento 3b2578b7f9

Ver ficheiro

@ -1,4 +1,4 @@
/* Copyright (c) 2018 Albert S. /* Copyright (c) 2018-2020 Albert S.
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -27,28 +27,30 @@ SOFTWARE.
#include "logger.h" #include "logger.h"
#include "utils.h" #include "utils.h"
// TODO: instead of returning vector maybe provide an iterator version too.
// TODO: % may not be necessary (was in C version just to be sure against format string attacks
// TODO: hopefully not too slow looking up every character here:
const std::map<char, std::string> replacements = {{'<', "&lt;"}, {'>', "gt;"}, {'\"', "&quot;"}, {'%', "&#37;"}};
std::string utils::html_xss(std::string_view str) std::string utils::html_xss(std::string_view str)
{ {
std::string result; std::string result;
int size = str.length(); for(char c : str)
for(int i = 0; i < size; i++)
{ {
char c = str[i]; switch(c)
auto val = replacements.find(c);
if(val != replacements.end())
{
result += val->second;
}
else
{ {
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '\"':
result += "&quot;";
break;
case '%':
result += "&#37;";
break;
default:
result += c; result += c;
} }
} }
return result; return result;
} }
@ -93,6 +95,7 @@ std::vector<std::string> utils::splitByString(const std::string &str, const std:
{ {
return splitByRegex(str, delim + "+"); return splitByRegex(str, delim + "+");
} }
std::vector<std::string> utils::splitByRegex(const std::string &str, const std::string &regex) std::vector<std::string> utils::splitByRegex(const std::string &str, const std::string &regex)
{ {
std::vector<std::string> result; std::vector<std::string> result;