-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdater.cpp
More file actions
880 lines (819 loc) · 25.6 KB
/
Updater.cpp
File metadata and controls
880 lines (819 loc) · 25.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
#include "Updater.h"
#include "Config.h"
#include "Downloader.h"
#include "Logger.h"
#include "vdf_parser.hpp"
#if _MSC_VER
// make Boost happy when building with MSVC
#include <sdkddkver.h>
#endif
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/readable_pipe.hpp>
#include <boost/process/environment.hpp>
#include <boost/process/stdio.hpp>
#include <boost/process/process.hpp>
// these must be included after boost, because it #include's Windows.h
#include <archive.h>
#include <archive_entry.h>
#include <nlohmann/json.hpp>
#include <regex>
#include <stdexcept>
#include <system_error>
#include <vector>
namespace
{
bool IsDirectory(const std::filesystem::path& path)
{
const auto& targetPath(
std::filesystem::is_symlink(path) ?
std::filesystem::read_symlink(path) : path
);
return std::filesystem::is_directory(targetPath);
}
enum class ToStringCase
{
LOWER, TITLE, UPPER
};
const std::vector<std::string_view> FRAMEWORK_STRING_LOWER
{ "none", "carbon", "oxide" };
const std::vector<std::string_view> FRAMEWORK_STRING_TITLE
{ "None", "Carbon", "Oxide" };
const std::vector<std::string_view> FRAMEWORK_STRING_UPPER
{ "NONE", "CARBON", "OXIDE" };
std::string_view ToString(
const rustLaunchSite::Config::ModFrameworkType framework,
const ToStringCase stringCase
)
{
std::size_t index{0};
using enum rustLaunchSite::Config::ModFrameworkType;
switch (framework)
{
case NONE: index = 0; break;
case CARBON: index = 1; break;
case OXIDE: index = 2; break;
}
using enum ToStringCase;
switch (stringCase)
{
case LOWER: return FRAMEWORK_STRING_LOWER.at(index);
case TITLE: return FRAMEWORK_STRING_TITLE.at(index);
case UPPER: return FRAMEWORK_STRING_UPPER.at(index);
}
return {};
}
std::filesystem::path GetFrameworkDllPath(
const std::filesystem::path& serverInstallPath,
const rustLaunchSite::Config::ModFrameworkType framework
)
{
using enum rustLaunchSite::Config::ModFrameworkType;
switch (framework)
{
case NONE:
break;
case CARBON:
return serverInstallPath / "carbon/managed/Carbon.dll";
case OXIDE:
return serverInstallPath / "RustDedicated_Data/Managed/Oxide.Rust.dll";
}
return {};
}
const std::vector<std::string_view> FRAMEWORK_URL
{
// NONE
"",
// CARBON
"https://api.github.com/repos/CarbonCommunity/Carbon/releases/tags/production_build",
// OXIDE
"https://api.github.com/repos/OxideMod/Oxide.Rust/releases/latest"
};
std::shared_ptr<struct archive> GetReadArchive()
{
return { // NOSONAR
archive_read_new(), [](struct archive* h){archive_read_free(h);}};
}
std::shared_ptr<struct archive> GetWriteDiskArchive()
{
return { // NOSONAR
archive_write_disk_new(), [](struct archive* h){archive_write_free(h);}};
}
int CopyArchiveData(
rustLaunchSite::Logger& logger
, std::shared_ptr<struct archive> ar
, std::shared_ptr<struct archive> aw)
{
while (true)
{
const void* buff{};
std::size_t size{};
std::int64_t offset{};
const auto readResult{
archive_read_data_block(ar.get(), &buff, &size, &offset)};
if (ARCHIVE_EOF == readResult) return ARCHIVE_OK;
if (readResult < ARCHIVE_OK) return readResult;
const auto writeResult{
archive_write_data_block(aw.get(), buff, size, offset)};
if (writeResult < ARCHIVE_OK)
{
LOGWRN(logger, "Failed to write extracted file data: " << archive_error_string(aw.get()));
return static_cast<int>(writeResult);
}
}
}
bool CheckArchiveResult(
rustLaunchSite::Logger& logger
, const int result
, std::string_view prefix
, std::shared_ptr<struct archive> arch)
{
if (result == ARCHIVE_EOF) return false;
if (result >= ARCHIVE_OK) return true;
const bool isError{result < ARCHIVE_WARN};
LOG(
logger
, isError ? rustLaunchSite::LogLevel::ERR : rustLaunchSite::LogLevel::WRN
, prefix << ": " << arch ? archive_error_string(arch.get()) : "");
return !isError;
}
bool IsExecutableFile(const std::filesystem::path& filePath)
{
const auto& ext{filePath.extension()};
return
".a" == ext
|| ".dll" == ext
|| ".DLL" == ext
|| ".sh" == ext
|| ".so" == ext
;
}
void FixPermissions(
rustLaunchSite::Logger& logger, const std::filesystem::path& filePath)
{
using enum std::filesystem::perms;
if (!IsExecutableFile(filePath)) return;
std::error_code ec{};
std::filesystem::permissions(
filePath
, owner_exec | group_exec | others_exec
, std::filesystem::perm_options::add
, ec
);
if (ec)
{
LOGWRN(logger, "Issue while setting execute permissions on file " << filePath << ": " << ec.message());
return;
}
LOGINF(logger, "Set execute permissions on file " << filePath);
}
// extract Carbon/Oxide release archive into server installation directory
void ExtractArchiveData(
rustLaunchSite::Logger& logger
, const std::vector<char>& archData
, std::string_view url
, std::string_view frameworkTitle
, [[maybe_unused]] const std::filesystem::path& serverInstallPath)
{
if (archData.size() < 2)
{
LOGWRN(logger, "Cannot update " << frameworkTitle << " because valid data was not downloaded from URL " << url);
return;
}
auto arch{GetReadArchive()};
// determine file type
if (0x1F == archData.at(0) &&
0x8B == static_cast<unsigned char>(archData.at(1)))
{
// .tar.gz
archive_read_support_filter_gzip(arch.get());
archive_read_support_format_tar(arch.get());
}
else if ('P' == archData.at(0) && 'K' == archData.at(1))
{
// .zip
archive_read_support_format_zip(arch.get());
}
else
{
// unknown
LOGWRN(logger, "Failed to determine " << frameworkTitle << " archive format for data of length=" << archData.size() << " downloaded from URL " << url);
return;
}
// bind arch to data blob
auto result{
archive_read_open_memory(arch.get(), archData.data(), archData.size())};
if (ARCHIVE_OK != result)
{
LOGWRN(logger, "Failed to open " << frameworkTitle << " archive data of length=" << archData.size() << " downloaded from URL " << url);
return;
}
// allocate a handle for writing extracted data to disk
auto outFile{GetWriteDiskArchive()};
archive_write_disk_set_options(
outFile.get(),
ARCHIVE_EXTRACT_ACL |
ARCHIVE_EXTRACT_FFLAGS |
ARCHIVE_EXTRACT_PERM |
ARCHIVE_EXTRACT_TIME
);
archive_write_disk_set_standard_lookup(outFile.get());
// loop through archive contents and extract to disk
while (true)
{
// extract entry metadata
struct archive_entry* entry{};
if (!CheckArchiveResult(
logger
, archive_read_next_header(arch.get(), &entry)
, "Issue while reading archive entry"
, arch))
{
break;
}
// make the output file relative to server install path
const auto outFilePath{serverInstallPath / archive_entry_pathname_w(entry)};
archive_entry_copy_pathname_w(entry, outFilePath.generic_wstring().data());
// create output file for entry
result = archive_write_header(outFile.get(), entry);
if (result < ARCHIVE_OK)
{
LOGWRN(logger, "Issue while creating output file " << outFilePath << ": " << archive_error_string(outFile.get()));
}
else if (archive_entry_size(entry) > 0 && !CheckArchiveResult(
logger
// write output file data
, CopyArchiveData(logger, arch, outFile)
, std::string{"Issue while writing output file "} +
outFilePath.generic_string()
, outFile)
)
{
break;
}
// finalize output file
if (!CheckArchiveResult(
logger
, archive_write_finish_entry(outFile.get())
, std::string{"Issue while finalizing output file "} +
outFilePath.generic_string()
, outFile))
{
break;
}
LOGINF(logger, "Extracted file " << outFilePath);
FixPermissions(logger, outFilePath);
}
archive_read_close(arch.get());
archive_write_close(outFile.get());
}
std::string_view GetFrameworkURL(
const rustLaunchSite::Config::ModFrameworkType framework
)
{
std::size_t index{0};
using enum rustLaunchSite::Config::ModFrameworkType;
switch (framework)
{
case NONE: index = 0; break;
case CARBON: index = 1; break;
case OXIDE: index = 2; break;
}
return FRAMEWORK_URL.at(index);
}
const std::vector<std::string_view> FRAMEWORK_ASSET
{
// NONE
"",
// CARBON
#if _MSC_VER || defined(__MINGW32__)
"Carbon.Windows.Release.zip",
#else
"Carbon.Linux.Release.tar.gz",
#endif
// OXIDE
#if _MSC_VER || defined(__MINGW32__)
"Oxide.Rust.zip"
#else
"Oxide.Rust-linux.zip"
#endif
};
std::string_view GetFrameworkAsset(
const rustLaunchSite::Config::ModFrameworkType framework
)
{
std::size_t index{0};
using enum rustLaunchSite::Config::ModFrameworkType;
switch (framework)
{
case NONE: index = 0; break;
case CARBON: index = 1; break;
case OXIDE: index = 2; break;
}
return FRAMEWORK_ASSET.at(index);
}
template<typename P>
std::string RunExecutable(
rustLaunchSite::Logger& logger,
const P& exe,
const std::vector<std::string>& args)
{
if (exe.empty()) return {};
boost::asio::io_context ioContext;
boost::asio::readable_pipe stdoutPipe{ioContext};
// boost::asio::readable_pipe stderrPipe{ioContext};
boost::process::process proc(
ioContext, exe, args, boost::process::process_stdio{{}, stdoutPipe, {}});
std::string output1;
// std::string output2;
boost::system::error_code errorCode;
boost::asio::read(
stdoutPipe, boost::asio::dynamic_buffer(output1), errorCode);
// boost::asio::read(stderrPipe, boost::asio::dynamic_buffer(output2), errorCode);
proc.wait(errorCode);
// LOGINF(logger, exe << " output:\n" << output1);
if (errorCode && boost::asio::error::eof != errorCode)
{
LOGWRN(logger, "Got error code " << errorCode.value() << " / category " << errorCode.category().name() << " running " << exe << ": " << errorCode.message());
}
const auto exitCode(proc.exit_code());
if (proc.exit_code())
{
LOGWRN(logger, "Got nonzero exit code " << exitCode << " running " << exe);
}
// return !output1.empty() && output1.back() == '\n' ?
// output1 + output2 : output1 + '\n' + output2;
return output1;
}
template<typename TreeReadFunc>
std::string GetAppManifestValueCommon(
rustLaunchSite::Logger& logger
, TreeReadFunc trf
, const std::vector<std::string>& keyPath
, const bool warn = true)
{
try
{
const tyti::vdf::object& root(trf());
std::shared_ptr<tyti::vdf::object> child;
for (std::size_t i{0}; i < keyPath.size(); ++i)
{
const auto& entry(keyPath.at(i));
// LOGINF(logger, "Processing keyPath[" << i << "]=" << entry);
if (!i)
{
// just validate that the root node name matches the first key
if (entry == root.name)
{
continue;
}
if (warn)
{
LOGWRN(logger, "Root node name \"" << root.name << "\" does not match expected value \"" << entry << "\"; aborting");
}
return {};
}
// if this is the last entry, it must be an attribute
if (keyPath.size() - 1 == i)
{
if (1 == i)
{
// special case: path is only 2 keys long
// LOGINF(logger, "Returning attribute for 2-key path: " << root.attribs.at(entry));
return root.attribs.at(entry);
}
if (child)
{
// LOGINF(logger, "Returning attribute for " << keyPath.size() << "-key path: " << child->attribs.at(entry));
return child->attribs.at(entry);
}
if (warn)
{
LOGWRN(logger, "No child node when processing finaly key \"" << entry << "\" of path");
}
return {};
}
// advance to child at next key
child = (child ? child->childs.at(entry) : root.childs.at(entry));
}
}
catch (const std::exception& ex)
{
if (warn)
{
LOGWRN(logger, "Exception parsing server app manifest: " << ex.what());
}
}
catch (...)
{
if (warn)
{
LOGWRN(logger, "Unknown exception parsing server app manifest");
}
}
return {};
}
std::string GetAppManifestValueFromFile(
rustLaunchSite::Logger& logger
, const std::filesystem::path& appManifestPath
, const std::vector<std::string>& keyPath
, const bool warn = true)
{
return GetAppManifestValueCommon(
logger,
[&appManifestPath]()
{
std::ifstream file(appManifestPath);
return tyti::vdf::read(file);
},
keyPath,
warn
);
}
std::string GetAppManifestValueFromString(
rustLaunchSite::Logger& logger
, const std::string& appManifestData
, const std::vector<std::string>& keyPath
, const bool warn = true)
{
return GetAppManifestValueCommon(
logger,
[&appManifestData]()
{
return tyti::vdf::read(
std::cbegin(appManifestData), std::cend(appManifestData));
},
keyPath,
warn
);
}
}
namespace rustLaunchSite
{
Updater::Updater(
Logger& logger
, std::shared_ptr<const Config> cfgSptr
, std::shared_ptr<Downloader> downloaderSptr
)
: cfgSptr_{cfgSptr}
, downloaderSptr_{downloaderSptr}
, serverInstallPath_{cfgSptr->GetInstallPath()}
, appManifestPath_{cfgSptr->GetInstallPath() / "steamapps/appmanifest_258550.acf"}
, steamCmdPath_{cfgSptr->GetSteamcmdPath()}
, frameworkDllPath_{GetFrameworkDllPath(
serverInstallPath_, cfgSptr->GetUpdateModFrameworkType())}
, logger_{logger}
{
// install path must be either a directory, or a symbolic link to one
if (!IsDirectory(serverInstallPath_))
{
throw std::invalid_argument(std::string("ERROR: Server install path does not exist: ") + serverInstallPath_.string());
}
#if _MSC_VER || defined(__MINGW32__)
if (!std::filesystem::exists(serverInstallPath_ / "RustDedicated.exe"))
#else
if (!std::filesystem::exists(serverInstallPath_ / "RustDedicated"))
#endif
{
throw std::invalid_argument(std::string("ERROR: Rust dedicated server not found in configured install path: ") + serverInstallPath_.string());
}
if (!std::filesystem::exists(appManifestPath_))
{
LOGWRN(logger_, "Steam app manifest file " << appManifestPath_ << " does not exist; automatic Steam updates disabled");
appManifestPath_.clear();
}
if (!std::filesystem::exists(steamCmdPath_))
{
LOGWRN(logger_, "Failed to locate SteamCMD at config file specified path " << steamCmdPath_ << "; automatic Steam updates disabled");
steamCmdPath_.clear();
}
if (
!frameworkDllPath_.empty() && !std::filesystem::exists(frameworkDllPath_))
{
LOGWRN(logger_, "Modding framework DLL '" << frameworkDllPath_ << "' not found; automatic " << ToString(cfgSptr->GetUpdateModFrameworkType(), ToStringCase::TITLE) << " updates disabled");
frameworkDllPath_.clear();
}
// LOGINF(logger_, "Updater initialized. Server updates " << (serverUpdateCheck_ ? "enabled" : "disabled") << ". Oxide updates " << (oxideUpdateCheck_ ? "enabled" : "disabled")<< "");
}
Updater::~Updater() = default;
bool Updater::CheckFramework() const
{
if (cfgSptr_->GetUpdateModFrameworkType() == Config::ModFrameworkType::NONE)
{
return false;
}
const auto& frameworkTitle{
ToString(cfgSptr_->GetUpdateModFrameworkType(), ToStringCase::TITLE)};
const auto& currentVersion(GetInstalledFrameworkVersion());
LOGINF(logger_, "CheckFramework(): Installed " << frameworkTitle << " version: '" << currentVersion << "'");
const auto& latestVersion(GetLatestFrameworkVersion());
LOGINF(logger_, "CheckFramework(): Latest " << frameworkTitle << " version: '" << latestVersion << "'");
return (
!currentVersion.empty() && !latestVersion.empty() &&
currentVersion != latestVersion
);
}
bool Updater::CheckServer() const
{
const std::string& currentServerVersion(GetInstalledServerBuild());
LOGINF(logger_, "CheckServer(): Installed Server version: '" << currentServerVersion << "'");
std::string latestServerVersion;
for (std::size_t i{0}; i < 5 && latestServerVersion.empty(); ++i)
{
if (i)
{
LOGINF(logger_, "CheckServer(): Retrying latest Server version check...");
}
latestServerVersion = GetLatestServerBuild(GetInstalledServerBranch());
}
if (latestServerVersion.empty())
{
LOGWRN(logger_, "CheckServer(): Exhausted latest Server version check attempts");
}
else
{
LOGINF(logger_, "CheckServer(): Latest Server version: '" << latestServerVersion << "'");
}
return (
!currentServerVersion.empty() && !latestServerVersion.empty() &&
currentServerVersion != latestServerVersion
);
}
void Updater::UpdateFramework(const bool suppressWarning) const
{
if (cfgSptr_->GetUpdateModFrameworkType() == Config::ModFrameworkType::NONE)
{
return;
}
const auto& frameworkTitle{
ToString(cfgSptr_->GetUpdateModFrameworkType(), ToStringCase::TITLE)};
// abort if Carbon/Oxide was not already installed
// this should also catch the case that this is called when update checking is
// disabled, but we don't explicity support that
if (frameworkDllPath_.empty())
{
if (!suppressWarning)
{
LOGWRN(logger_, "Cannot update " << frameworkTitle << " because a previous installation was not detected");
}
return;
}
// abort if any required path is empty, meaning it failed validation
if (serverInstallPath_.empty())
{
LOGWRN(logger_, "Cannot update " << frameworkTitle << " because server install path is invalid");
return;
}
// get URL of latest Carbon/Oxide release archive
const auto& url{GetLatestFrameworkURL()};
if (url.empty())
{
LOGWRN(logger_, "Cannot update " << frameworkTitle << " because download URL was not found");
return;
}
// download archive to RAM
const std::vector<char>& archData{downloaderSptr_->GetUrlToVector(url)};
// extract archive
ExtractArchiveData(
logger_, archData, url, frameworkTitle, serverInstallPath_);
}
void Updater::UpdateServer() const
{
// abort if any required path is empty, meaning it failed validation
if (serverInstallPath_.empty() || steamCmdPath_.empty())
{
LOGWRN(logger_, "Cannot update server because install and/or steamcmd path is invalid");
return;
}
std::vector<std::string> args
{
"+force_install_dir", serverInstallPath_.string(),
"+login", "anonymous",
"+app_update", "258550"
};
if
(
std::string betaKey(GetInstalledServerBranch());
!betaKey.empty()
)
{
args.emplace_back("-beta");
args.emplace_back(std::move(betaKey));
}
args.emplace_back("validate");
args.emplace_back("+quit");
RunExecutable(logger_, steamCmdPath_.string(), args);
}
std::string Updater::GetInstalledFrameworkVersion() const
{
std::string retVal;
if (frameworkDllPath_.empty()) { return retVal; }
#if _MSC_VER || defined(__MINGW32__)
// TODO: make powershell path configurable?
const auto& psPath(
boost::process::environment::find_executable("powershell.exe"));
if (psPath.empty())
{
LOGWRN(logger_, "Failed to find powershell; you may need to install mono-utils or similar");
return retVal;
}
retVal = RunExecutable(
logger_,
psPath,
{
"-Command",
"(Get-Item '" + frameworkDllPath_.string() +
"').VersionInfo.ProductVersion"
}
);
// for some reason this has a newline at the end, so strip that off
while (retVal.back() == '\r' || retVal.back() == '\n') { retVal.pop_back(); }
// strip off anything starting with `+` or `-` if present
return retVal.substr(0, retVal.find_first_of("+-"));
#else
// TODO: make monodis path configurable?
const auto& monodisPath(
boost::process::environment::find_executable("monodis"));
if (monodisPath.empty())
{
LOGWRN(logger_, "Failed to find monodis; you may need to install mono-utils or similar");
return retVal;
}
const auto& output(RunExecutable(
logger_, monodisPath, {"--assembly", frameworkDllPath_.string()}));
// attempt to extract version from output
std::smatch match;
if (std::regex_search(
output, match, std::regex{R"(Version: *[0-9]+\.[0-9]+\.[0-9]+)"}))
{
const auto& matchStr(match.begin()->str());
std::smatch match2;
if (std::regex_search(
matchStr, match2, std::regex{R"([0-9]+\.[0-9]+\.[0-9]+)"}))
{
retVal = match2.begin()->str();
}
}
if (retVal.empty())
{
LOGWRN(logger_, "Failed to extract Carbon version from monodis output");
}
// return version number or empty string
return retVal;
#endif
}
std::string Updater::GetInstalledServerBranch() const
{
const auto& branch(GetAppManifestValueFromFile(
logger_
, appManifestPath_
, { "AppState", "UserConfig", "BetaKey" }
, false));
// clean installs may not have a branch listed in appmanifest; assume public
return branch.empty() ? "public" : branch;
}
std::string Updater::GetInstalledServerBuild() const
{
return GetAppManifestValueFromFile(
logger_, appManifestPath_, { "AppState", "buildid" });
}
std::string Updater::GetLatestServerBuild(const std::string_view branch) const
{
// abort if any required path is empty, meaning it failed validation
if (serverInstallPath_.empty() || steamCmdPath_.empty())
{
LOGWRN(logger_, "Cannot check for server updates because install and/or steamcmd path is invalid");
return {};
}
std::string output(RunExecutable(
logger_,
steamCmdPath_.string(),
{
"+force_install_dir", serverInstallPath_.string(),
"+login", "anonymous",
"+app_info_update", "1",
"+app_info_print", "258550",
"+logoff",
"+quit"
}
));
// LOGINF(logger_, "SteamCMD output: " << output);
const auto startPos(output.find("\"258550\""));
if (std::string::npos == startPos)
{
LOGWRN(logger_, "Failed to extract latest server version from SteamCMD output (startPos=" << startPos << "):\n" << output);
return {};
}
output = output.substr(startPos);
const auto logoffPos(output.find("Logging off current session..."));
output = output.substr(0, logoffPos);
// LOGINF(logger_, "Truncated SteamCMD output to startPos=" << startPos << ": " << output);
//258550.depots.branches.<branch>.buildid
output = GetAppManifestValueFromString(
logger_,
output,
{
"258550", "depots", "branches",
std::string(branch.empty() ? "public" : branch),
"buildid"
}
);
// LOGINF(logger_, "Extracted buildid from SteamCMD output: " << output);
return output;
}
std::string Updater::GetLatestFrameworkURL() const
{
if (!downloaderSptr_)
{
LOGWRN(logger_, "Downloader handle is null");
return {};
}
const auto modFrameworkType{cfgSptr_->GetUpdateModFrameworkType()};
const auto frameworkURL{GetFrameworkURL(modFrameworkType)};
const auto& frameworkInfo{downloaderSptr_->GetUrlToString(frameworkURL)};
const auto frameworkAsset{GetFrameworkAsset(modFrameworkType)};
const auto frameworkTitle{ToString(modFrameworkType, ToStringCase::TITLE)};
try
{
const auto& j(nlohmann::json::parse(frameworkInfo));
// "assets" node is a list of release files, so find the one of interest
for (const auto& asset : j["assets"])
{
if (asset["name"].get<std::string>() == frameworkAsset)
{
return asset["browser_download_url"];
}
}
}
catch (const nlohmann::json::exception& e)
{
LOGWRN(logger_, "Exception extracting download URL from " << frameworkTitle << " releases JSON: " << e.what());
LOGWRN(logger_, "\t...Input string: '" << frameworkInfo << "'");
return {};
}
LOGWRN(logger_, "Failed to extract download URL from " << frameworkTitle << " releases JSON");
return {};
}
std::string Updater::GetLatestFrameworkVersion() const
{
if (!downloaderSptr_)
{
LOGWRN(logger_, "Downloader handle is null");
return {};
}
const auto modFrameworkType{cfgSptr_->GetUpdateModFrameworkType()};
const auto frameworkURL{GetFrameworkURL(modFrameworkType)};
const auto& frameworkInfo{downloaderSptr_->GetUrlToString(frameworkURL)};
const auto frameworkTitle{ToString(modFrameworkType, ToStringCase::TITLE)};
try
{
const auto& j(nlohmann::json::parse(frameworkInfo));
if (!j.contains("name"))
{
LOGWRN(logger_, "Data received from frameworkURL=" << frameworkURL << " missing JSON 'name': " << frameworkInfo);
return {};
}
switch (modFrameworkType)
{
case Config::ModFrameworkType::NONE: break;
// need to process the Carbon release name
case Config::ModFrameworkType::CARBON:
{
// Carbon release versions look like "Production Build — v1.2024.1033.4309"
// ...but we only want the part after the 'v', so strip the rest off
static const std::string_view CARBON_PREFIX{"Production Build — v"};
const std::string& carbonVersion(j["name"]);
// bail if the version string doesn't start with the prefix string, as it
// means release naming has changed
if (carbonVersion.find(CARBON_PREFIX) != 0)
{
LOGWRN(logger_, "Carbon release prefix not found in version string: " << carbonVersion);
return {};
}
// return everything *after* the prefix string
return carbonVersion.substr(CARBON_PREFIX.length());
}
// just return the raw release name for Oxide
case Config::ModFrameworkType::OXIDE: return j["name"];
}
LOGWRN(logger_, "Unsupported plugin framework");
return {};
}
catch(const nlohmann::json::exception& e)
{
LOGWRN(logger_, "JSON exception while extracting version name from " << frameworkTitle << " release data: " << e.what() << "\n\t...Input data: " << frameworkInfo);
return {};
}
catch (const std::exception& e)
{
LOGWRN(logger_, "General exception while extracting version name from " << frameworkTitle << " release data: " << e.what() << "\n\t...Input data: " << frameworkInfo);
return {};
}
catch (...)
{
LOGWRN(logger_, "Unknown exception while extracting version name from " << frameworkTitle << " release data\n\t...Input data: " << frameworkInfo);
return {};
}
}
}