game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
steam_appinfo_parser.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// steam_appinfo_parser.cpp
4// ==============================================================================
5// Implementation of Steam appinfo.vdf binary parser
6// ==============================================================================
7//
8// appinfo.vdf v29 format (magic 0x07564429):
9//
10// [Header]
11// magic: uint32 (0x07564429)
12// universe: uint32 (1 = public)
13// string_table_offset: uint64 (byte offset to string table at end of file)
14//
15// [App Records] (repeated until appid == 0)
16// appid: uint32 (0 = end sentinel)
17// size: uint32 (byte count of the record data that follows)
18// [Record Data - 'size' bytes]
19// info_state: uint32
20// last_updated: uint32
21// access_token: uint64
22// sha1: 20 bytes
23// change_number: uint32
24// sha1_data: 20 bytes
25// [Binary VDF data - remaining bytes]
26//
27// [String Table] (at string_table_offset)
28// count: uint32 (number of strings)
29// strings: null-terminated UTF-8 strings, concatenated
30//
31// Binary VDF uses string table indices (uint32) as key names instead of
32// inline strings. Value types are the same as standard binary VDF.
33// ==============================================================================
34
36#include "logger.h"
37
38#include <algorithm>
39#include <cstring>
40#include <fstream>
41
42// ==============================================================================
43// SteamAppVdfInfo - Launch entry selection
44// ==============================================================================
45
46std::optional<SteamLaunchEntry> SteamAppVdfInfo::getProtonLaunchEntry() const
47{
48 // Collect all Windows-compatible entries
49 std::vector<const SteamLaunchEntry*> windowsEntries;
50 for (const auto& entry : launchEntries)
51 {
52 if (entry.supportsWindows() && !entry.executable.empty())
53 {
54 windowsEntries.push_back(&entry);
55 }
56 }
57
58 if (windowsEntries.empty())
59 return std::nullopt;
60
61 // Prefer default type entries
62 for (const auto* entry : windowsEntries)
63 {
64 if (entry->isDefault())
65 return *entry;
66 }
67
68 // Fall back to first Windows entry
69 return *windowsEntries.front();
70}
71
72std::optional<SteamLaunchEntry> SteamAppVdfInfo::getNativeLaunchEntry() const
73{
74 std::vector<const SteamLaunchEntry*> linuxEntries;
75 for (const auto& entry : launchEntries)
76 {
77 if (entry.supportsLinux() && !entry.executable.empty())
78 {
79 linuxEntries.push_back(&entry);
80 }
81 }
82
83 if (linuxEntries.empty())
84 return std::nullopt;
85
86 for (const auto* entry : linuxEntries)
87 {
88 if (entry->isDefault())
89 return *entry;
90 }
91
92 return *linuxEntries.front();
93}
94
95// ==============================================================================
96// SteamAppInfoParser - File loading
97// ==============================================================================
98
99bool SteamAppInfoParser::load(const std::filesystem::path& path)
100{
101 std::ifstream file(path, std::ios::binary | std::ios::ate);
102 if (!file.is_open())
103 {
104 Logger::error("[AppInfo] Failed to open: {}", path.string());
105 return false;
106 }
107
108 auto fileSize = file.tellg();
109 if (fileSize < 16)
110 {
111 Logger::error("[AppInfo] File too small: {} bytes", static_cast<size_t>(fileSize));
112 return false;
113 }
114
115 // Guard against absurdly large files (appinfo.vdf is typically <20 MB).
116 constexpr std::streamoff kMaxFileSize = 512LL * 1024 * 1024; // 512 MB
117 if (fileSize > kMaxFileSize)
118 {
119 Logger::error("[AppInfo] File exceeds maximum allowed size ({} bytes): {}",
120 static_cast<size_t>(fileSize), path.string());
121 return false;
122 }
123
124 file.seekg(0);
125 data_.resize(static_cast<size_t>(fileSize));
126 file.read(reinterpret_cast<char*>(data_.data()), fileSize);
127 file.close();
128
129 // Read header
130 std::memcpy(&version_, data_.data(), 4);
131 if (version_ == MAGIC_V27 || version_ == MAGIC_V28)
132 {
133 // Pre-June-2024 format with inline keys (no string table). Recognised
134 // but not fully parsed — returning false here causes the library scan
135 // to fall back to ACF manifests, which still yields the installed-game
136 // list without appinfo metadata.
137 Logger::warn("[AppInfo] Detected legacy appinfo.vdf format 0x{:08X}. "
138 "Update your Steam client to restore metadata parsing; "
139 "falling back to ACF manifests.",
140 version_);
141 return false;
142 }
143 if (version_ != MAGIC_V29)
144 {
146 "[AppInfo] Unknown format version: 0x{:08X} (expected 0x{:08X}, 0x{:08X}, or 0x{:08X})",
147 version_, MAGIC_V27, MAGIC_V28, MAGIC_V29);
148 return false;
149 }
150
151 // Read string table offset (bytes 8-15)
152 uint64_t stOffset = 0;
153 std::memcpy(&stOffset, data_.data() + 8, 8);
154
155 if (stOffset >= data_.size())
156 {
157 Logger::error("[AppInfo] String table offset out of bounds: {}", stOffset);
158 return false;
159 }
160
161 if (!loadStringTable(static_cast<size_t>(stOffset)))
162 {
163 Logger::error("[AppInfo] Failed to parse string table");
164 return false;
165 }
166
167 if (!indexAppRecords())
168 {
169 Logger::error("[AppInfo] Failed to index app records");
170 return false;
171 }
172
173 Logger::info("[AppInfo] Loaded {} apps, {} strings from {}", appOffsets_.size(),
174 stringTable_.size(), path.filename().string());
175 return true;
176}
177
178bool SteamAppInfoParser::loadStringTable(size_t offset)
179{
180 if (offset + 4 > data_.size())
181 return false;
182
183 uint32_t count = 0;
184 std::memcpy(&count, data_.data() + offset, 4);
185 offset += 4;
186
187 stringTable_.clear();
188 // Cap reserve to avoid OOM from a malformed/corrupt count field.
189 constexpr uint32_t kMaxStringCount = 1'000'000;
190 stringTable_.reserve(std::min(count, kMaxStringCount));
191
192 for (uint32_t i = 0; i < count && offset < data_.size(); ++i)
193 {
194 // Read null-terminated string
195 const char* start = reinterpret_cast<const char*>(data_.data() + offset);
196 size_t maxLen = data_.size() - offset;
197 size_t len = strnlen(start, maxLen);
198
199 stringTable_.emplace_back(start, len);
200 if (len == maxLen)
201 break; // no null terminator in remaining data — stop to prevent OOB
202 offset += len + 1; // skip null terminator
203 }
204
205 return true;
206}
207
208bool SteamAppInfoParser::indexAppRecords()
209{
210 appOffsets_.clear();
211
212 // App records start after 16-byte header (magic + universe + string_table_offset)
213 size_t offset = 16;
214
215 while (offset + 8 <= data_.size())
216 {
217 uint32_t appId = 0;
218 std::memcpy(&appId, data_.data() + offset, 4);
219 offset += 4;
220
221 if (appId == 0) // End sentinel
222 break;
223
224 uint32_t recordSize = 0;
225 std::memcpy(&recordSize, data_.data() + offset, 4);
226 offset += 4;
227
228 // Use subtraction to avoid size_t + uint32_t overflow on large offsets
229 if (recordSize > data_.size() - offset)
230 {
231 Logger::warn("[AppInfo] Truncated record for app {}", appId);
232 break;
233 }
234
235 appOffsets_[appId] = {offset, recordSize};
236 offset += recordSize;
237 }
238
239 return true; // Empty app list is valid (e.g., fresh Steam install with no games)
240}
241
242// ==============================================================================
243// SteamAppInfoParser - App record parsing
244// ==============================================================================
245
246std::optional<SteamAppVdfInfo> SteamAppInfoParser::getAppInfo(uint32_t appId) const
247{
248 auto it = appOffsets_.find(appId);
249 if (it == appOffsets_.end())
250 return std::nullopt;
251
252 auto [offset, size] = it->second;
253 return parseAppRecord(offset, size);
254}
255
256bool SteamAppInfoParser::hasApp(uint32_t appId) const
257{
258 return appOffsets_.find(appId) != appOffsets_.end();
259}
260
261SteamAppVdfInfo SteamAppInfoParser::parseAppRecord(size_t offset, size_t size) const
262{
263 SteamAppVdfInfo info;
264
265 // Skip the 60-byte record header to reach binary VDF data
266 size_t vdfStart = offset + APP_RECORD_HEADER_SIZE;
267 size_t vdfEnd = offset + size;
268
269 if (vdfStart >= vdfEnd || vdfEnd > data_.size())
270 return info;
271
272 auto vdfData = parseVdfBinary(vdfStart, vdfEnd);
273
274 // Navigate: root -> appinfo -> common for name/type
275 if (auto* appinfo = getNestedMap(vdfData, "appinfo"))
276 {
277 if (auto* common = getNestedMap(*appinfo, "common"))
278 {
279 info.name = getNestedString(*common, "name");
280 info.type = getNestedString(*common, "type");
281 }
282
283 // Navigate: appinfo -> config -> launch for executable configs
284 if (auto* config = getNestedMap(*appinfo, "config"))
285 {
286 if (auto* launch = getNestedMap(*config, "launch"))
287 {
288 for (const auto& [key, val] : *launch)
289 {
290 if (val.type != VdfValue::MAP)
291 continue;
292
293 int idx = -1;
294 try
295 {
296 idx = std::stoi(key);
297 }
298 catch (...)
299 {
300 continue;
301 }
302
303 info.launchEntries.push_back(parseLaunchEntry(val.mapVal, idx));
304 }
305
306 // Sort by index for deterministic ordering
307 std::sort(info.launchEntries.begin(), info.launchEntries.end(),
308 [](const auto& a, const auto& b) { return a.index < b.index; });
309 }
310 }
311 }
312
313 // Extract appId from the VDF data
314 if (auto* appinfo = getNestedMap(vdfData, "appinfo"))
315 {
316 auto it = appinfo->find("appid");
317 if (it != appinfo->end())
318 {
319 info.appId = it->second.asInt();
320 }
321 }
322
323 return info;
324}
325
326SteamLaunchEntry SteamAppInfoParser::parseLaunchEntry(const VdfMap& data, int index) const
327{
328 SteamLaunchEntry entry;
329 entry.index = index;
330 entry.executable = getNestedString(data, "executable");
331 entry.arguments = getNestedString(data, "arguments");
332 entry.description = getNestedString(data, "description");
333 entry.type = getNestedString(data, "type");
334
335 // OS info is nested under "config" within the launch entry
336 if (auto* config = getNestedMap(data, "config"))
337 {
338 entry.oslist = getNestedString(*config, "oslist");
339 entry.osarch = getNestedString(*config, "osarch");
340 }
341
342 return entry;
343}
344
345// ==============================================================================
346// SteamAppInfoParser - Binary VDF parsing (v29 with string table)
347// ==============================================================================
348
349SteamAppInfoParser::VdfMap SteamAppInfoParser::parseVdfBinary(size_t offset, size_t endOffset) const
350{
351 return parseVdfBinaryRecursive(offset, endOffset, 0);
352}
353
354SteamAppInfoParser::VdfMap
355SteamAppInfoParser::parseVdfBinaryRecursive(size_t& offset, size_t endOffset, int depth) const
356{
357 VdfMap result;
358
359 if (depth > 64)
360 return result;
361
362 while (offset < endOffset)
363 {
364 uint8_t typeTag = data_[offset];
365 offset += 1;
366
367 if (typeTag == static_cast<uint8_t>(VdfType::End))
368 return result;
369
370 // Read key as string table index (uint32)
371 if (offset + 4 > endOffset)
372 break;
373
374 uint32_t keyIndex = 0;
375 std::memcpy(&keyIndex, data_.data() + offset, 4);
376 offset += 4;
377
378 std::string key = getStringByIndex(keyIndex);
379
380 VdfValue value;
381
382 switch (static_cast<VdfType>(typeTag))
383 {
384 case VdfType::Nested:
385 {
386 value.type = VdfValue::MAP;
387 value.mapVal = parseVdfBinaryRecursive(offset, endOffset, depth + 1);
388 break;
389 }
390 case VdfType::String:
391 {
392 value.type = VdfValue::STRING;
393 const char* start = reinterpret_cast<const char*>(data_.data() + offset);
394 size_t maxLen = endOffset - offset;
395 size_t len = strnlen(start, maxLen);
396 value.strVal.assign(start, len);
397 offset += len + (len < maxLen ? 1 : 0); // +1 for null terminator if present
398 break;
399 }
400 case VdfType::Int32:
401 case VdfType::Color:
402 case VdfType::Pointer:
403 {
404 value.type = VdfValue::INT32;
405 if (offset + 4 > endOffset)
406 return result; // truncated data — stop cleanly
407 std::memcpy(&value.intVal, data_.data() + offset, 4);
408 offset += 4;
409 break;
410 }
411 case VdfType::Float32:
412 {
413 value.type = VdfValue::INT32;
414 if (offset + 4 > endOffset)
415 return result; // truncated data — stop cleanly
416 // Store raw bits — we don't need float values
417 std::memcpy(&value.intVal, data_.data() + offset, 4);
418 offset += 4;
419 break;
420 }
421 case VdfType::Int64:
422 case VdfType::Int64Unsigned:
423 {
424 value.type = VdfValue::INT64;
425 if (offset + 8 > endOffset)
426 return result; // truncated data — stop cleanly
427 std::memcpy(&value.int64Val, data_.data() + offset, 8);
428 offset += 8;
429 break;
430 }
431 default:
432 // Unknown type — stop parsing this level
433 Logger::debug("[AppInfo] Unknown VDF type 0x{:02X} at offset {}", typeTag, offset - 5);
434 return result;
435 }
436
437 result[key] = std::move(value);
438 }
439
440 return result;
441}
442
443// ==============================================================================
444// SteamAppInfoParser - Helpers
445// ==============================================================================
446
447std::string SteamAppInfoParser::getStringByIndex(uint32_t index) const
448{
449 if (index < stringTable_.size())
450 return stringTable_[index];
451 return std::to_string(index);
452}
453
454const SteamAppInfoParser::VdfMap* SteamAppInfoParser::getNestedMap(const VdfMap& root,
455 const std::string& key) const
456{
457 auto it = root.find(key);
458 if (it != root.end())
459 return it->second.asMap();
460 return nullptr;
461}
462
463std::string SteamAppInfoParser::getNestedString(const VdfMap& map, const std::string& key) const
464{
465 auto it = map.find(key);
466 if (it != map.end() && it->second.type == VdfValue::STRING)
467 return it->second.strVal;
468 return {};
469}
470
471uint32_t SteamAppInfoParser::getNestedInt(const VdfMap& map, const std::string& key) const
472{
473 auto it = map.find(key);
474 if (it != map.end() && it->second.type == VdfValue::INT32)
475 return it->second.intVal;
476 return 0;
477}
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
std::optional< SteamAppVdfInfo > getAppInfo(uint32_t appId) const
Get parsed app info for a specific app ID.
bool load(const std::filesystem::path &path)
Load and index an appinfo.vdf file.
bool hasApp(uint32_t appId) const
Check if a specific app ID exists in the cache.
Parsed metadata for a single Steam app from appinfo.vdf.
std::string name
App name from common section.
std::optional< SteamLaunchEntry > getProtonLaunchEntry() const
Get the best launch entry for running under Proton.
std::vector< SteamLaunchEntry > launchEntries
All launch configurations.
std::string type
App type: "Game", "Tool", "DLC", "Demo", etc.
std::optional< SteamLaunchEntry > getNativeLaunchEntry() const
Get the best launch entry for native Linux execution.
A single launch configuration from appinfo.vdf.
int index
Launch entry index (0, 1, 2, ...).
std::string description
User-facing description (e.g., "DirectX 12 mode").
std::string osarch
Architecture: "32", "64", or empty.
std::string executable
Executable path relative to install dir (e.g., "game.exe").
std::string type
Launch type: "default", "none", "option1", "option2", etc.
std::string arguments
Default launch arguments.
std::string oslist
Comma-separated OS list: "windows", "linux", "macos".