Repository navigation
Expand file tree
/
Copy pathConfig.cs
More file actions
315 lines (276 loc) · 12.2 KB
/
Copy pathConfig.cs
File metadata and controls
315 lines (276 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using GTerm.Extensions;
namespace GTerm
{
internal class JsonConfig
{
public string[]? ExclusionPatterns { get; set; }
public bool ArchiveLogs { get; set; }
public bool MonitorGmod { get; set; }
public bool StartAsGmod { get; set; }
public bool? API { get; set; }
public string? APISecret { get; set; }
public int? APIPort { get; set; }
public bool? MCP { get; set; }
public int? MCPCollectionWindowMs { get; set; }
public int? MCPPort { get; set; }
public string? MCPSecret { get; set; }
public bool SkipGameFiles { get; set; }
public bool SkipModule { get; set; }
public bool SkipModuleUpdate { get; set; }
public string? Realm { get; set; }
public string? GmodRoot { get; set; }
public int? ModulePort { get; set; }
/// <summary>Tool packages the user accepted, written by GTerm itself (see MCP/ToolPackages.cs).</summary>
public ToolPackageConsentEntry[]? ToolPackageConsent { get; set; }
}
internal class ToolPackageConsentEntry
{
/// <summary>Server IPv4, or "local".</summary>
public string? Scope { get; set; }
public string? Package { get; set; }
public string? Hash { get; set; }
public DateTime? AcceptedAt { get; set; }
}
/// <summary>The realm the module binary is named for: its gmsv_/gmcl_ prefix.</summary>
internal enum ModuleRealm
{
/// <summary>gmcl_gterm_*.dll</summary>
Client,
/// <summary>gmsv_gterm_*.dll, the default.</summary>
Server,
}
internal class Config
{
internal List<Regex> ExclusionPatterns { get; set; } = [];
internal bool ArchiveLogs { get; set; } = true;
internal bool MonitorGmod { get; set; } = true;
internal bool StartAsGmod { get; set; } = false;
internal bool API { get; set; } = false;
internal string? APISecret { get; set; }
internal int APIPort { get; set; }
internal bool MCP { get; set; } = false;
internal int MCPCollectionWindowMs { get; set; } = 1000;
internal int MCPPort { get; set; } = 27513;
internal string? MCPSecret { get; set; }
/// <summary>Do not touch the game's Lua files to require the module.</summary>
internal bool SkipGameFiles { get; set; } = false;
/// <summary>Do not download the module binary into lua/bin.</summary>
internal bool SkipModule { get; set; } = false;
internal bool SkipModuleUpdate { get; set; } = false;
internal ModuleRealm ModuleRealm { get; set; } = ModuleRealm.Server;
internal string? GmodRoot { get; set; }
internal int ModulePort { get; set; } = 27514;
private static readonly object FileLock = new();
internal Config() { }
internal Config(string[] args)
{
JsonConfig cfg = new();
string? configPath = JsonPath();
if (configPath != null && File.Exists(configPath))
{
string json = File.ReadAllText(configPath);
JsonConfig? extractedCfg = JsonConvert.DeserializeObject<JsonConfig>(json);
if (extractedCfg != null)
{
cfg = extractedCfg;
}
}
if (args.Length > 0)
{
Dictionary<string, List<string>> options = ParseCLIArgs(args);
ProcessOptions(options, ref cfg);
}
this.ProcessConfig(cfg);
}
/// <summary>Config.json next to the executable, or null when that cannot be resolved.</summary>
internal static string? JsonPath()
{
string? appPath = Path.GetDirectoryName(Process.GetCurrentProcess().GetExecutablePath());
return appPath == null ? null : Path.Combine(appPath, "Config.json");
}
/// <summary>The raw Config.json as a JObject. Missing or corrupt files read as empty.</summary>
internal static JObject ReadJson()
{
lock (FileLock) return ReadJsonUnlocked();
}
/// <summary>
/// Read-modify-write on Config.json. Only what <paramref name="mutate"/> touches changes;
/// every other key, known to GTerm or not, survives.
/// </summary>
internal static bool UpdateJson(Action<JObject> mutate)
{
string? path = JsonPath();
if (path == null) return false;
lock (FileLock)
{
try
{
JObject json = ReadJsonUnlocked();
mutate(json);
File.WriteAllText(path, json.ToString(Formatting.Indented));
return true;
}
catch (Exception ex)
{
LocalLogger.WriteLine($"Could not update {path}: {ex.Message}");
return false;
}
}
}
private static JObject ReadJsonUnlocked()
{
string? path = JsonPath();
if (path == null || !File.Exists(path)) return [];
try
{
return JObject.Parse(File.ReadAllText(path));
}
catch (Exception ex)
{
LocalLogger.WriteLine($"Could not parse {path}: {ex.Message}");
return [];
}
}
private void ProcessConfig(JsonConfig cfg)
{
this.ArchiveLogs = cfg.ArchiveLogs;
this.MonitorGmod = cfg.MonitorGmod;
this.StartAsGmod = cfg.StartAsGmod;
this.API = cfg.API ?? false;
this.APIPort = cfg.APIPort ?? 27512;
this.APISecret = cfg.APISecret;
this.MCP = cfg.MCP ?? false;
this.MCPCollectionWindowMs = cfg.MCPCollectionWindowMs ?? 1000;
this.MCPPort = cfg.MCPPort ?? 27513;
this.MCPSecret = cfg.MCPSecret;
this.SkipGameFiles = cfg.SkipGameFiles;
this.SkipModule = cfg.SkipModule;
this.SkipModuleUpdate = cfg.SkipModuleUpdate;
this.ModuleRealm = ParseModuleRealm(cfg.Realm);
this.GmodRoot = cfg.GmodRoot;
this.ModulePort = cfg.ModulePort ?? 27514;
if (this.ModulePort < 1 || this.ModulePort > 65535)
throw new ArgumentOutOfRangeException(nameof(cfg.ModulePort), "ModulePort must be between 1 and 65535.");
if (cfg.ExclusionPatterns != null)
{
foreach (string pattern in cfg.ExclusionPatterns)
{
this.ExclusionPatterns.Add(new Regex(pattern, RegexOptions.Compiled));
}
}
LocalLogger.WriteLine("Config params:");
LocalLogger.WriteLine("Logs archiving: " + this.ArchiveLogs);
LocalLogger.WriteLine("Gmod monitoring: " + this.MonitorGmod);
LocalLogger.WriteLine("Start as Gmod: " + this.StartAsGmod);
LocalLogger.WriteLine("MCP: " + this.MCP);
LocalLogger.WriteLine("MCP Collection Window: " + this.MCPCollectionWindowMs + "ms");
LocalLogger.WriteLine("MCP Port: " + this.MCPPort);
LocalLogger.WriteLine("MCP Secret: " + (string.IsNullOrWhiteSpace(this.MCPSecret) ? "(none)" : "***configured***"));
LocalLogger.WriteLine("Skip game files: " + this.SkipGameFiles);
LocalLogger.WriteLine("Skip module: " + this.SkipModule);
LocalLogger.WriteLine("Skip module update: " + this.SkipModuleUpdate);
LocalLogger.WriteLine("Module realm: " + this.ModuleRealm);
LocalLogger.WriteLine("Explicit GMod root: " + (this.GmodRoot ?? "(auto)"));
LocalLogger.WriteLine("Module TCP port: " + this.ModulePort);
LocalLogger.WriteLine("Exclusion Patterns: \n", string.Join("\n", this.ExclusionPatterns.Select(r => r.ToString())));
}
private static ModuleRealm ParseModuleRealm(string? value)
{
switch (value?.Trim().ToLowerInvariant())
{
case "cl" or "client":
return ModuleRealm.Client;
case null or "":
case "sv" or "server":
return ModuleRealm.Server;
default:
LocalLogger.WriteLine($"Unknown module realm '{value}', expected CL or SV. Defaulting to SV");
return ModuleRealm.Server;
}
}
private static Dictionary<string, List<string>> ParseCLIArgs(string[] args)
{
args = args.Select(arg => arg.Trim()).ToArray();
List<string>? knownOptionParams = null;
Dictionary<string, List<string>> options = new(StringComparer.OrdinalIgnoreCase);
string? curOption = null;
List<string> curOptionParams = [];
foreach (string arg in args)
{
if (arg.StartsWith("--"))
{
if (curOption != null)
{
if (options.TryGetValue(curOption, out knownOptionParams))
{
knownOptionParams.AddRange(curOptionParams);
curOptionParams.Clear();
}
else
{
options.Add(curOption, new List<string>(curOptionParams));
curOptionParams.Clear();
}
}
if (arg.Length > 3)
curOption = arg.Substring(2);
}
else
{
curOptionParams.Add(arg);
}
}
// for the last option
if (curOption != null)
{
if (options.TryGetValue(curOption, out knownOptionParams))
knownOptionParams.AddRange(curOptionParams);
else
options.Add(curOption, curOptionParams);
}
return options;
}
private static void ProcessOptions(Dictionary<string, List<string>> options, ref JsonConfig curCfg)
{
Type baseCfgType = typeof(JsonConfig);
PropertyInfo[] props = baseCfgType.GetProperties();
foreach (KeyValuePair<string, List<string>> option in options)
{
PropertyInfo? prop = props.FirstOrDefault(p => p.Name.Equals(option.Key, StringComparison.CurrentCultureIgnoreCase));
if (prop == null) continue;
switch (prop.PropertyType)
{
case Type t when t == typeof(bool) || t == typeof(bool?):
bool value = true;
if (option.Value.Count > 0)
{
string raw = string.Join(' ', option.Value);
if (bool.TryParse(raw, out bool parsedBool)) value = parsedBool;
else if (int.TryParse(raw, out int parsedValue)) value = parsedValue > 0;
else throw new ArgumentException($"Option --{option.Key} requires a boolean or integer.");
}
prop.SetValue(curCfg, value);
break;
case Type t when t == typeof(string[]):
prop.SetValue(curCfg, option.Value.ToArray());
break;
case Type t when t == typeof(int) || t == typeof(int?):
if (option.Value.Count == 0 || !int.TryParse(string.Join(' ', option.Value), out int number))
throw new ArgumentException($"Option --{option.Key} requires an integer.");
prop.SetValue(curCfg, number);
break;
case Type t when t == typeof(string):
prop.SetValue(curCfg, string.Join(' ', option.Value));
break;
default:
break;
}
}
}
}
}