OmniSciDB  6686921089
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
StringTransform.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "StringTransform.h"
18 #include "Logger/Logger.h"
19 
20 #include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
21 #include <boost/algorithm/string/split.hpp> // Include for boost::split
22 
23 #include <numeric>
24 #include <random>
25 #include <regex>
26 
27 #ifndef __CUDACC__
28 #include <boost/filesystem.hpp>
29 #include <iomanip>
30 #endif
31 
32 void apply_shim(std::string& result,
33  const boost::regex& reg_expr,
34  const std::function<void(std::string&, const boost::smatch&)>& shim_fn) {
35  boost::smatch what;
36  std::vector<std::pair<size_t, size_t>> lit_pos = find_string_literals(result);
37  auto start_it = result.cbegin();
38  auto end_it = result.cend();
39  while (true) {
40  if (!boost::regex_search(start_it, end_it, what, reg_expr)) {
41  break;
42  }
43  const auto next_start =
44  inside_string_literal(what.position(), what.length(), lit_pos);
45  if (next_start) {
46  start_it = result.cbegin() + *next_start;
47  } else {
48  shim_fn(result, what);
49  lit_pos = find_string_literals(result);
50  start_it = result.cbegin();
51  end_it = result.cend();
52  }
53  }
54 }
55 
56 std::vector<std::pair<size_t, size_t>> find_string_literals(const std::string& query) {
57  boost::regex literal_string_regex{R"(([^']+)('(?:[^']+|'')+'))", boost::regex::perl};
58  boost::smatch what;
59  auto it = query.begin();
60  auto prev_it = it;
61  std::vector<std::pair<size_t, size_t>> positions;
62  while (true) {
63  try {
64  if (!boost::regex_search(it, query.end(), what, literal_string_regex)) {
65  break;
66  }
67  } catch (const std::exception& e) {
68  LOG(WARNING) << "Error processing literals: " << e.what()
69  << "\nContinuing query parse...";
70  // boost::regex throws an exception about the complexity of matching when
71  // the wrong type of quotes are used or they're mismatched. Let the query
72  // through unmodified, the parser will throw a much more informative error.
73  // This can also throw on very long queries
74  break;
75  }
76  CHECK_GT(what[1].length(), 0);
77  prev_it = it;
78  it += what.length();
79  positions.emplace_back(prev_it + what[1].length() - query.begin(),
80  it - query.begin());
81  }
82  return positions;
83 }
84 
85 std::string hide_sensitive_data_from_query(std::string const& query_str) {
86  constexpr std::regex::flag_type flags =
87  std::regex::ECMAScript | std::regex::icase | std::regex::optimize;
88  static const std::initializer_list<std::pair<std::regex, std::string>> rules{
89  {std::regex(
90  R"(\b((?:password|s3_access_key|s3_secret_key|s3_session_token|username|credential_string)\s*=\s*)'.+?')",
91  flags),
92  "$1'XXXXXXXX'"},
93  {std::regex(R"((\\set_license\s+)\S+)", flags), "$1XXXXXXXX"}};
94  return std::accumulate(
95  rules.begin(), rules.end(), query_str, [](auto& str, auto& rule) {
96  return std::regex_replace(str, rule.first, rule.second);
97  });
98 }
99 
100 template <>
101 std::string to_string(char const*&& v) {
102  return std::string(v);
103 }
104 
105 template <>
106 std::string to_string(std::string&& v) {
107  return std::move(v);
108 }
109 
110 std::string generate_random_string(const size_t len) {
111  static char charset[] =
112  "0123456789"
113  "abcdefghijklmnopqrstuvwxyz"
114  "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
115 
116  static std::mt19937 prng{std::random_device{}()};
117  static std::uniform_int_distribution<size_t> dist(0, strlen(charset) - 1);
118 
119  std::string str;
120  str.reserve(len);
121  for (size_t i = 0; i < len; i++) {
122  str += charset[dist(prng)];
123  }
124  return str;
125 }
126 
127 #ifndef __CUDACC__
128 // This version of split works almost exactly like Python's split,
129 // which is very convienently-designed.
130 // See also: https://docs.python.org/3.8/library/stdtypes.html#str.split
131 std::vector<std::string> split(std::string_view str,
132  std::string_view delim,
133  std::optional<size_t> maxsplit) {
134  std::vector<std::string> result;
135 
136  // Use an explicit delimiter.
137  if (!delim.empty()) {
138  std::string::size_type i = 0, j = 0;
139  while ((i = str.find(delim, i)) != std::string::npos &&
140  (!maxsplit || result.size() < maxsplit.value())) {
141  result.emplace_back(str, j, i - j);
142  i += delim.size();
143  j = i;
144  }
145  result.emplace_back(str, j, std::string::npos);
146  return result;
147 
148  // Treat any number of consecutive whitespace characters as a delimiter.
149  } else {
150  bool prev_ws = true;
151  std::string::size_type i = 0, j = 0;
152  for (; i < str.size(); ++i) {
153  if (prev_ws) {
154  if (!isspace(str[i])) {
155  // start of word
156  prev_ws = false;
157  j = i;
158  }
159  } else {
160  if (isspace(str[i])) {
161  // start of space
162  result.emplace_back(str, j, i - j);
163  prev_ws = true;
164  j = i;
165  if ((maxsplit && result.size() == maxsplit.value())) {
166  // stop early if maxsplit was reached
167  result.emplace_back(str, j, std::string::npos);
168  return result;
169  }
170  }
171  }
172  }
173  if (!prev_ws) {
174  result.emplace_back(str, j, std::string::npos);
175  }
176  return result;
177  }
178 }
179 
180 std::string strip(std::string_view str) {
181  std::string::size_type i, j;
182  for (i = 0; i < str.size() && std::isspace(str[i]); ++i) {
183  }
184  for (j = str.size(); j > i && std::isspace(str[j - 1]); --j) {
185  }
186  return std::string(str.substr(i, j - i));
187 }
188 
189 std::optional<size_t> inside_string_literal(
190  const size_t start,
191  const size_t length,
192  const std::vector<std::pair<size_t, size_t>>& literal_positions) {
193  const auto end = start + length;
194  for (const auto& literal_position : literal_positions) {
195  if (literal_position.first <= start && end <= literal_position.second) {
196  return literal_position.second;
197  }
198  }
199  return std::nullopt;
200 }
201 
202 #endif // __CUDACC__
203 
205  std::string& str) noexcept {
206  char inside_quote = 0;
207  bool previous_c_was_backslash = false;
208  for (auto& c : str) {
209  // if this character is a quote of either type
210  if (c == '\'' || c == '\"') {
211  // ignore if previous character was a backslash
212  if (!previous_c_was_backslash) {
213  // start or end of a quoted region
214  if (inside_quote == c) {
215  // end region
216  inside_quote = 0;
217  } else if (inside_quote == 0) {
218  // start region
219  inside_quote = c;
220  }
221  }
222  } else if (inside_quote == 0) {
223  // outside quoted region
224  if (c == '\n' || c == '\t' || c == '\r') {
225  // replace these with space
226  c = ' ';
227  }
228  // otherwise leave alone, including quotes of a different type
229  }
230  // handle backslashes, except for double backslashes
231  if (c == '\\') {
232  previous_c_was_backslash = !previous_c_was_backslash;
233  } else {
234  previous_c_was_backslash = false;
235  }
236  }
237  // if we didn't end a region, there were unclosed or mixed-nested quotes
238  // accounting for backslashes should mean that this should only be the
239  // case with truly malformed strings which Calcite will barf on anyway
240  return (inside_quote == 0);
241 }
242 
243 #ifndef __CUDACC__
244 std::string get_quoted_string(const std::string& filename, char quote, char escape) {
245  std::stringstream ss;
246  ss << std::quoted(filename, quote, escape); // TODO: prevents string_view Jun 2020
247  return ss.str();
248 }
249 #endif // __CUDACC__
250 
251 #ifndef __CUDACC__
252 std::string simple_sanitize(const std::string& str) {
253  auto sanitized_str{str};
254  for (auto& c : sanitized_str) {
255  c = (c < 32) ? ' ' : c;
256  }
257  return sanitized_str;
258 }
259 #endif // __CUDACC__
std::string hide_sensitive_data_from_query(std::string const &query_str)
std::vector< std::pair< size_t, size_t > > find_string_literals(const std::string &query)
std::optional< size_t > inside_string_literal(const size_t start, const size_t length, const std::vector< std::pair< size_t, size_t >> &literal_positions)
std::string strip(std::string_view str)
trim any whitespace from the left and right ends of a string
#define LOG(tag)
Definition: Logger.h:203
std::string simple_sanitize(const std::string &str)
simple sanitize string (replace control characters with space)
#define CHECK_GT(x, y)
Definition: Logger.h:221
std::string to_string(char const *&&v)
std::vector< std::string > split(std::string_view str, std::string_view delim, std::optional< size_t > maxsplit)
split apart a string into a vector of substrings
std::string get_quoted_string(const std::string &filename, char quote, char escape)
Quote a string while escaping any existing quotes in the string.
std::string generate_random_string(const size_t len)
DEVICE auto accumulate(ARGS &&...args)
Definition: gpu_enabled.h:42
void apply_shim(std::string &result, const boost::regex &reg_expr, const std::function< void(std::string &, const boost::smatch &)> &shim_fn)
bool remove_unquoted_newlines_linefeeds_and_tabs_from_sql_string(std::string &str) noexcept
sanitize an SQL string