1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright (C) 2011-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <util/encode/encode.h>
#include <util/str.h>

#include <cstddef><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstdint><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <exception><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iomanip><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <regex><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <string><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <vector><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <boost/algorithm/string/classification.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/algorithm/string/constants.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/algorithm/string/split.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace std;

namespace isc {
namespace util {
namespace str {

string
trim(const string& input) {
    if (input.empty()) {
        return (string());
    }
    static const char* blanks = " \t\n";

    // Search for first non-blank character in the string.
    size_t const first(input.find_first_not_of(blanks));
    if (first == string::npos) {
        return (string());
    }

    // String not all blanks, so look for last character.
    size_t const last(input.find_last_not_of(blanks));

    // Extract the trimmed substring.
    return (input.substr(first, (last - first + 1)));
}

vector<string>
tokens(const string& text, const string& delim, bool escape) {
    vector<string> result;
    string token;
    bool in_token = false;
    bool escaped = false;
    for (auto const& c : text) {
        if (delim.find(c) != string::npos) {
            // Current character is a delimiter
            if (!in_token) {
                // Two or more delimiters, eat them
            } else if (escaped) {
                // Escaped delimiter in a token: reset escaped and keep it
                escaped = false;
                token.push_back(c);
            } else {
                // End of the current token: save it if not empty
                if (!token.empty()) {
                    result.push_back(token);
                }
                // Reset state
                in_token = false;
                token.clear();
            }
        } else if (escape && (c == '\\')) {
            // Current character is the escape character
            if (!in_token) {<--- Condition '!in_token' is redundant
                // The escape character is the first character of a new token
                in_token = true;<--- Assignment 'in_token=true'
            }
            if (escaped) {
                // Escaped escape: reset escaped and keep one character
                escaped = false;
                token.push_back(c);
            } else {
                // Remember to keep the next character
                escaped = true;
            }
        } else {
            // Not a delimiter nor an escape
            if (!in_token) {<--- Condition '!in_token' is redundant
                // First character of a new token
                in_token = true;<--- Assignment 'in_token=true'
            }
            if (escaped) {
                // Escaped common character: as escape was false
                escaped = false;
                token.push_back('\\');
                token.push_back(c);
            } else {
                // The common case: keep it
                token.push_back(c);
            }
        }
    }
    // End of input: close and save the current token if not empty
    if (escaped) {
        // Pending escape
        token.push_back('\\');
    }
    if (!token.empty()) {
        result.push_back(token);
    }

    return (result);
}

char
toUpper(char const chr) {
    return (toupper(chr));
}

void
uppercase(string& text) {
    transform(text.begin(), text.end(), text.begin(), toUpper);
}

char
toLower(char const chr) {
    return (tolower(static_cast<int>(chr)));
}

void
lowercase(string& text) {
    transform(text.begin(), text.end(), text.begin(), toLower);
}

vector<uint8_t>
quotedStringToBinary(const string& quoted_string) {
    vector<uint8_t> binary;
    // Remove whitespace before and after the quotes.
    string trimmed_string = trim(quoted_string);

    // We require two quote characters, so the length of the string must be
    // equal to 2 at minimum, and it must start and end with quotes.
    if ((trimmed_string.length() > 1) &&
        ((trimmed_string[0] == '\'') && (trimmed_string[trimmed_string.length() - 1] == '\''))) {
        // Remove quotes and trim the text inside the quotes.
        trimmed_string = trim(trimmed_string.substr(1, trimmed_string.length() - 2));
        // Copy string contents into the vector.
        binary.assign(trimmed_string.begin(), trimmed_string.end());
    }
    // Return resulting vector or empty vector.
    return (binary);
}

void
decodeColonSeparatedHexString(const string& hex_string, vector<uint8_t>& binary) {
    decodeSeparatedHexString(hex_string, ":", binary);
}

void
decodeSeparatedHexString(const string& hex_string, const string& sep, vector<uint8_t>& binary) {
    vector<string> split_text;
    boost::split(split_text, hex_string, boost::is_any_of(sep),
                 boost::algorithm::token_compress_off);

    vector<uint8_t> binary_vec;
    for (size_t i = 0; i < split_text.size(); ++i) {
        // If there are multiple tokens and the current one is empty, it
        // means that two consecutive colons were specified. This is not
        // allowed.
        if ((split_text.size() > 1) && split_text[i].empty()) {
            isc_throw(BadValue, "two consecutive separators ('"
                                    << sep << "') specified in a decoded string '" << hex_string
                                    << "'");

            // Between a colon we expect at most two characters.
        } else if (split_text[i].size() > 2) {
            isc_throw(BadValue, "invalid format of the decoded string"
                                    << " '" << hex_string << "'");

        } else if (!split_text[i].empty()) {
            stringstream s;
            s << "0x";

            for (unsigned int j = 0; j < split_text[i].length(); ++j) {
                // Check if we're dealing with hexadecimal digit.
                if (!isxdigit(split_text[i][j])) {
                    isc_throw(BadValue, "'" << split_text[i][j]
                                            << "' is not a valid hexadecimal digit in"
                                            << " decoded string '" << hex_string << "'");
                }
                s << split_text[i][j];
            }

            // The stream should now have one or two hexadecimal digits.
            // Let's convert it to a number and store in a temporary
            // vector.
            unsigned int binary_value;
            s >> hex >> binary_value;

            binary_vec.push_back(static_cast<uint8_t>(binary_value));
        }
    }

    // All ok, replace the data in the output vector with a result.
    binary.swap(binary_vec);
}

void
decodeFormattedHexString(const string& hex_string, vector<uint8_t>& binary) {
    // If there is at least one colon we assume that the string
    // comprises octets separated by colons (e.g. MAC address notation).
    if (hex_string.find(':') != string::npos) {
        decodeSeparatedHexString(hex_string, ":", binary);
    } else if (hex_string.find(' ') != string::npos) {
        decodeSeparatedHexString(hex_string, " ", binary);
    } else {
        ostringstream s;

        // If we have odd number of digits we'll have to prepend '0'.
        if (hex_string.length() % 2 != 0) {
            s << "0";
        }

        // It is ok to use '0x' prefix in a string.
        if ((hex_string.length() > 2) && (hex_string.substr(0, 2) == "0x")) {
            // Exclude '0x' from the decoded string.
            s << hex_string.substr(2);

        } else {
            // No '0x', so decode the whole string.
            s << hex_string;
        }

        try {
            // Decode the hex string.
            encode::decodeHex(s.str(), binary);

        } catch (...) {
            isc_throw(BadValue, "'" << hex_string
                                    << "' is not a valid"
                                       " string of hexadecimal digits");
        }
    }
}

class StringSanitizerImpl {
public:
    /// @brief Constructor.
    StringSanitizerImpl(const string& char_set, const string& char_replacement)
        : char_set_(char_set), char_replacement_(char_replacement) {
        if (char_set.size() > StringSanitizer::MAX_DATA_SIZE) {
            isc_throw(BadValue, "char set size: '" << char_set.size() << "' exceeds max size: '"
                                                   << StringSanitizer::MAX_DATA_SIZE << "'");
        }

        if (char_replacement.size() > StringSanitizer::MAX_DATA_SIZE) {
            isc_throw(BadValue, "char replacement size: '"
                                    << char_replacement.size() << "' exceeds max size: '"
                                    << StringSanitizer::MAX_DATA_SIZE << "'");
        }
        try {
            scrub_exp_ = regex(char_set, regex::extended);
        } catch (const exception& ex) {
            isc_throw(BadValue, "invalid regex: '" << char_set_ << "', " << ex.what());
        }
    }

    string scrub(const string& original) {
        stringstream result;
        try {
            regex_replace(ostream_iterator<char>(result), original.begin(), original.end(),
                          scrub_exp_, char_replacement_);
        } catch (const exception& ex) {
            isc_throw(BadValue, "replacing '" << char_set_ << "' with '" << char_replacement_
                                              << "' in '" << original << "' failed: ,"
                                              << ex.what());
        }

        return (result.str());
    }

private:
    /// @brief The char set data for regex.
    string char_set_;

    /// @brief The char replacement data for regex.
    string char_replacement_;

    regex scrub_exp_;
};

// @note The regex engine is implemented using recursion and can cause
// stack overflow if the input data is too large. An arbitrary size of
// 4096 should be enough for all cases.
const uint32_t StringSanitizer::MAX_DATA_SIZE = 4096;

StringSanitizer::StringSanitizer(const string& char_set, const string& char_replacement)
    : impl_(new StringSanitizerImpl(char_set, char_replacement)) {
}

string
StringSanitizer::scrub(const string& original) {
    return (impl_->scrub(original));
}

bool
isPrintable(const string& content) {
    for (char const ch : content) {<--- Consider using std::all_of or std::none_of algorithm instead of a raw loop.
        if (isprint(ch) == 0) {
            return (false);
        }
    }
    return (true);
}

bool
isPrintable(const vector<uint8_t>& content) {
    for (uint8_t const ch : content) {<--- Consider using std::all_of or std::none_of algorithm instead of a raw loop.
        if (isprint(ch) == 0) {
            return (false);
        }
    }
    return (true);
}

string
dumpAsHex(const uint8_t* data, size_t length) {
    stringstream output;
    for (size_t i = 0; i < length; ++i) {
        if (i) {
            output << ":";
        }

        output << setfill('0') << setw(2) << hex << static_cast<unsigned short>(data[i]);
    }

    return (output.str());
}

}  // namespace str
}  // namespace util
}  // namespace isc