-
Notifications
You must be signed in to change notification settings - Fork 25
/
util.cc
312 lines (254 loc) · 6.12 KB
/
util.cc
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
/**
* bcm2-utils
* Copyright (C) 2016 Joseph Lehner <[email protected]>
*
* bcm2-utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* bcm2-utils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with bcm2-utils. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <algorithm>
#include "profile.h"
#include "util.h"
using namespace std;
namespace bcm2dump {
namespace {
string& unescape(string& str, char delim)
{
string::size_type i = 0;
while ((i = str.find('\\', i)) != string::npos) {
if ((i + 1) >= str.size()) {
throw invalid_argument("stray backslash in '" + str + "'");
} else if (str[i + 1] == '\\' || str[i + 1] == delim) {
str.erase(i, 1);
i += 1;
} else {
throw invalid_argument("invalid escape sequence in '" + str + "'");
}
}
return str;
}
void push_back(vector<string>& strings, string str, char delim, bool empties, size_t limit)
{
if (empties || !str.empty()) {
if (!limit || strings.size() < limit) {
strings.push_back(unescape(str, delim));
} else {
strings.back() += delim + unescape(str, delim);
}
}
}
bool is_unescaped(const string& str, string::size_type pos)
{
if (!pos) {
return true;
}
bool ret = false;
if (pos >= 1) {
ret = str[pos - 1] != '\\';
}
if (pos >= 2 && !ret) {
ret = str[pos - 2] == '\\';
}
return ret;
}
// inspired by http://wordaligned.org/articles/cpp-streambufs
//
// we don't care if the operations on the ofstream's buffer fail,
// as this is expected if we're not using a logfile!
class logbuf : public streambuf
{
public:
logbuf(ostream& os)
: m_os(os)
{}
static ofstream file;
protected:
virtual int overflow(int c) override
{
file.rdbuf()->sputc(c);
return m_os.rdbuf()->sputc(c);
}
virtual int sync() override
{
file.rdbuf()->pubsync();
return m_os.rdbuf()->pubsync();
}
private:
ostream& m_os;
};
ofstream logbuf::file;
ostream log_cout(new logbuf(cout));
ostream log_cerr(new logbuf(cerr));
}
string trim(string str)
{
if (str.empty()) {
return str;
}
auto i = str.find_last_not_of(" \r\n\t");
if (i != string::npos) {
str.erase(i + 1);
}
i = str.find_first_not_of(" \r\n\t");
if (i == string::npos) {
return "";
}
str = str.substr(i);
// strip embedded carriage returns
while ((i = str.find('\r')) != string::npos) {
str.erase(i, 1);
}
return str;
}
vector<string> split(const string& str, char delim, bool empties, size_t limit)
{
string::size_type beg = 0, end = str.find(delim);
vector<string> subs;
while (end != string::npos) {
if (is_unescaped(str, end)) {
push_back(subs, str.substr(beg, end - beg), delim, empties, limit);
beg = end + 1;
}
end = str.find(delim, end + 1);
if (end == string::npos) {
push_back(subs, str.substr(beg, str.size()), delim, empties, limit);
}
}
if (subs.empty() && !str.empty()) {
push_back(subs, str, delim, empties, limit);
}
return subs;
}
string to_hex(const std::string& buffer)
{
string ret;
for (char c : buffer) {
ret += to_hex(c & 0xff, 2);
}
return ret;
}
string from_hex(const string& hexstr)
{
if (hexstr.size() % 2) {
throw user_error("invalid hex-string size "
+ to_string(hexstr.size()));
}
size_t i = 0;
if (starts_with(hexstr, "0x")) {
i += 2;
}
string ret;
ret.reserve((hexstr.size() - i) / 2);
for (; i < hexstr.size(); i += 2) {
string chr = hexstr.substr(i, 2);
try {
ret += lexical_cast<int>(hexstr.substr(i, 2), 16);
} catch (const bad_lexical_cast& e) {
throw user_error("invalid hex char '" + chr + "'");
}
}
return ret;
}
std::string transform(const std::string& str, std::function<int(int)> f)
{
string ret;
ret.reserve(str.size());
for (int c : str) {
ret += f(c);
}
return ret;
}
std::string escape(string str, bool escape_quote)
{
string::size_type pos;
while ((pos = str.find_first_of(escape_quote ? "\\\"" : "\\")) != string::npos) {
str.insert(pos, 1, '\'');
}
string::iterator it = str.begin();
while ((it = find_if(it, str.end(), [] (auto c) { return !isprint(c); })) != str.end()) {
str.replace(it, it + 1, "\\x" + to_hex(*it));
}
return str;
}
int logger::s_loglevel = logger::info;
bool logger::s_no_stdout = false;
list<string> logger::s_lines;
constexpr int logger::trace;
constexpr int logger::debug;
constexpr int logger::verbose;
constexpr int logger::info;
constexpr int logger::warn;
constexpr int logger::err;
ostream& logger::log(int severity)
{
if (severity < s_loglevel) {
return logbuf::file;
} else if (s_no_stdout || severity >= warn) {
return log_cerr;
} else {
return log_cout;
}
}
void logger::log(int severity, const char* format, va_list args)
{
if (severity < s_loglevel) {
return;
}
char buf[256];
vsnprintf(buf, sizeof(buf), format, args);
log(severity) << buf;
}
void logger::log_io(const string& line, bool in)
{
if (s_lines.size() == 50) {
s_lines.pop_front();
}
s_lines.push_back((in ? "==> " : "<== ") + (line.empty() ?
"(empty)"s : ("'" + trim(line.c_str()) + "'")));
ostream& os = logbuf::file ? logbuf::file : log(trace);
os << s_lines.back() << endl;
}
void logger::set_logfile(const string& filename)
{
logbuf::file.open(filename.c_str());
}
string getaddrinfo_category::message(int condition) const
{
#ifndef _WIN32
return gai_strerror(condition);
#else
return to_string(condition);
#endif
}
#ifdef _WIN32
string winapi_category::message(int condition) const
{
char* buf = nullptr;
DWORD len = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
condition,
//MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
0,
reinterpret_cast<LPTSTR>(&buf),
0,
nullptr);
if (buf && len) {
string msg = trim(buf);
LocalFree(buf);
return msg;
}
return "0x" + to_hex(condition);
}
#endif
}