Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "ModIo.h"
26 :
27 : #include "i18n/L10n.h"
28 : #include "lib/code_generation.h"
29 : #include "lib/debug.h"
30 : #include "lib/file/file_system.h"
31 : #include "lib/status.h"
32 : #include "lib/sysdep/filesystem.h"
33 : #include "lib/sysdep/sysdep.h"
34 : #include "maths/MD5.h"
35 : #include "ps/CLogger.h"
36 : #include "ps/ConfigDB.h"
37 : #include "ps/GameSetup/CmdLineArgs.h"
38 : #include "ps/GameSetup/Paths.h"
39 : #include "ps/Mod.h"
40 : #include "ps/ModInstaller.h"
41 : #include "ps/Util.h"
42 : #include "scriptinterface/JSON.h"
43 : #include "scriptinterface/Context.h"
44 : #include "scriptinterface/Conversions.h"
45 : #include "scriptinterface/Request.h"
46 :
47 : #include <algorithm>
48 : #include <boost/algorithm/string/classification.hpp>
49 : #include <boost/algorithm/string/split.hpp>
50 : #include <cstdio>
51 : #include <cstring>
52 : #include <filesystem>
53 : #include <fmt/printf.h>
54 : #include <initializer_list>
55 : #include <js/Array.h>
56 : #include <js/PropertyAndElement.h>
57 : #include <js/RootingAPI.h>
58 : #include <js/TypeDecls.h>
59 : #include <js/Value.h>
60 : #include <system_error>
61 :
62 : namespace Script { class Interface; }
63 :
64 : ModIo* g_ModIo = nullptr;
65 :
66 : struct DownloadCallbackData
67 : {
68 : DownloadCallbackData()
69 : : fp(nullptr), md5(), hash_state(nullptr)
70 : {
71 : }
72 :
73 0 : DownloadCallbackData(FILE* _fp)
74 0 : : fp(_fp), md5()
75 : {
76 0 : hash_state = static_cast<crypto_generichash_state*>(
77 0 : sodium_malloc(crypto_generichash_statebytes()));
78 :
79 0 : ENSURE(hash_state);
80 :
81 0 : crypto_generichash_init(hash_state, nullptr, 0U, crypto_generichash_BYTES_MAX);
82 0 : }
83 :
84 0 : ~DownloadCallbackData()
85 : {
86 0 : if (hash_state)
87 0 : sodium_free(hash_state);
88 0 : }
89 :
90 : FILE* fp;
91 : MD5 md5;
92 : crypto_generichash_state* hash_state;
93 : };
94 :
95 0 : ModIo::ModIo()
96 0 : : m_GamesRequest("/games"), m_CallbackData(nullptr)
97 : {
98 : // Get config values from the default namespace.
99 : // This can be overridden on the command line.
100 : //
101 : // We do this so a malicious mod cannot change the base url and
102 : // get the user to make connections to someone else's endpoint.
103 : // If another user of the engine wants to provide different values
104 : // here, while still using the same engine version, they can just
105 : // provide some shortcut/script that sets these using command line
106 : // parameters.
107 0 : std::string pk_str;
108 0 : g_ConfigDB.GetValue(CFG_DEFAULT, "modio.public_key", pk_str);
109 0 : g_ConfigDB.GetValue(CFG_DEFAULT, "modio.v1.baseurl", m_BaseUrl);
110 0 : {
111 0 : std::string api_key;
112 0 : g_ConfigDB.GetValue(CFG_DEFAULT, "modio.v1.api_key", api_key);
113 0 : m_ApiKey = "api_key=" + api_key;
114 0 : }
115 0 : {
116 0 : std::string nameid;
117 0 : g_ConfigDB.GetValue(CFG_DEFAULT, "modio.v1.name_id", nameid);
118 0 : m_IdQuery = "name_id="+nameid;
119 0 : }
120 :
121 0 : m_CurlMulti = curl_multi_init();
122 0 : ENSURE(m_CurlMulti);
123 :
124 0 : m_Curl = curl_easy_init();
125 0 : ENSURE(m_Curl);
126 :
127 : // Capture error messages
128 0 : curl_easy_setopt(m_Curl, CURLOPT_ERRORBUFFER, m_ErrorBuffer);
129 :
130 : // Fail if the server did
131 0 : curl_easy_setopt(m_Curl, CURLOPT_FAILONERROR, 1L);
132 :
133 : // Disable signal handlers (required for multithreaded applications)
134 0 : curl_easy_setopt(m_Curl, CURLOPT_NOSIGNAL, 1L);
135 :
136 : // To minimise security risks, don't support redirects (except for file
137 : // downloads, for which this setting will be enabled).
138 0 : curl_easy_setopt(m_Curl, CURLOPT_FOLLOWLOCATION, 0L);
139 :
140 : // For file downloads, one redirect seems plenty for a CDN serving the files.
141 0 : curl_easy_setopt(m_Curl, CURLOPT_MAXREDIRS, 1L);
142 :
143 0 : m_Headers = NULL;
144 0 : std::string ua = "User-Agent: pyrogenesis ";
145 0 : ua += curl_version();
146 0 : ua += " (https://play0ad.com/)";
147 0 : m_Headers = curl_slist_append(m_Headers, ua.c_str());
148 0 : curl_easy_setopt(m_Curl, CURLOPT_HTTPHEADER, m_Headers);
149 :
150 0 : if (sodium_init() < 0)
151 0 : ENSURE(0 && "Failed to initialize libsodium.");
152 :
153 0 : size_t bin_len = 0;
154 0 : if (sodium_base642bin((unsigned char*)&m_pk, sizeof m_pk, pk_str.c_str(), pk_str.size(), NULL, &bin_len, NULL, sodium_base64_VARIANT_ORIGINAL) != 0 || bin_len != sizeof m_pk)
155 0 : ENSURE(0 && "Failed to decode base64 public key. Please fix your configuration or mod.io will be unusable.");
156 0 : }
157 :
158 0 : ModIo::~ModIo()
159 : {
160 : // Clean things up to avoid unpleasant surprises,
161 : // and delete the temporary file if any.
162 0 : TearDownRequest();
163 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
164 0 : DeleteDownloadedFile();
165 :
166 0 : curl_slist_free_all(m_Headers);
167 0 : curl_easy_cleanup(m_Curl);
168 0 : curl_multi_cleanup(m_CurlMulti);
169 :
170 0 : delete m_CallbackData;
171 0 : }
172 :
173 0 : size_t ModIo::ReceiveCallback(void* buffer, size_t size, size_t nmemb, void* userp)
174 : {
175 0 : ModIo* self = static_cast<ModIo*>(userp);
176 :
177 0 : self->m_ResponseData += std::string((char*)buffer, (char*)buffer+size*nmemb);
178 :
179 0 : return size*nmemb;
180 : }
181 :
182 0 : size_t ModIo::DownloadCallback(void* buffer, size_t size, size_t nmemb, void* userp)
183 : {
184 0 : DownloadCallbackData* data = static_cast<DownloadCallbackData*>(userp);
185 0 : if (!data->fp)
186 : return 0;
187 :
188 0 : size_t len = fwrite(buffer, size, nmemb, data->fp);
189 :
190 : // Only update the hash with data we actually managed to write.
191 : // In case we did not write all of it we will fail the download,
192 : // but we do not want to have a possibly valid hash in that case.
193 0 : size_t written = len*size;
194 :
195 0 : data->md5.Update(static_cast<const std::uint8_t*>(buffer), written);
196 :
197 0 : ENSURE(data->hash_state);
198 :
199 0 : crypto_generichash_update(data->hash_state, static_cast<const std::uint8_t*>(buffer), written);
200 :
201 0 : return written;
202 : }
203 :
204 0 : int ModIo::DownloadProgressCallback(void* clientp, curl_off_t dltotal, curl_off_t dlnow,
205 : curl_off_t /*ultotal*/, curl_off_t /*ulnow*/)
206 : {
207 0 : DownloadProgressData* data = static_cast<DownloadProgressData*>(clientp);
208 :
209 : // If we got more data than curl expected, something is very wrong, abort.
210 0 : if (dltotal != 0 && dlnow > dltotal)
211 : return 1;
212 :
213 0 : data->progress = dltotal == 0 ? 0 : static_cast<double>(dlnow) / static_cast<double>(dltotal);
214 :
215 0 : return 0;
216 : }
217 :
218 0 : CURLMcode ModIo::SetupRequest(const std::string& url, bool fileDownload)
219 : {
220 0 : if (fileDownload)
221 : {
222 : // The download link will most likely redirect elsewhere, so allow that.
223 : // We verify the validity of the file later.
224 0 : curl_easy_setopt(m_Curl, CURLOPT_FOLLOWLOCATION, 1L);
225 : // Enable the progress meter
226 0 : curl_easy_setopt(m_Curl, CURLOPT_NOPROGRESS, 0L);
227 :
228 : // Set IO callbacks
229 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEFUNCTION, DownloadCallback);
230 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEDATA, static_cast<void*>(m_CallbackData));
231 0 : curl_easy_setopt(m_Curl, CURLOPT_XFERINFOFUNCTION, DownloadProgressCallback);
232 0 : curl_easy_setopt(m_Curl, CURLOPT_XFERINFODATA, static_cast<void*>(&m_DownloadProgressData));
233 :
234 : // Initialize the progress counter
235 0 : m_DownloadProgressData.progress = 0;
236 : }
237 : else
238 : {
239 : // To minimise security risks, don't support redirects
240 0 : curl_easy_setopt(m_Curl, CURLOPT_FOLLOWLOCATION, 0L);
241 : // Disable the progress meter
242 0 : curl_easy_setopt(m_Curl, CURLOPT_NOPROGRESS, 1L);
243 :
244 : // Set IO callbacks
245 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEFUNCTION, ReceiveCallback);
246 0 : curl_easy_setopt(m_Curl, CURLOPT_WRITEDATA, this);
247 : }
248 :
249 0 : m_ErrorBuffer[0] = '\0';
250 0 : curl_easy_setopt(m_Curl, CURLOPT_URL, url.c_str());
251 0 : return curl_multi_add_handle(m_CurlMulti, m_Curl);
252 : }
253 :
254 0 : void ModIo::TearDownRequest()
255 : {
256 0 : const curl_version_info_data* info = curl_version_info(CURLVERSION_NOW);
257 0 : const CURLMcode code = curl_multi_remove_handle(m_CurlMulti, m_Curl);
258 0 : if (info->version_num >= 0x080a00 && info->version_num < 0x080b02)
259 : {
260 : // Version 8.10.0 through 8.11.1 return CURLM_BAD_EASY_HANDLE
261 0 : ENSURE(code == CURLM_OK || code == CURLM_BAD_EASY_HANDLE);
262 : }
263 : else
264 : {
265 0 : ENSURE(code == CURLM_OK);
266 : }
267 :
268 0 : if (m_CallbackData)
269 : {
270 0 : if (m_CallbackData->fp)
271 0 : fclose(m_CallbackData->fp);
272 0 : m_CallbackData->fp = nullptr;
273 : }
274 0 : }
275 :
276 0 : void ModIo::StartGetGameId()
277 : {
278 : // Don't start such a request during active downloads.
279 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::GAMEID ||
280 0 : m_DownloadProgressData.status == DownloadProgressStatus::LISTING ||
281 : m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
282 : return;
283 :
284 0 : m_GameId.clear();
285 :
286 0 : CURLMcode err = SetupRequest(m_BaseUrl+m_GamesRequest+"?"+m_ApiKey+"&"+m_IdQuery, false);
287 0 : if (err != CURLM_OK)
288 : {
289 0 : TearDownRequest();
290 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_GAMEID;
291 0 : m_DownloadProgressData.error = fmt::sprintf(
292 0 : g_L10n.Translate("Failure while starting querying for game id. Error: %s; %s."),
293 0 : curl_multi_strerror(err), m_ErrorBuffer);
294 0 : return;
295 : }
296 :
297 0 : m_DownloadProgressData.status = DownloadProgressStatus::GAMEID;
298 : }
299 :
300 0 : void ModIo::StartListMods()
301 : {
302 : // Don't start such a request during active downloads.
303 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::GAMEID ||
304 0 : m_DownloadProgressData.status == DownloadProgressStatus::LISTING ||
305 : m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
306 : return;
307 :
308 0 : m_ModData.clear();
309 :
310 0 : if (m_GameId.empty())
311 : {
312 0 : LOGERROR("Game ID not fetched from mod.io. Call StartGetGameId first and wait for it to finish.");
313 0 : return;
314 : }
315 :
316 0 : CURLMcode err = SetupRequest(m_BaseUrl+m_GamesRequest+m_GameId+"/mods?"+m_ApiKey, false);
317 0 : if (err != CURLM_OK)
318 : {
319 0 : TearDownRequest();
320 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_LISTING;
321 0 : m_DownloadProgressData.error = fmt::sprintf(
322 0 : g_L10n.Translate("Failure while starting querying for mods. Error: %s; %s."),
323 0 : curl_multi_strerror(err), m_ErrorBuffer);
324 0 : return;
325 : }
326 :
327 0 : m_DownloadProgressData.status = DownloadProgressStatus::LISTING;
328 : }
329 :
330 0 : void ModIo::StartDownloadMod(std::uint32_t idx)
331 : {
332 : // Don't start such a request during active downloads.
333 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::GAMEID ||
334 0 : m_DownloadProgressData.status == DownloadProgressStatus::LISTING ||
335 : m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
336 0 : return;
337 :
338 0 : if (idx >= m_ModData.size())
339 : return;
340 :
341 0 : const Paths paths(g_CmdLineArgs);
342 0 : const OsPath modUserPath = paths.UserData()/"mods";
343 0 : const OsPath modPath = modUserPath/m_ModData[idx].properties["name_id"];
344 0 : if (!DirectoryExists(modPath) && INFO::OK != CreateDirectories(modPath, 0700, false))
345 : {
346 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_DOWNLOADING;
347 0 : m_DownloadProgressData.error = fmt::sprintf(
348 0 : g_L10n.Translate("Could not create mod directory: %s."), modPath.string8());
349 0 : return;
350 : }
351 :
352 : // Name the file after the name_id, since using the filename would mean that
353 : // we could end up with multiple zip files in the folder that might not work
354 : // as expected for a user (since a later version might remove some files
355 : // that aren't compatible anymore with the engine version).
356 : // So we ignore the filename provided by the API and assume that we do not
357 : // care about handling update.zip files. If that is the case we would need
358 : // a way to find out what files are required by the current one and which
359 : // should be removed for everything to work. This seems to be too complicated
360 : // so we just do not support that usage.
361 : // NOTE: We do save the file under a slightly different name from the final
362 : // one, to ensure that in case a download aborts and the file stays
363 : // around, the game will not attempt to open the file which has not
364 : // been verified.
365 0 : m_DownloadFilePath = modPath/(m_ModData[idx].properties["name_id"]+".zip.temp");
366 :
367 0 : delete m_CallbackData;
368 0 : m_CallbackData = new DownloadCallbackData(sys_OpenFile(m_DownloadFilePath, "wb"));
369 0 : if (!m_CallbackData->fp)
370 : {
371 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_DOWNLOADING;
372 0 : m_DownloadProgressData.error = fmt::sprintf(
373 0 : g_L10n.Translate("Could not open temporary file for mod download: %s."), m_DownloadFilePath.string8());
374 0 : return;
375 : }
376 :
377 0 : CURLMcode err = SetupRequest(m_ModData[idx].properties["binary_url"], true);
378 0 : if (err != CURLM_OK)
379 : {
380 0 : TearDownRequest();
381 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_DOWNLOADING;
382 0 : m_DownloadProgressData.error = fmt::sprintf(
383 0 : g_L10n.Translate("Failed to start the download. Error: %s; %s."), curl_multi_strerror(err), m_ErrorBuffer);
384 0 : return;
385 : }
386 :
387 0 : m_DownloadModID = idx;
388 0 : m_DownloadProgressData.status = DownloadProgressStatus::DOWNLOADING;
389 0 : }
390 :
391 0 : void ModIo::CancelRequest()
392 : {
393 0 : TearDownRequest();
394 :
395 0 : switch (m_DownloadProgressData.status)
396 : {
397 0 : case DownloadProgressStatus::GAMEID:
398 0 : case DownloadProgressStatus::FAILED_GAMEID:
399 0 : m_DownloadProgressData.status = DownloadProgressStatus::NONE;
400 0 : break;
401 0 : case DownloadProgressStatus::LISTING:
402 0 : case DownloadProgressStatus::FAILED_LISTING:
403 0 : m_DownloadProgressData.status = DownloadProgressStatus::READY;
404 0 : break;
405 0 : case DownloadProgressStatus::DOWNLOADING:
406 0 : case DownloadProgressStatus::FAILED_DOWNLOADING:
407 0 : m_DownloadProgressData.status = DownloadProgressStatus::LISTED;
408 0 : DeleteDownloadedFile();
409 0 : break;
410 : default:
411 : break;
412 : }
413 0 : }
414 :
415 0 : bool ModIo::AdvanceRequest(const Script::Interface& scriptInterface)
416 : {
417 : // If the request was cancelled, stop trying to advance it
418 0 : if (m_DownloadProgressData.status != DownloadProgressStatus::GAMEID &&
419 0 : m_DownloadProgressData.status != DownloadProgressStatus::LISTING &&
420 : m_DownloadProgressData.status != DownloadProgressStatus::DOWNLOADING)
421 : return true;
422 :
423 0 : int stillRunning;
424 0 : CURLMcode err = curl_multi_perform(m_CurlMulti, &stillRunning);
425 0 : if (err != CURLM_OK)
426 : {
427 0 : std::string error = fmt::sprintf(
428 0 : g_L10n.Translate("Asynchronous download failure: %s, %s."), curl_multi_strerror(err), m_ErrorBuffer);
429 0 : TearDownRequest();
430 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::GAMEID)
431 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_GAMEID;
432 0 : else if (m_DownloadProgressData.status == DownloadProgressStatus::LISTING)
433 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_LISTING;
434 0 : else if (m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
435 : {
436 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_DOWNLOADING;
437 0 : DeleteDownloadedFile();
438 : }
439 0 : m_DownloadProgressData.error = error;
440 0 : return true;
441 0 : }
442 :
443 0 : CURLMsg* message;
444 0 : do
445 : {
446 0 : int in_queue;
447 0 : message = curl_multi_info_read(m_CurlMulti, &in_queue);
448 :
449 0 : if (!message)
450 0 : continue;
451 :
452 0 : if (message->data.result == CURLE_OK)
453 0 : continue;
454 :
455 0 : std::string error = fmt::sprintf(
456 0 : g_L10n.Translate("Download failure. Server response: %s; %s."), curl_easy_strerror(message->data.result), m_ErrorBuffer);
457 0 : TearDownRequest();
458 0 : if (m_DownloadProgressData.status == DownloadProgressStatus::GAMEID)
459 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_GAMEID;
460 0 : else if (m_DownloadProgressData.status == DownloadProgressStatus::LISTING)
461 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_LISTING;
462 0 : else if (m_DownloadProgressData.status == DownloadProgressStatus::DOWNLOADING)
463 : {
464 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_DOWNLOADING;
465 0 : DeleteDownloadedFile();
466 : }
467 0 : m_DownloadProgressData.error = error;
468 0 : return true;
469 0 : } while (message);
470 :
471 0 : if (stillRunning)
472 : return false;
473 :
474 : // Download finished.
475 0 : TearDownRequest();
476 :
477 : // Perform parsing and/or checks
478 0 : std::string error;
479 0 : switch (m_DownloadProgressData.status)
480 : {
481 0 : case DownloadProgressStatus::GAMEID:
482 0 : if (!ParseGameId(scriptInterface, error))
483 : {
484 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_GAMEID;
485 0 : m_DownloadProgressData.error = error;
486 : break;
487 : }
488 :
489 0 : m_DownloadProgressData.status = DownloadProgressStatus::READY;
490 0 : break;
491 0 : case DownloadProgressStatus::LISTING:
492 0 : if (!ParseMods(scriptInterface, error))
493 : {
494 0 : m_ModData.clear(); // Failed during parsing, make sure we don't provide partial data
495 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_LISTING;
496 0 : m_DownloadProgressData.error = error;
497 : break;
498 : }
499 :
500 0 : m_DownloadProgressData.status = DownloadProgressStatus::LISTED;
501 0 : break;
502 0 : case DownloadProgressStatus::DOWNLOADING:
503 0 : if (!VerifyDownloadedFile(error))
504 : {
505 0 : m_DownloadProgressData.status = DownloadProgressStatus::FAILED_FILECHECK;
506 0 : m_DownloadProgressData.error = error;
507 0 : DeleteDownloadedFile();
508 : break;
509 : }
510 :
511 0 : m_DownloadProgressData.status = DownloadProgressStatus::SUCCESS;
512 :
513 0 : {
514 0 : Paths paths(g_CmdLineArgs);
515 0 : CModInstaller installer(paths.UserData() / "mods", paths.Cache());
516 0 : CModInstaller::ModInstallationResult result = installer.Install(m_DownloadFilePath, g_ScriptContext, false);
517 0 : if (result != CModInstaller::ModInstallationResult::SUCCESS)
518 0 : LOGERROR("Failed to install '{}'", m_DownloadFilePath.string8());
519 0 : g_Mods.UpdateAvailableMods(scriptInterface);
520 0 : }
521 0 : break;
522 : default:
523 : break;
524 : }
525 :
526 0 : return true;
527 0 : }
528 :
529 0 : bool ModIo::ParseGameId(const Script::Interface& scriptInterface, std::string& err)
530 : {
531 0 : int id = -1;
532 0 : bool ret = ParseGameIdResponse(scriptInterface, m_ResponseData, id, err);
533 0 : m_ResponseData.clear();
534 0 : if (!ret)
535 : return false;
536 :
537 0 : m_GameId = "/" + std::to_string(id);
538 0 : return true;
539 : }
540 :
541 0 : bool ModIo::ParseMods(const Script::Interface& scriptInterface, std::string& err)
542 : {
543 0 : bool ret = ParseModsResponse(scriptInterface, m_ResponseData, m_ModData, m_pk, err);
544 0 : m_ResponseData.clear();
545 0 : return ret;
546 : }
547 :
548 0 : void ModIo::DeleteDownloadedFile()
549 : {
550 0 : std::error_code ec{};
551 0 : std::filesystem::remove(m_DownloadFilePath.string(), ec);
552 0 : if (ec)
553 0 : LOGERROR("Failed to delete temporary file.");
554 0 : m_DownloadFilePath = OsPath();
555 0 : }
556 :
557 0 : bool ModIo::VerifyDownloadedFile(std::string& err)
558 : {
559 : // Verify filesize, as a first basic download check.
560 0 : {
561 0 : std::error_code ec{};
562 0 : const std::uint64_t fileSize{static_cast<std::uint64_t>(std::filesystem::file_size(
563 0 : std::filesystem::path(m_DownloadFilePath.string()), ec))};
564 0 : if (ec)
565 : {
566 0 : LOGERROR("Failed to get filesize for '{}', reason: {}", m_DownloadFilePath.string8(),
567 : ec.message());
568 : }
569 0 : const std::uint64_t expectedFileSize{std::stoull(
570 0 : m_ModData[m_DownloadModID].properties.at("filesize"))};
571 :
572 0 : if (ec || fileSize != expectedFileSize)
573 : {
574 0 : err = g_L10n.Translate("Mismatched filesize.");
575 0 : return false;
576 : }
577 : }
578 :
579 0 : ENSURE(m_CallbackData);
580 :
581 : // MD5 (because upstream provides it)
582 : // Just used to make sure there was no obvious corruption during transfer.
583 0 : {
584 0 : std::uint8_t digest[MD5::DIGESTSIZE];
585 0 : m_CallbackData->md5.Final(digest);
586 0 : std::string md5digest = Hexify(digest, MD5::DIGESTSIZE);
587 :
588 :
589 0 : if (m_ModData[m_DownloadModID].properties.at("filehash_md5") != md5digest)
590 : {
591 0 : err = fmt::sprintf(
592 0 : g_L10n.Translate("Invalid file. Expected md5 %s, got %s."),
593 0 : m_ModData[m_DownloadModID].properties.at("filehash_md5").c_str(),
594 0 : md5digest);
595 0 : return false;
596 : }
597 0 : }
598 :
599 : // Verify file signature.
600 : // Used to make sure that the downloaded file was actually checked and signed
601 : // by Wildfire Games. And has not been tampered with by the API provider, or the CDN.
602 :
603 0 : unsigned char hash_fin[crypto_generichash_BYTES_MAX] = {};
604 0 : ENSURE(m_CallbackData->hash_state);
605 0 : if (crypto_generichash_final(m_CallbackData->hash_state, hash_fin, sizeof hash_fin) != 0)
606 : {
607 0 : err = g_L10n.Translate("Failed to compute final hash.");
608 0 : return false;
609 : }
610 :
611 0 : if (crypto_sign_verify_detached(m_ModData[m_DownloadModID].sig.sig, hash_fin, sizeof hash_fin, m_pk.pk) != 0)
612 : {
613 0 : err = g_L10n.Translate("Failed to verify signature.");
614 0 : return false;
615 : }
616 :
617 : return true;
618 : }
619 :
620 : #define FAIL(...) STMT(err = fmt::sprintf(__VA_ARGS__); CLEANUP(); return false;)
621 :
622 : /**
623 : * Parses the current content of m_ResponseData to extract m_GameId.
624 : *
625 : * The JSON data is expected to look like
626 : * { "data": [{"id": 42, ...}, ...], ... }
627 : * where we are only interested in the value of the id property.
628 : *
629 : * @returns true iff it successfully parsed the id.
630 : */
631 18 : bool ModIo::ParseGameIdResponse(const Script::Interface& scriptInterface, const std::string& responseData, int& id, std::string& err)
632 : {
633 : #define CLEANUP() id = -1;
634 18 : Script::Request rq(scriptInterface);
635 :
636 18 : JS::RootedValue gameResponse(rq.cx);
637 :
638 18 : if (!Script::ParseJSON(rq, responseData, &gameResponse))
639 2 : FAIL("Failed to parse response as JSON.");
640 :
641 16 : if (!gameResponse.isObject())
642 1 : FAIL("response not an object.");
643 :
644 15 : JS::RootedObject gameResponseObj(rq.cx, gameResponse.toObjectOrNull());
645 15 : JS::RootedValue dataVal(rq.cx);
646 15 : if (!JS_GetProperty(rq.cx, gameResponseObj, "data", &dataVal))
647 0 : FAIL("data property not in response.");
648 :
649 : // [{"id": 42, ...}, ...]
650 15 : if (!dataVal.isObject())
651 3 : FAIL("data property not an object.");
652 :
653 12 : JS::RootedObject data(rq.cx, dataVal.toObjectOrNull());
654 12 : std::uint32_t length;
655 12 : bool isArray;
656 12 : if (!JS::IsArrayObject(rq.cx, data, &isArray) || !isArray || !JS::GetArrayLength(rq.cx, data, &length) || !length)
657 2 : FAIL("data property not an array with at least one element.");
658 :
659 : // {"id": 42, ...}
660 10 : JS::RootedValue first(rq.cx);
661 10 : if (!JS_GetElement(rq.cx, data, 0, &first))
662 0 : FAIL("Couldn't get first element.");
663 10 : if (!first.isObject())
664 2 : FAIL("First element not an object.");
665 :
666 8 : JS::RootedObject firstObj(rq.cx, &first.toObject());
667 8 : bool hasIdProperty;
668 8 : if (!JS_HasProperty(rq.cx, firstObj, "id", &hasIdProperty) || !hasIdProperty)
669 2 : FAIL("No id property in first element.");
670 :
671 6 : JS::RootedValue idProperty(rq.cx);
672 6 : ENSURE(JS_GetProperty(rq.cx, firstObj, "id", &idProperty));
673 :
674 6 : if (!idProperty.isNumber())
675 3 : FAIL("id property not a number.");
676 :
677 3 : id = -1;
678 3 : if (!Script::FromJSVal(rq, idProperty, id) || id <= 0)
679 2 : FAIL("Invalid id.");
680 :
681 : return true;
682 : #undef CLEANUP
683 18 : }
684 :
685 : /**
686 : * Parses the current content of m_ResponseData into m_ModData.
687 : *
688 : * The JSON data is expected to look like
689 : * { data: [modobj1, modobj2, ...], ... (including result_count) }
690 : * where modobjN has the following structure
691 : * { homepage_url: "url", name: "displayname", nameid: "short-non-whitespace-name",
692 : * summary: "short desc.", modfile: { version: "1.2.4", filename: "asdf.zip",
693 : * filehash: { md5: "deadbeef" }, filesize: 1234, download: { binary_url: "someurl", ... } }, ... }.
694 : * Only the listed properties are of interest to consumers, and we flatten
695 : * the modfile structure as that simplifies handling and there are no conflicts.
696 : */
697 43 : bool ModIo::ParseModsResponse(const Script::Interface& scriptInterface, const std::string& responseData, std::vector<ModIoModData>& modData, const PKStruct& pk, std::string& err)
698 : {
699 : // Make sure we don't end up passing partial results back
700 : #define CLEANUP() modData.clear();
701 :
702 43 : Script::Request rq(scriptInterface);
703 :
704 43 : JS::RootedValue modResponse(rq.cx);
705 :
706 43 : if (!Script::ParseJSON(rq, responseData, &modResponse))
707 2 : FAIL("Failed to parse response as JSON.");
708 :
709 41 : if (!modResponse.isObject())
710 1 : FAIL("response not an object.");
711 :
712 40 : JS::RootedObject modResponseObj(rq.cx, modResponse.toObjectOrNull());
713 40 : JS::RootedValue dataVal(rq.cx);
714 40 : if (!JS_GetProperty(rq.cx, modResponseObj, "data", &dataVal))
715 0 : FAIL("data property not in response.");
716 :
717 : // [modobj1, modobj2, ... ]
718 40 : if (!dataVal.isObject())
719 3 : FAIL("data property not an object.");
720 :
721 37 : JS::RootedObject rData(rq.cx, dataVal.toObjectOrNull());
722 37 : std::uint32_t length;
723 37 : bool isArray;
724 37 : if (!JS::IsArrayObject(rq.cx, rData, &isArray) || !isArray || !JS::GetArrayLength(rq.cx, rData, &length) || !length)
725 2 : FAIL("data property not an array with at least one element.");
726 :
727 35 : modData.clear();
728 35 : modData.reserve(length);
729 :
730 : #define INVALIDATE_DATA_AND_CONTINUE(...) \
731 : {\
732 : data.properties.emplace("invalid", "true");\
733 : data.properties.emplace("error", __VA_ARGS__);\
734 : continue;\
735 : }
736 :
737 70 : for (std::uint32_t i = 0; i < length; ++i)
738 : {
739 35 : modData.emplace_back();
740 35 : ModIoModData& data = modData.back();
741 35 : JS::RootedValue el(rq.cx);
742 35 : if (!JS_GetElement(rq.cx, rData, i, &el) || !el.isObject())
743 3 : INVALIDATE_DATA_AND_CONTINUE("Failed to get array element object.")
744 :
745 32 : bool ok = true;
746 32 : std::string copyStringError;
747 : #define COPY_STRINGS_ELSE_CONTINUE(prefix, obj, ...) \
748 : for (const std::string prop : { __VA_ARGS__ }) \
749 : { \
750 : std::string val; \
751 : if (!Script::FromJSProperty(rq, obj, prop.c_str(), val, true)) \
752 : { \
753 : ok = false; \
754 : copyStringError = "Failed to get " + prop + " from " + #obj + "."; \
755 : break; \
756 : }\
757 : data.properties.emplace(prefix+prop, val); \
758 : } \
759 : if (!ok) \
760 : INVALIDATE_DATA_AND_CONTINUE(copyStringError);
761 :
762 : // TODO: Currently the homepage_url field does not contain a non-null value for any entry.
763 131 : COPY_STRINGS_ELSE_CONTINUE("", el, "name", "name_id", "summary")
764 :
765 : // Now copy over the modfile part, but without the pointless substructure
766 23 : JS::RootedObject elObj(rq.cx, el.toObjectOrNull());
767 23 : JS::RootedValue modFile(rq.cx);
768 23 : if (!JS_GetProperty(rq.cx, elObj, "modfile", &modFile))
769 0 : INVALIDATE_DATA_AND_CONTINUE("Failed to get modfile data.");
770 :
771 23 : if (!modFile.isObject())
772 2 : INVALIDATE_DATA_AND_CONTINUE("modfile not an object.");
773 :
774 68 : COPY_STRINGS_ELSE_CONTINUE("", modFile, "version", "filesize");
775 :
776 17 : JS::RootedObject modFileObj(rq.cx, modFile.toObjectOrNull());
777 17 : JS::RootedValue filehash(rq.cx);
778 17 : if (!JS_GetProperty(rq.cx, modFileObj, "filehash", &filehash))
779 0 : INVALIDATE_DATA_AND_CONTINUE("Failed to get filehash data.");
780 :
781 42 : COPY_STRINGS_ELSE_CONTINUE("filehash_", filehash, "md5");
782 :
783 13 : JS::RootedValue download(rq.cx);
784 13 : if (!JS_GetProperty(rq.cx, modFileObj, "download", &download))
785 0 : INVALIDATE_DATA_AND_CONTINUE("Failed to get download data.");
786 :
787 32 : COPY_STRINGS_ELSE_CONTINUE("", download, "binary_url");
788 :
789 : // Parse metadata_blob (sig+deps)
790 10 : std::string metadata_blob;
791 10 : if (!Script::FromJSProperty(rq, modFile, "metadata_blob", metadata_blob, true))
792 2 : INVALIDATE_DATA_AND_CONTINUE("Failed to get metadata_blob from modFile.");
793 :
794 8 : JS::RootedValue metadata(rq.cx);
795 8 : if (!Script::ParseJSON(rq, metadata_blob, &metadata))
796 1 : INVALIDATE_DATA_AND_CONTINUE("Failed to parse metadata_blob as JSON.");
797 :
798 7 : if (!metadata.isObject())
799 1 : INVALIDATE_DATA_AND_CONTINUE("metadata_blob is not decoded as an object.");
800 :
801 6 : if (!Script::FromJSProperty(rq, metadata, "dependencies", data.dependencies, true))
802 2 : INVALIDATE_DATA_AND_CONTINUE("Failed to get dependencies from metadata_blob.");
803 :
804 4 : std::vector<std::string> minisigs;
805 4 : if (!Script::FromJSProperty(rq, metadata, "minisigs", minisigs, true))
806 2 : INVALIDATE_DATA_AND_CONTINUE("Failed to get minisigs from metadata_blob.");
807 :
808 : // Check we did find a valid matching signature.
809 2 : std::string signatureParsingErr;
810 2 : if (!ParseSignature(minisigs, data.sig, pk, signatureParsingErr))
811 2 : INVALIDATE_DATA_AND_CONTINUE(signatureParsingErr);
812 :
813 : #undef COPY_STRINGS_ELSE_CONTINUE
814 : #undef INVALIDATE_DATA_AND_CONTINUE
815 79 : }
816 :
817 : return true;
818 : #undef CLEANUP
819 63 : }
820 :
821 : /**
822 : * Parse signatures to find one that matches the public key, and has a valid global signature.
823 : * Returns true and sets @param sig to the valid matching signature.
824 : */
825 15 : bool ModIo::ParseSignature(const std::vector<std::string>& minisigs, SigStruct& sig, const PKStruct& pk, std::string& err)
826 : {
827 : #define CLEANUP() sig = {};
828 16 : for (const std::string& file_sig : minisigs)
829 : {
830 : // Format of a .minisig file (created using minisign(1) with -SHm file.zip)
831 : // untrusted comment: .*\nb64sign_of_file\ntrusted comment: .*\nb64sign_of_sign_of_file_and_trusted_comment
832 :
833 14 : std::vector<std::string> sig_lines;
834 14 : boost::split(sig_lines, file_sig, boost::is_any_of("\n"));
835 14 : if (sig_lines.size() < 4)
836 2 : FAIL("Invalid (too short) sig.");
837 :
838 : // Verify that both the untrusted comment and the trusted comment start with the correct prefix
839 : // because that is easy.
840 12 : const std::string untrusted_comment_prefix = "untrusted comment: ";
841 12 : const std::string trusted_comment_prefix = "trusted comment: ";
842 12 : if (!sig_lines[0].starts_with(untrusted_comment_prefix))
843 2 : FAIL("Malformed untrusted comment.");
844 10 : if (!sig_lines[2].starts_with(trusted_comment_prefix))
845 2 : FAIL("Malformed trusted comment.");
846 :
847 : // We only _really_ care about the second line which is the signature of the file (b64-encoded)
848 : // Also handling the other signature is nice, but not really required.
849 8 : const std::string& msg_sig = sig_lines[1];
850 :
851 8 : size_t bin_len = 0;
852 8 : if (sodium_base642bin((unsigned char*)&sig, sizeof sig, msg_sig.c_str(), msg_sig.size(), NULL, &bin_len, NULL, sodium_base64_VARIANT_ORIGINAL) != 0 || bin_len != sizeof sig)
853 2 : FAIL("Failed to decode base64 sig.");
854 :
855 6 : cassert(sizeof pk.keynum == sizeof sig.keynum);
856 :
857 6 : if (memcmp(&pk.keynum, &sig.keynum, sizeof sig.keynum) != 0)
858 1 : continue; // mismatched key, try another one
859 :
860 5 : if (memcmp(&sig.sig_alg, "ED", 2) != 0)
861 1 : FAIL("Only hashed minisign signatures are supported.");
862 :
863 : // Signature matches our public key
864 :
865 : // Now verify the global signature (sig || trusted_comment)
866 :
867 4 : unsigned char global_sig[crypto_sign_BYTES];
868 4 : if (sodium_base642bin(global_sig, sizeof global_sig, sig_lines[3].c_str(), sig_lines[3].size(), NULL, &bin_len, NULL, sodium_base64_VARIANT_ORIGINAL) != 0 || bin_len != sizeof global_sig)
869 1 : FAIL("Failed to decode base64 global_sig.");
870 :
871 3 : const std::string trusted_comment = sig_lines[2].substr(trusted_comment_prefix.size());
872 :
873 3 : unsigned char* sig_and_trusted_comment = (unsigned char*)sodium_malloc((sizeof sig.sig) + trusted_comment.size());
874 3 : if (!sig_and_trusted_comment)
875 0 : FAIL("sodium_malloc failed.");
876 :
877 3 : memcpy(sig_and_trusted_comment, sig.sig, sizeof sig.sig);
878 3 : memcpy(sig_and_trusted_comment + sizeof sig.sig, trusted_comment.data(), trusted_comment.size());
879 :
880 3 : if (crypto_sign_verify_detached(global_sig, sig_and_trusted_comment, (sizeof sig.sig) + trusted_comment.size(), pk.pk) != 0)
881 : {
882 1 : err = "Failed to verify global signature.";
883 1 : sodium_free(sig_and_trusted_comment);
884 : return false;
885 : }
886 :
887 2 : sodium_free(sig_and_trusted_comment);
888 :
889 : // Valid global sig, and the keynum matches the real one
890 : return true;
891 37 : }
892 :
893 15 : FAIL("Invalid signature.");
894 : #undef CLEANUP
895 : }
896 :
897 : #undef FAIL
|