-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.cpp
executable file
·360 lines (312 loc) · 9.72 KB
/
utilities.cpp
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QProcess>
#include <QRandomGenerator>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QUrl>
#include <QJsonDocument>
#include <QJsonObject>
#include "utilities.h"
#ifdef Q_OS_WINDOWS
QString printErrorMessage(DWORD errorCode) {
LPVOID lpMsgBuf;
DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD dwLanguageId = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
FormatMessageW(
dwFlags,
NULL,
errorCode,
dwLanguageId,
(LPWSTR)&lpMsgBuf,
0,
NULL
);
QString errorMsg = QString::fromWCharArray((LPCWSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
return errorMsg.trimmed();
}
QString Utils::getNextDriverLetter()
{
DWORD drivesBitmask = GetLogicalDrives();
if (drivesBitmask == 0) {
DWORD error = GetLastError();
qDebug() << "GetLogicalDrives failed. Error code:" << error;
return "";
}
QString letters = "FGHIJKLMNOPQRSTUVWXYZ";
QString availableLetter;
for (int i = letters.size() - 1; i >= 0; --i) {
QChar letterChar = letters.at(i);
int driveIndex = letterChar.toLatin1() - 'A';
if ((drivesBitmask & (1 << driveIndex)) == 0) {
availableLetter = letterChar;
break;
}
}
if (availableLetter.isEmpty()) {
qDebug() << "Can't find free drive letter";
return "";
}
return availableLetter;
}
#endif
QString Utils::getRandomString(int len)
{
const QString possibleCharacters = QStringLiteral("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
QString randomString;
for (int i = 0; i < len; ++i) {
randomString.append(possibleCharacters.at(QRandomGenerator::system()->bounded(possibleCharacters.length())));
}
return randomString;
}
QString Utils::VerifyJsonString(const QString &source)
{
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(source.toUtf8(), &error);
Q_UNUSED(doc)
if (error.error == QJsonParseError::NoError) {
return "";
} else {
qDebug() << "WARNING: Json parse returns: " + error.errorString();
return error.errorString();
}
}
QJsonObject Utils::JsonFromString(const QString &string)
{
auto removeComment = string.trimmed();
if (removeComment != string.trimmed()) {
qDebug() << "Some comments have been removed from the json.";
}
QJsonDocument doc = QJsonDocument::fromJson(removeComment.toUtf8());
return doc.object();
}
QString Utils::SafeBase64Decode(QString string)
{
QByteArray ba = string.replace(QChar('-'), QChar('+')).replace(QChar('_'), QChar('/')).toUtf8();
return QByteArray::fromBase64(ba, QByteArray::Base64Option::OmitTrailingEquals);
}
QString Utils::JsonToString(const QJsonObject &json, QJsonDocument::JsonFormat format)
{
QJsonDocument doc;
doc.setObject(json);
return doc.toJson(format);
}
QString Utils::JsonToString(const QJsonArray &array, QJsonDocument::JsonFormat format)
{
QJsonDocument doc;
doc.setArray(array);
return doc.toJson(format);
}
bool Utils::initializePath(const QString &path)
{
QDir dir;
if (!dir.mkpath(path)) {
qWarning().noquote() << QString("Cannot initialize path: '%1'").arg(path);
return false;
}
return true;
}
bool Utils::createEmptyFile(const QString &path)
{
QFile f(path);
return f.open(QIODevice::WriteOnly | QIODevice::Truncate);
}
QString Utils::executable(const QString &baseName, bool absPath)
{
QString ext;
#ifdef Q_OS_WIN
ext = ".exe";
#endif
const QString fileName = baseName + ext;
if (!absPath) {
return fileName;
}
return QCoreApplication::applicationDirPath() + "/" + fileName;
}
QString Utils::usrExecutable(const QString &baseName)
{
if (QFileInfo::exists("/usr/sbin/" + baseName))
return ("/usr/sbin/" + baseName);
else
return ("/usr/bin/" + baseName);
}
bool Utils::processIsRunning(const QString &fileName, const bool fullFlag)
{
#ifdef Q_OS_WIN
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
qWarning() << "Utils::processIsRunning error CreateToolhelp32Snapshot";
return false;
}
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (!Process32FirstW(hSnapshot, &pe32)) {
CloseHandle(hSnapshot);
qWarning() << "Utils::processIsRunning error Process32FirstW";
return false;
}
do {
QString exeFile = QString::fromWCharArray(pe32.szExeFile);
if (exeFile.compare(fileName, Qt::CaseInsensitive) == 0) {
CloseHandle(hSnapshot);
return true;
}
} while (Process32NextW(hSnapshot, &pe32));
CloseHandle(hSnapshot);
return false;
#elif defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
return false;
#else
QProcess process;
QStringList arguments;
if (fullFlag) {
arguments << "-f";
}
arguments << fileName;
process.setProcessChannelMode(QProcess::MergedChannels);
process.start("pgrep", arguments);
process.waitForFinished();
if (process.exitStatus() == QProcess::NormalExit) {
if (fullFlag) {
return (process.readLine().toUInt() > 0);
} else {
return (process.readAll().toUInt() > 0);
}
}
return false;
#endif
}
bool Utils::killProcessByName(const QString &name)
{
qDebug().noquote() << "Kill process" << name;
#ifdef Q_OS_WIN
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return false;
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
bool success = false;
if (Process32FirstW(hSnapshot, &pe32)) {
do {
QString exeFile = QString::fromWCharArray(pe32.szExeFile);
if (exeFile.compare(name, Qt::CaseInsensitive) == 0) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe32.th32ProcessID);
if (hProcess != NULL) {
if (TerminateProcess(hProcess, 0)) {
success = true;
} else {
DWORD error = GetLastError();
qCritical() << "Can't terminate process" << exeFile << "(PID:" << pe32.th32ProcessID << "). Error:" << printErrorMessage(error);
}
CloseHandle(hProcess);
} else {
DWORD error = GetLastError();
qCritical() << "Can't open process for termination" << exeFile << "(PID:" << pe32.th32ProcessID << "). Error:" << printErrorMessage(error);
}
}
} while (Process32NextW(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
return success;
#elif defined Q_OS_IOS || defined(Q_OS_ANDROID)
return false;
#else
return QProcess::execute("pkill", { name }) == 0;
#endif
}
QString Utils::openVpnExecPath()
{
#ifdef Q_OS_WIN
return Utils::executable("openvpn/openvpn", true);
#elif defined Q_OS_LINUX
// We have service that runs OpenVPN on Linux. We need to make same
// path for client and service.
return Utils::executable("../../client/bin/openvpn", true);
#else
return Utils::executable("/openvpn", true);
#endif
}
QString Utils::wireguardExecPath()
{
#ifdef Q_OS_WIN
return Utils::executable("wireguard/wireguard-service", true);
#elif defined Q_OS_LINUX
return Utils::usrExecutable("wg-quick");
#elif defined Q_OS_MAC
return Utils::executable("/wireguard", true);
#else
return {};
#endif
}
QString Utils::certUtilPath()
{
#ifdef Q_OS_WIN
QString winPath = QString::fromUtf8(qgetenv("windir"));
return winPath + "\\system32\\certutil.exe";
#else
return "";
#endif
}
QString Utils::tun2socksPath()
{
#ifdef Q_OS_WIN
return Utils::executable("xray/tun2socks", true);
#elif defined Q_OS_LINUX
// We have service that runs OpenVPN on Linux. We need to make same
// path for client and service.
return Utils::executable("../../client/bin/tun2socks", true);
#else
return Utils::executable("/tun2socks", true);
#endif
}
#ifdef Q_OS_WIN
// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool Utils::signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
bool success = false;
DWORD thisConsoleId = GetCurrentProcessId();
// Leave current console if it exists
// (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
bool consoleDetached = (FreeConsole() != FALSE);
if (AttachConsole(dwProcessId) != FALSE) {
// Add a fake Ctrl-C handler for avoid instant kill is this console
// WARNING: do not revert it or current program will be also killed
SetConsoleCtrlHandler(nullptr, true);
success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
FreeConsole();
}
if (consoleDetached) {
// Create a new console if previous was deleted by OS
if (AttachConsole(thisConsoleId) == FALSE) {
int errorCode = GetLastError();
if (errorCode == 31) // 31=ERROR_GEN_FAILURE
{
AllocConsole();
}
}
}
return success;
}
#endif
void Utils::logException(const std::exception &e)
{
qCritical() << e.what();
try {
std::rethrow_if_nested(e);
} catch (const std::exception &nested) {
logException(nested);
} catch (...) {}
}
void Utils::logException(const std::exception_ptr &eptr)
{
try {
if (eptr) std::rethrow_exception(eptr);
} catch (const std::exception &e) {
logException(e);
} catch (...) {}
}