-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
439 lines (368 loc) · 14.6 KB
/
main.cpp
File metadata and controls
439 lines (368 loc) · 14.6 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#include "libplog/ploga.h"
#include "third_party/httplib.h"
#include "zipconf.h"
#include <Windows.h>
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <winhttp.h>
#include <zip.h>
enum LogAnExitCodes : int32_t {
Success,
// Internal errors
ArgumentFail,
PathConversion,
NoAnalyser,
BufferFail,
_InternalErrorsEnd = 100,
// HTTP-related
UrlParse,
HttpOpen,
HttpConnect,
HttpRequest,
HttpRequestSend,
HttpResponse,
HttpHeaders,
HttpRetryFail,
HttpTooMuch,
_HttpErrorsEnd = 200,
// Zip-related
ZipSource,
ZipOpen,
ZipNoFile,
ZipUnexpected,
_ZipErrorsEnd = 300,
};
std::thread createHttpServer(std::string const&& loglines) {
return std::thread(
[](std::string const&& lines) {
httplib::Server svr;
svr.Get("/", [&lines](httplib::Request const& req, httplib::Response& resp) { resp.set_content(lines, "text/plain"); });
svr.listen("0.0.0.0", 13370);
},
std::move(loglines));
}
int32_t main(int32_t argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <p7d file path> [--noblock]", argv[0]);
return LogAnExitCodes::ArgumentFail;
}
std::thread httpServer;
if (auto argLink = std::string_view(argv[1]); !argLink.empty()) {
std::unique_ptr<PLogAnalyzer> analyser;
std::vector<char> growingdata, unpdata;
if (argLink.starts_with("http")) {
int32_t need = MultiByteToWideChar(CP_UTF8, 0, argLink.data(), -1, nullptr, 0);
if (need <= 0) {
fprintf(stderr, "Failed to determine widechar length of URL\n");
return LogAnExitCodes::PathConversion;
}
std::wstring wideUrl;
wideUrl.resize(need);
if (MultiByteToWideChar(CP_UTF8, 0, argLink.data(), -1, wideUrl.data(), need) != need) {
fprintf(stderr, "Failed to convert URL, stack corruption?\n");
return LogAnExitCodes::PathConversion;
}
wideUrl.pop_back();
constexpr size_t maxDomainSize = 256;
constexpr size_t maxPathSize = 512;
char buffer[(maxDomainSize + maxPathSize) * sizeof(wchar_t)];
URL_COMPONENTSW uc = {
.dwStructSize = sizeof(URL_COMPONENTSW),
.lpszScheme = nullptr,
.dwSchemeLength = 0,
.lpszHostName = (wchar_t*)buffer,
.dwHostNameLength = maxDomainSize,
.lpszUserName = nullptr,
.dwUserNameLength = 0,
.lpszPassword = nullptr,
.dwPasswordLength = 0,
.lpszUrlPath = (wchar_t*)(buffer + maxDomainSize * sizeof(wchar_t)),
.dwUrlPathLength = maxPathSize,
.lpszExtraInfo = nullptr,
.dwExtraInfoLength = 0,
};
if (WinHttpCrackUrl(wideUrl.c_str(), wideUrl.length(), 0, &uc) != TRUE) {
fprintf(stderr, "Failed to parse URL: %lu\n", GetLastError());
return LogAnExitCodes::UrlParse;
}
HINTERNET hSess = WinHttpOpen(L"psOff_logan/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (hSess == NULL) {
fprintf(stderr, "Failed to build HTTP session: %lu\n", GetLastError());
return LogAnExitCodes::HttpOpen;
}
DWORD redirPolicy = WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS;
WinHttpSetOption(hSess, WINHTTP_OPTION_REDIRECT_POLICY, &redirPolicy, sizeof(redirPolicy));
HINTERNET hConn = WinHttpConnect(hSess, uc.lpszHostName, uc.nPort, 0);
if (hConn == NULL) {
fprintf(stderr, "Failed to connect to server: %lu\n", GetLastError());
return LogAnExitCodes::HttpConnect;
}
DWORD orflags = WINHTTP_FLAG_REFRESH;
if (uc.nScheme == INTERNET_SCHEME_HTTPS) orflags |= WINHTTP_FLAG_SECURE;
HINTERNET hRequ = WinHttpOpenRequest(hConn, L"GET", uc.lpszUrlPath, nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, orflags);
if (hRequ == NULL) {
fprintf(stderr, "Failed to open request to server: %lu\n", GetLastError());
return LogAnExitCodes::HttpRequest;
}
if (!WinHttpSendRequest(hRequ, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
fprintf(stderr, "Failed to send request to server: %lu\n", GetLastError());
return LogAnExitCodes::HttpRequestSend;
}
if (!WinHttpReceiveResponse(hRequ, NULL)) {
fprintf(stderr, "Failed to receive response from server: %lu\n", GetLastError());
return LogAnExitCodes::HttpResponse;
}
size_t csize;
DWORD csizeLen = sizeof(csize);
if (!WinHttpQueryHeaders(hRequ, WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER64, WINHTTP_HEADER_NAME_BY_INDEX, &csize, &csizeLen,
WINHTTP_NO_HEADER_INDEX)) {
DWORD error = GetLastError();
if (error != ERROR_WINHTTP_HEADER_NOT_FOUND) {
fprintf(stderr, "Failed to receive response length from server: %lu\n", GetLastError());
return LogAnExitCodes::HttpHeaders;
}
csize = 0;
}
std::memset(buffer, 0, sizeof(buffer));
char* outdata = nullptr;
size_t outdatasize = 0;
DWORD availdata = 0;
DWORD downloaded = 0;
if ((csize == 0) || (csize > sizeof(buffer))) { // Growing case
growingdata.reserve(csize);
do {
WinHttpQueryDataAvailable(hRequ, &availdata);
if (availdata == 0) break;
availdata = std::min((DWORD)sizeof(buffer), availdata); // Shrink to our buffer size
uint32_t retries = 0;
retry_grow:
downloaded = 0;
if (!WinHttpReadData(hRequ, buffer, availdata, &downloaded)) {
if (++retries > 15) {
fprintf(stderr, "Server read failed after 15 retries!\n");
return LogAnExitCodes::HttpRetryFail;
}
if (downloaded == 0) {
fprintf(stderr, "Server read failed, retrying in 5 seconds...\n");
std::this_thread::sleep_for(std::chrono::seconds(5));
goto retry_grow;
}
}
if ((csize > 0) && ((growingdata.size() + downloaded) > csize)) {
fprintf(stderr, "Server sent way more data than it should!\n");
return LogAnExitCodes::HttpTooMuch;
}
growingdata.insert(growingdata.end(), std::begin(buffer), std::begin(buffer) + downloaded);
} while (true);
outdata = growingdata.data();
outdatasize = growingdata.size();
} else { // Static case
char* bufpos = buffer;
size_t bufleft = sizeof(buffer);
do {
WinHttpQueryDataAvailable(hRequ, &availdata);
if (availdata == 0) break;
if (bufleft < availdata) {
fprintf(stderr, "Server sent way more data than it should!\n");
return LogAnExitCodes::HttpTooMuch;
}
uint32_t retries = 0;
retry:
downloaded = 0;
if (!WinHttpReadData(hRequ, bufpos, availdata, &downloaded)) {
if (++retries > 15) {
fprintf(stderr, "Server read failed after 15 retries!\n");
return LogAnExitCodes::HttpRetryFail;
}
if (downloaded == 0) {
fprintf(stderr, "Server read failed, retrying in 5 seconds...\n");
std::this_thread::sleep_for(std::chrono::seconds(5));
goto retry;
}
}
if (downloaded > 0) {
bufpos += downloaded;
bufleft -= downloaded;
}
} while (bufleft > 0);
outdata = buffer;
outdatasize = sizeof(buffer) - bufleft;
}
if (outdata != nullptr && outdatasize > 0) {
if (std::memcmp(outdata, "PK", 2) == 0) { // Most likely Zip archive, handle it
zip_error_t zerr;
zip_source_t* zsrc;
zip_t* zarc;
zip_error_init(&zerr);
if ((zsrc = zip_source_buffer_create(outdata, outdatasize, 0, &zerr)) == nullptr) {
fprintf(stderr, "Failed to create zip source: %s\n", zip_error_strerror(&zerr));
zip_error_fini(&zerr);
return LogAnExitCodes::ZipSource;
}
if ((zarc = zip_open_from_source(zsrc, 0, &zerr)) == nullptr) {
fprintf(stderr, "Failed to open zip: %s\n", zip_error_strerror(&zerr));
zip_source_free(zsrc);
zip_error_fini(&zerr);
return LogAnExitCodes::ZipOpen;
}
zip_error_fini(&zerr);
struct MenuEntry {
zip_int64_t index;
zip_uint64_t size;
std::string name;
};
std::vector<MenuEntry> files;
std::string serveData;
zip_int64_t num_files = zip_get_num_entries(zarc, 0);
for (zip_int64_t i = 0; i < num_files; ++i) {
zip_stat_t sb;
if (zip_stat_index(zarc, i, 0, &sb) < 0) {
fprintf(stderr, "Failed to stat zip file#%lld: %s\n", i, zip_strerror(zarc));
continue;
}
if (sb.size == 0) {
fprintf(stderr, "File %s skipped: %s\n", sb.name, "it's empty");
continue;
}
if (!std::string_view(sb.name).ends_with(".plog")) {
fprintf(stderr, "File %s skipped: %s\n", sb.name, "not a .plog file");
continue;
}
zip_file_t* zf = zip_fopen_index(zarc, i, 0);
if (zf == nullptr) {
fprintf(stderr, "File %s skipped: %s\n", sb.name, zip_strerror(zarc));
continue;
}
char plogdata[0xe];
if (zip_fread(zf, plogdata, sizeof(plogdata)) != sizeof(plogdata)) { // Read plog line
fprintf(stderr, "File %s skipped: %s\n", sb.name, zip_strerror(zarc));
zip_fclose(zf);
continue;
}
std::string_view plogdatasv(plogdata);
auto const plogend = plogdatasv.find(';');
if (plogend == std::string_view::npos) {
fprintf(stderr, "File %s skipped: Invalid start sequence\n", sb.name);
zip_fclose(zf);
continue;
}
files.emplace_back(i, sb.size, std::string(plogdatasv.substr(0, plogend)));
{
if (!serveData.empty() && serveData.back() != '\n') serveData.push_back('\n');
auto const prevSize = serveData.size();
serveData.resize(prevSize + sb.size);
std::memcpy(serveData.data() + prevSize, plogdata, sizeof(plogdata));
auto const restSize = sb.size - sizeof(plogdata);
if (zip_fread(zf, serveData.data() + prevSize + sizeof(plogdata), restSize) != restSize) {
fprintf(stderr, "Warning, failed to read %s for HTTP serving purposes\n", sb.name);
serveData.resize(prevSize);
}
}
zip_fclose(zf);
}
if (files.empty()) {
zip_close(zarc);
zip_source_close(zsrc);
fprintf(stderr, "No p7d files found in zip archive!\n");
return LogAnExitCodes::ZipNoFile;
}
auto unpackZipFile = [&unpdata, zarc, zsrc](MenuEntry& lf) {
zip_file_t* zf = zip_fopen_index(zarc, lf.index, 0);
if (zf == nullptr) {
fprintf(stderr, "Failed to open zip file: %s\n", zip_strerror(zarc));
zip_close(zarc);
zip_source_close(zsrc);
return LogAnExitCodes::ZipUnexpected;
}
unpdata.resize(lf.size);
if (zip_fread(zf, unpdata.data(), unpdata.size()) != lf.size) {
fprintf(stderr, "Failed to read zip file: %s\n", zip_strerror(zarc));
zip_close(zarc);
zip_source_close(zsrc);
return LogAnExitCodes::ZipUnexpected;
}
zip_fclose(zf);
return LogAnExitCodes::Success;
};
httpServer = createHttpServer(std::move(serveData));
if (files.size() > 1) { // Entering interactive mode
while (true) {
std::cout << "\x1b[0;0H\x1b[2J0. [Exit]" << std::endl;
for (auto it = files.begin(); it != files.end(); ++it) {
std::cout << std::format("{}. {} ({} bytes)", std::distance(files.begin(), it) + 1, it->name, it->size) << std::endl;
}
std::cout << std::endl << "Enter index: ";
int32_t index = 0;
std::cin >> index;
getchar(); // Skip newline
if (index == 0) break;
if (index > files.size()) continue;
if (unpackZipFile(files[index - 1]) != LogAnExitCodes::Success) {
}
std::cout << "\x1b[0;0H\x1b[2J";
std::cout << createMemAnalyser(unpdata.data(), unpdata.size())->spit().c_str();
unpdata.clear();
std::cout << std::endl << "Press enter to go back...";
while (getchar() != '\n')
;
}
zip_close(zarc);
zip_source_close(zsrc);
return LogAnExitCodes::Success;
} else {
if (unpackZipFile(files.front()) != LogAnExitCodes::Success) {
zip_close(zarc);
zip_source_close(zsrc);
return LogAnExitCodes::ZipUnexpected;
}
outdata = unpdata.data();
outdatasize = unpdata.size();
zip_close(zarc);
zip_source_close(zsrc);
}
} else {
std::string buf(outdata, outdata + outdatasize);
httpServer = createHttpServer(std::move(buf));
}
analyser = createMemAnalyser(outdata, outdatasize);
} else {
fprintf(stderr, "Invalid output buffer!\n");
return LogAnExitCodes::BufferFail;
}
} else if (auto fpath = std::filesystem::path(argLink); std::filesystem::exists(fpath)) {
{
std::ifstream f(fpath);
std::stringstream ss;
ss << f.rdbuf();
httpServer = createHttpServer(ss.str());
}
analyser = createFileAnalyser(fpath);
}
if (analyser != nullptr) {
std::cout << analyser->spit().c_str();
} else {
fprintf(stderr, "P7Dump fail: No suitable analyser found for specified link\n");
return LogAnExitCodes::NoAnalyser;
}
}
if (argc == 2 || std::string_view(argv[2]) != "--noblock") {
while (true)
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (httpServer.joinable()) httpServer.detach();
return LogAnExitCodes::Success;
}