-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuc.launcher.cpp
More file actions
448 lines (375 loc) · 15.2 KB
/
uc.launcher.cpp
File metadata and controls
448 lines (375 loc) · 15.2 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
440
441
442
443
444
445
446
447
448
#include <windows.h>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
// Convert UTF-8 std::string → std::wstring safely
std::wstring toWide(const std::string& input) {
int size_needed = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0);
std::wstring output(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, &output[0], size_needed);
return output;
}
// Convert std::wstring → std::string safely
std::string toNarrow(const std::wstring& input) {
int size_needed = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL);
std::string output(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, &output[0], size_needed, NULL, NULL);
return output;
}
// Parse command line arguments to get appid
std::string getArgValue(const std::string& cmdLine, const std::string& arg) {
std::istringstream iss(cmdLine);
std::string token;
std::string prevToken;
while (iss >> token) {
// Check for -appid or /appid
if (token == arg || token == "/" + arg) {
return prevToken;
}
prevToken = token;
}
return "";
}
// Simple function to extract appid value
int getAppIdFromArgs(const std::string& cmdLine) {
std::istringstream iss(cmdLine);
std::string token;
while (iss >> token) {
// Look for -appid or /appid
if (token == "-appid" || token == "/appid") {
// Next token should be the appid
if (iss >> token) {
try {
return std::stoi(token);
} catch (...) {
return -1;
}
}
}
}
return -1;
}
// HTTP GET request using WinHTTP
std::string httpGet(const std::wstring& url) {
// Parse URL
URL_COMPONENTSW urlComp = {};
urlComp.dwStructSize = sizeof(urlComp);
wchar_t scheme[32] = {};
wchar_t host[256] = {};
wchar_t path[1024] = {};
urlComp.lpszScheme = scheme;
urlComp.dwSchemeLength = sizeof(scheme) / sizeof(wchar_t);
urlComp.lpszHostName = host;
urlComp.dwHostNameLength = sizeof(host) / sizeof(wchar_t);
urlComp.lpszUrlPath = path;
urlComp.dwUrlPathLength = sizeof(path) / sizeof(wchar_t);
if (!WinHttpCrackUrl(url.c_str(), url.length(), 0, &urlComp)) {
return "";
}
// Use WinHTTP to make the request
HINTERNET hSession = WinHttpOpen(L"UnionCraxLauncher/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return "";
HINTERNET hConnect = WinHttpConnect(hSession, host, urlComp.nPort, 0);
if (!hConnect) {
WinHttpCloseHandle(hSession);
return "";
}
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hRequest) {
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return "";
}
BOOL bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
if (!bResults) {
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return "";
}
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (!bResults) {
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return "";
}
// Read response
std::string response;
DWORD dwSize = 0;
do {
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) break;
if (dwSize == 0) break;
char* buffer = new char[dwSize + 1];
ZeroMemory(buffer, dwSize + 1);
DWORD dwDownloaded = 0;
if (WinHttpReadData(hRequest, buffer, dwSize, &dwDownloaded)) {
response += buffer;
}
delete[] buffer;
} while (dwSize > 0);
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return response;
}
// Simple JSON value extraction (for basic key-value extraction)
std::string extractJsonField(const std::string& json, const std::string& fieldName) {
// Look for "fieldName": "value" or "fieldName": value
std::string searchPattern = "\"" + fieldName + "\":";
size_t pos = json.find(searchPattern);
if (pos == std::string::npos) {
// Try with space after colon
searchPattern = "\"" + fieldName + "\": ";
pos = json.find(searchPattern);
}
if (pos == std::string::npos) return "";
pos += searchPattern.length();
// Skip whitespace
while (pos < json.length() && (json[pos] == ' ' || json[pos] == '\t')) pos++;
if (pos >= json.length()) return "";
// Check if string value
if (json[pos] == '"') {
pos++;
size_t endPos = json.find('"', pos);
if (endPos == std::string::npos) return "";
return json.substr(pos, endPos - pos);
}
// Number or other value
size_t endPos = pos;
while (endPos < json.length() && json[endPos] != ',' && json[endPos] != '}' && json[endPos] != ']') endPos++;
std::string value = json.substr(pos, endPos - pos);
// Trim whitespace
value.erase(remove_if(value.begin(), value.end(), ::isspace), value.end());
return value;
}
// Find game entry by appid in JSON array
std::string findGameByAppId(const std::string& json, int appid) {
// Look for objects that contain "appid": <appid>
std::string searchAppId = "\"appid\":";
size_t pos = 0;
while (true) {
pos = json.find(searchAppId, pos);
if (pos == std::string::npos) break;
// Check if the number after appid matches
size_t numStart = pos + searchAppId.length();
while (numStart < json.length() && (json[numStart] == ' ' || json[numStart] == '\t')) numStart++;
// Extract the number
size_t numEnd = numStart;
while (numEnd < json.length() && isdigit(json[numEnd])) numEnd++;
if (numEnd > numStart) {
std::string numStr = json.substr(numStart, numEnd - numStart);
try {
int foundAppId = std::stoi(numStr);
if (foundAppId == appid) {
// Found the right appid, now find the enclosing object
// Go backwards to find the opening {
size_t objStart = pos;
while (objStart > 0 && json[objStart] != '{') objStart--;
// Go forward to find the closing }
size_t objEnd = numEnd;
int braceCount = 0;
bool inString = false;
while (objEnd < json.length()) {
char c = json[objEnd];
if (c == '"' && (objEnd == 0 || json[objEnd-1] != '\\')) {
inString = !inString;
} else if (!inString) {
if (c == '{') braceCount++;
else if (c == '}') {
braceCount--;
if (braceCount == 0) break;
}
}
objEnd++;
}
return json.substr(objStart, objEnd - objStart + 1);
}
} catch (...) {
// Invalid number, continue
}
}
pos = numEnd;
}
return "";
}
// Write INI file
bool writeIniFile(const std::string& path, const std::string& gameExe, const std::string& workingDir, const std::string& launchArgs) {
std::ofstream file(path);
if (!file.is_open()) return false;
file << "[Launcher]" << std::endl;
file << "# Path to the game executable (required)" << std::endl;
file << "# Can be absolute path or relative to the launcher's directory" << std::endl;
file << "gameExe=" << gameExe << std::endl;
file << std::endl;
file << "# Working directory for the game (optional)" << std::endl;
file << "# If not specified, the launcher's directory will be used" << std::endl;
file << "# Can be absolute path or relative to the launcher's directory" << std::endl;
file << "workingDir=" << workingDir << std::endl;
file << std::endl;
file << "# Command line arguments to pass to the game (optional)" << std::endl;
file << "# Separate multiple arguments with spaces" << std::endl;
file << "launchArgs=" << launchArgs << std::endl;
file.close();
return true;
}
bool fileExists(const std::string& filePath) {
std::ifstream file(filePath);
return file.good();
}
// Get string from INI file (Windows API wrapper)
std::string getIniString(const std::string& iniPath, const std::string& section, const std::string& key, const std::string& defaultValue) {
wchar_t buffer[4096] = {};
std::wstring wIniPath = toWide(iniPath);
std::wstring wSection = toWide(section);
std::wstring wKey = toWide(key);
DWORD result = GetPrivateProfileStringW(
wSection.c_str(),
wKey.c_str(),
toWide(defaultValue).c_str(),
buffer,
sizeof(buffer) / sizeof(wchar_t),
wIniPath.c_str()
);
return toNarrow(buffer);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Get the command line as string
std::string cmdLine(lpCmdLine);
// Get the appid from command line arguments
int appId = getAppIdFromArgs(cmdLine);
if (appId <= 0) {
MessageBoxA(NULL,
"Usage: uc.launcher.exe -appid <appid>\n\n"
"Example: uc.launcher.exe -appid 4310\n\n"
"This will load <appid>.ini (e.g., 4310.ini) or fetch from the server if it doesn't exist.",
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Get the directory where the launcher is located
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string currentPath(buffer);
size_t pos = currentPath.find_last_of("\\/");
std::string exeDir = (pos != std::string::npos) ? currentPath.substr(0, pos) : ".";
// Build INI path based on appid
std::string iniPath = exeDir + "\\" + std::to_string(appId) + ".ini";
// Check if INI file exists
if (!fileExists(iniPath)) {
// Try to fetch from API
MessageBoxA(NULL,
("INI file not found for appid " + std::to_string(appId) + ".\n"
"Attempting to fetch game data from server...").c_str(),
"Game Launcher", MB_OK | MB_ICONINFORMATION);
std::wstring apiUrlW = L"https://union-crax.xyz/api/games";
std::string response = httpGet(apiUrlW);
if (response.empty()) {
MessageBoxA(NULL,
("Failed to fetch game data from server.\n\n"
"Please check your internet connection and try again, or create " + std::to_string(appId) + ".ini manually.").c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Find the game by appid in the JSON response
std::string gameJson = findGameByAppId(response, appId);
if (gameJson.empty()) {
MessageBoxA(NULL,
("Game with appid " + std::to_string(appId) + " not found on the server.\n\n"
"Please verify the appid is correct.").c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Extract game configuration from JSON
// These field names need to match the API response
std::string gameExe = extractJsonField(gameJson, "exe");
std::string workingDir = extractJsonField(gameJson, "workingDir");
std::string launchArgs = extractJsonField(gameJson, "launchArgs");
// If fields are empty, try alternate names
if (gameExe.empty()) gameExe = extractJsonField(gameJson, "gameExe");
if (workingDir.empty()) workingDir = extractJsonField(gameJson, "working_directory");
if (workingDir.empty()) workingDir = ".";
if (gameExe.empty()) {
MessageBoxA(NULL,
("Game configuration incomplete for appid " + std::to_string(appId) + ".\n\n"
"The server response is missing required game information.").c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Save the fetched configuration as INI file
if (!writeIniFile(iniPath, gameExe, workingDir, launchArgs)) {
MessageBoxA(NULL,
("Failed to save configuration file.\n\n"
"Could not write to: " + iniPath).c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
MessageBoxA(NULL,
("Successfully fetched game data and saved configuration to:\n" + iniPath).c_str(),
"Game Launcher", MB_OK | MB_ICONINFORMATION);
}
// Read configuration from INI file
std::string exePath = getIniString(iniPath, "Launcher", "gameExe", "");
std::string workingDir = getIniString(iniPath, "Launcher", "workingDir", ".");
std::string arguments = getIniString(iniPath, "Launcher", "launchArgs", "");
// Validate required gameExe
if (exePath.empty()) {
MessageBoxA(NULL,
("The 'gameExe' setting is missing or empty in " + std::to_string(appId) + ".ini.\n"
"Please configure the gameExe path relative to the launcher.").c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Check if the executable exists
if (!fileExists(exePath)) {
MessageBoxA(NULL,
("Failed to find the game executable:\n" + exePath).c_str(),
"Game Launcher Error", MB_OK | MB_ICONERROR);
return 1;
}
// Build the full command line
std::string commandLineStr = "\"" + exePath + "\"";
// Add arguments if specified
if (!arguments.empty()) {
commandLineStr += " " + arguments;
}
std::wstring cmdW = toWide(commandLineStr);
std::wstring workingDirW = toWide(workingDir);
STARTUPINFOW si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
// Launch the game
BOOL result = CreateProcessW(
NULL,
&cmdW[0], // writable buffer required by WinAPI
NULL,
NULL,
FALSE,
0,
NULL,
workingDirW.empty() ? NULL : workingDirW.c_str(),
&si,
&pi
);
if (!result) {
DWORD error = GetLastError();
MessageBoxA(NULL,
("Failed to launch the game.\n"
"Error code: " + std::to_string(error) + "\n\n"
"Command: " + commandLineStr + "\n"
"Working directory: " + workingDir).c_str(),
"Game Launcher Error",
MB_OK | MB_ICONERROR);
return 1;
}
// Clean up handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}