forked from Rollocraft/CS2MultiplayerMod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModsCheck.cs
More file actions
383 lines (338 loc) · 16.1 KB
/
Copy pathModsCheck.cs
File metadata and controls
383 lines (338 loc) · 16.1 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Colossal.IO.AssetDatabase;
using Colossal.PSI.Common;
using CS2MPMod.Core.Diagnostics;
using CS2MPMod.Game.Diagnostics;
using CS2MPMod.Localization;
using Game.Modding;
using Game.SceneFlow;
// Aliased because the enclosing namespace's own Mod type would otherwise win here.
using PlaysetMod = Colossal.PSI.Common.Mod;
namespace CS2MPMod.Game
{
/// <summary>
/// Finds every mod other than this one that is live for the running game. Hosting and
/// joining are both refused while any is present: nothing in the sync layer accounts
/// for a third party changing prefabs, tools or the simulation, so one such mod on one
/// side is enough to desync the session or crash the other player.
///
/// The active Paradox Mods playset is the source of truth wherever it can be read: it
/// tracks what the player toggles live, and it is the only source that also lists
/// asset-only mods (maps, prop and prefab packs), which load no assembly and so are
/// invisible to the mod loader. Only the <em>active</em> playset is read; mods sitting in
/// the player's other playsets are not enabled for this run and are ignored.
///
/// It is re-read on the rescan interval rather than once, for two reasons: the playset
/// reads empty for the first seconds of a run (the platform reports no active playset
/// until it has signed in and synced, which is why the game's own startup log can say
/// "(none)"), and a mod toggled off mid-session has to clear the gate without a restart.
///
/// The loaded-assembly list is only a fallback, for when no playset is ever readable
/// (offline, or a local development install). It cannot clear until the game restarts,
/// so a block that came from it says so.
/// </summary>
internal static class ModsCheck
{
/// <summary>
/// This mod's Paradox Mods id (Properties/PublishConfiguration.xml). Recognises our
/// own playset entry when it carries no local path to match on.
/// </summary>
private const string OwnPlatformId = "150432";
/// <summary>Names listed before the rest collapse into a "+N more" tail.</summary>
private const int MaxNamesListed = 6;
/// <summary>Cap per name, so one absurdly long mod title cannot flood the UI.</summary>
private const int MaxNameLength = 64;
/// <summary>
/// The blocking state is read from a getter binding on every UI frame, and a scan
/// walks the loaded mod list, so results are held for this long in between.
/// </summary>
private const long RescanMilliseconds = 5000;
/// <summary>Marker the fault string carries so the status screen can classify it.</summary>
public const string FaultMarker = "Unsupported mods enabled:";
private static readonly object Gate = new object();
private static readonly Stopwatch Clock = Stopwatch.StartNew();
private static string[] _cached = Array.Empty<string>();
private static long _scannedAt = long.MinValue;
private static bool _playsetEverPopulated;
private static bool _restartRequired;
private static string _ownFolder;
private static bool _scanWarned;
/// <summary>
/// Display names of the other live mods, sorted, or an empty array when the only
/// mod running is this one. A scan that fails outright reports empty: a detection
/// fault must not lock the player out of multiplayer altogether.
/// </summary>
public static string[] OtherModNames
{
get
{
lock (Gate)
{
long now = Clock.ElapsedMilliseconds;
if (_scannedAt != long.MinValue && now - _scannedAt < RescanMilliseconds)
return _cached;
_scannedAt = now;
string[] previous = _cached;
_cached = Scan();
LogChange(previous, _cached);
return _cached;
}
}
}
public static bool AnyOtherMods => OtherModNames.Length > 0;
/// <summary>
/// Localized sentence naming the offending mods for the blocking banner, or "" when
/// nothing else is running (which hides the banner).
/// </summary>
public static string BlockText(bool ignored = false)
{
string[] names = OtherModNames;
if (names.Length == 0) return "";
// Reading the names is what refreshes _restartRequired, so the order matters.
if (ignored)
return L10n.F(L10n.Key.UiModsIgnored, NamesText(names));
return L10n.F(_restartRequired ? L10n.Key.UiModsBlockedRestart : L10n.Key.UiModsBlocked,
NamesText(names));
}
/// <summary>
/// English detail for the session fault and the log. Faults stay English on purpose:
/// the status screen classifies them by substring and localizes for display.
/// </summary>
public static string FaultDetail()
{
string[] names = OtherModNames;
return names.Length == 0 ? "" : FaultMarker + " " + NamesText(names);
}
/// <summary>
/// The other live mods for a session log line: <c>none</c>, or the names in brackets.
/// Recorded whether or not they block anything - with the compatibility check bypassed
/// they are the first thing to suspect in a desync, so the log has to say they were there.
/// </summary>
public static string Summary()
{
string[] names = OtherModNames;
return names.Length == 0 ? "none" : "[" + NamesText(names) + "]";
}
/// <summary>Comma-separated names, truncated to <see cref="MaxNamesListed"/>.</summary>
private static string NamesText(string[] names)
{
int listed = names.Length < MaxNamesListed ? names.Length : MaxNamesListed;
string text = string.Join(", ", names, 0, listed);
int rest = names.Length - listed;
return rest > 0 ? text + " (+" + rest + ")" : text;
}
private static string[] Scan()
{
// Not before our own folder is known: a read that cannot recognise this mod's
// own entry would list it as an offender and block multiplayer outright.
string[] fromPlayset = Array.Empty<string>();
bool readPlayset = !string.IsNullOrEmpty(OwnFolder()) &&
TryReadActivePlayset(out fromPlayset);
if (readPlayset && fromPlayset.Length > 0) _playsetEverPopulated = true;
// An empty read only counts once the playset has proved it reports anything at
// all. Before that it is indistinguishable from a platform that has not finished
// starting up, and trusting it would open the gate for the first seconds of
// every run.
if (readPlayset && (_playsetEverPopulated || fromPlayset.Length > 0))
{
Array.Sort(fromPlayset, StringComparer.OrdinalIgnoreCase);
_restartRequired = false;
return fromPlayset;
}
var names = new List<string>();
AddLoadedMods(names, new HashSet<string>(StringComparer.OrdinalIgnoreCase));
names.Sort(StringComparer.OrdinalIgnoreCase);
_restartRequired = names.Count > 0;
return names.ToArray();
}
/// <summary>
/// The mods the active playset has enabled, as the game's own mod loader reads them
/// on startup. The call resolves from the platform's local mod cache, so it neither
/// blocks on the network nor needs the player to be online - it does wait out an
/// asynchronous call on the calling thread, which is why the rescan interval and not
/// the UI frame decides how often it runs. False when no backend could be asked at
/// all, which is distinct from a backend answering "nothing enabled".
///
/// The Paradox backend is reached by reflection over the instance the platform
/// already created, deliberately without naming its assembly: a declared reference
/// the running copy of the game cannot resolve makes it refuse to load this mod at
/// all - the same reason the Steam relay lives in its own runtime-loaded assembly.
/// </summary>
private static bool TryReadActivePlayset(out string[] names)
{
names = Array.Empty<string>();
try
{
PlatformManager platform = PlatformManager.instance;
if (platform == null) return false;
foreach (IModSupport backend in platform.modsBackends)
{
if (backend == null) continue;
MethodInfo method = backend.GetType().GetMethod(
"GetModsInActivePlaysetSync",
BindingFlags.Public | BindingFlags.Instance,
null, Type.EmptyTypes, null);
if (method == null) continue;
if (!(method.Invoke(backend, null) is IEnumerable<PlaysetMod> mods)) continue;
var found = new List<string>();
foreach (PlaysetMod mod in mods)
{
if (IsSelf(mod)) continue;
string name = PlaysetName(mod);
if (!string.IsNullOrEmpty(name)) found.Add(name);
}
names = found.ToArray();
return true;
}
}
catch (Exception ex)
{
WarnOnce("active playset", ex);
}
return false;
}
private static void AddLoadedMods(List<string> names, HashSet<string> seen)
{
try
{
ModManager manager = GameManager.instance != null ? GameManager.instance.modManager : null;
if (manager == null) return;
foreach (ModManager.ModInfo info in manager)
{
if (info == null || info.asset == null) continue;
if (!info.asset.isMod || !info.isLoaded) continue;
if (IsSelf(info)) continue;
Add(names, seen, LoadedName(info));
}
}
catch (Exception ex)
{
WarnOnce("loaded mods", ex);
}
}
private static void Add(List<string> names, HashSet<string> seen, string name)
{
if (string.IsNullOrEmpty(name)) return;
if (seen.Add(name)) names.Add(name);
}
private static bool IsSelf(PlaysetMod mod)
{
if (string.Equals(mod.id, OwnPlatformId, StringComparison.Ordinal)) return true;
return SharesOwnFolder(mod.path);
}
private static bool IsSelf(ModManager.ModInfo info)
{
string own = typeof(Mod).Assembly.GetName().Name;
if (string.Equals(info.asset.name, own, StringComparison.OrdinalIgnoreCase)) return true;
return SharesOwnFolder(info.asset.path);
}
/// <summary>
/// Whether a reported path belongs to this mod. Compared both ways round because
/// the playset reports a mod's root folder while our own assembly can sit in a
/// subfolder of it.
/// </summary>
private static bool SharesOwnFolder(string path)
{
string own = OwnFolder();
if (string.IsNullOrEmpty(own) || string.IsNullOrEmpty(path)) return false;
string other = Normalize(path);
if (other.Length == 0) return false;
return IsSameOrUnder(own, other) || IsSameOrUnder(other, own);
}
/// <summary>
/// Containment that stops at a path separator, so a neighbouring folder whose name
/// merely starts with ours ("CS2MPModExtras") is not mistaken for this mod.
/// </summary>
private static bool IsSameOrUnder(string path, string root)
{
if (path.Length == root.Length)
return string.Equals(path, root, StringComparison.OrdinalIgnoreCase);
return path.Length > root.Length &&
path[root.Length] == '/' &&
path.StartsWith(root, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// This mod's own folder. Resolution is retried until it succeeds - the mod loader
/// has no asset for us yet during the earliest part of startup.
/// </summary>
private static string OwnFolder()
{
if (!string.IsNullOrEmpty(_ownFolder)) return _ownFolder;
try
{
ModManager manager = GameManager.instance != null ? GameManager.instance.modManager : null;
if (manager != null &&
manager.TryGetExecutableAsset(typeof(Mod).Assembly, out ExecutableAsset asset) &&
asset != null && !string.IsNullOrEmpty(asset.path))
_ownFolder = Normalize(Path.GetDirectoryName(asset.path));
}
catch (Exception)
{
// Falls through to the assembly's own location below.
}
if (string.IsNullOrEmpty(_ownFolder))
{
try { _ownFolder = Normalize(Path.GetDirectoryName(typeof(Mod).Assembly.Location)); }
catch (Exception) { }
}
return _ownFolder;
}
private static string Normalize(string path)
{
if (string.IsNullOrEmpty(path)) return "";
return path.Replace('\\', '/').TrimEnd('/');
}
private static string PlaysetName(PlaysetMod mod)
{
string name = mod.displayName;
if (string.IsNullOrEmpty(name)) name = mod.id;
return Clip(name);
}
private static string LoadedName(ModManager.ModInfo info)
{
string name = info.asset.name;
if (string.IsNullOrEmpty(name)) name = info.name;
return Clip(name);
}
private static string Clip(string name)
{
if (string.IsNullOrEmpty(name)) return "";
name = name.Trim();
return name.Length > MaxNameLength ? name.Substring(0, MaxNameLength) : name;
}
/// <summary>
/// Reports the set whenever it changes, ungated: which other mods were live is one of the
/// few facts every bug report needs, and with the compatibility check bypassed the mod
/// that broke the session is in this list rather than in ours. Rare enough for an event -
/// it only fires when the set actually changes - and it names the source it read, which
/// is what a player needs when the block names a mod they have already turned off.
/// </summary>
private static void LogChange(string[] previous, string[] current)
{
if (previous.Length == current.Length)
{
bool same = true;
for (int i = 0; i < current.Length; i++)
if (!string.Equals(previous[i], current[i], StringComparison.Ordinal)) { same = false; break; }
if (same) return;
}
string source = _restartRequired ? "loaded assemblies (restart to clear)" : "active playset";
SyncLog.Event(LogTopic.Startup,
current.Length == 0
? "No other mods are active - multiplayer is available."
: "Other mods are active, from the " + source + ": " +
string.Join(", ", current) + ".");
}
private static void WarnOnce(string source, Exception ex)
{
if (_scanWarned) return;
_scanWarned = true;
SyncLog.Warn(LogTopic.Startup, "Could not read the " + source + " (" + ex.Message +
"); other mods cannot be detected from it.");
}
}
}