-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
355 lines (313 loc) · 12.2 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using PPGModCompiler.Config;
using PPGModCompiler.ModModels;
using PPGModCompiler.Utils;
using WatsonTcp;
namespace PPGModCompiler
{
public static class Program
{
public static WatsonTcpServer server;
private static bool shouldStayAlive = true;
private static int gameProcessId = -1;
private static CSharpCompilationOptions compilationOptions;
private static bool isBusy;
private static Thread monitor;
private static readonly StupidRepoConfig customConfig = ConfigManager.ReadConfig<StupidRepoConfig>("SR_CONFIG.json");
public static int Main(string[] args)
{
// set window title
Console.Title = "PPGModCompiler";
var compilerConfig = ConfigManager.ReadConfig<CompilerConfig>("config.json");
if (!Directory.Exists(customConfig.SteamPath) || !Steam.IsValidSteamPath(customConfig.SteamPath))
{
if (!customConfig.AutoFindSteamPath)
{
Console.Error.WriteLine("The folder to your Steam installation was not found, or is not a valid Steam installation. Please specify one in the SR_CONFIG.json file.");
return 1;
}
var steamPath = Steam.TryFindSteamPath();
if (steamPath == null)
{
Console.Error.WriteLine("A valid Steam installation could not be automatically located. Please specify one in the SR_CONFIG.json file.");
return 1;
}
customConfig.SteamPath = steamPath;
}
customConfig.SteamPath = customConfig.SteamPath.TrimEnd('/').TrimEnd('\\');
ConfigManager.SaveConfig("SR_CONFIG.json", customConfig);
compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, false, null, null, null, null, OptimizationLevel.Release);
if (compilerConfig.ShutdownWhenGameNotFound && args.Length == 1 && int.TryParse(args[0], out gameProcessId))
{
monitor = new Thread(MonitorLoop) { IsBackground = true };
monitor.Start();
}
server = new WatsonTcpServer(compilerConfig.Hostname, compilerConfig.Port);
server.Settings.Logger += (s, m) => Console.WriteLine($"[{s}] {m}");
server.Events.ClientConnected += async (_, e) =>
{
await server.SendAndWaitAsync(1000, e.Client.Guid, "alles goed ouwe");
};
// server.Events.ClientDisconnected += (_, e) => Console.WriteLine($"Client {e.Client.Guid} disconnected");
server.Events.MessageReceived += (_, e) => ProcessMessage(e.Data, e.Client, false);
server.Events.ServerStopped += (_, _) => Console.WriteLine("Server was stopped");
server.Start();
Console.WriteLine($"Started listening on {compilerConfig.Hostname}:{compilerConfig.Port}");
while (!server.IsListening) Thread.Sleep(500);
while (server.IsListening)
{
Thread.Sleep(500);
if (shouldStayAlive) continue;
if (server.IsListening)
server.Stop();
return 0;
}
return 0;
}
private static void MonitorLoop(object _)
{
while (true)
{
Thread.Sleep(1000);
try
{
if (!Process.GetProcessById(gameProcessId).HasExited) continue;
quit();
break;
}
catch (Exception ex)
{
quit();
break;
}
}
return;
static void quit()
{
shouldStayAlive = false;
server.Stop();
}
}
private static void ProcessMessage(byte[] data, ClientMetadata client, bool debuggingRn)
{
while (isBusy) Thread.Sleep(16);
isBusy = true;
var str = Encoding.UTF8.GetString(data);
try
{
// instructions = JsonConvert.DeserializeObject<ModCompileInstructions>(str);
if (str == "quit")
{
Console.WriteLine("Quit received.");
// server.Stop();
// shouldStayAlive = false;
// isBusy = false;
return;
}
if (str.StartsWith("ho"))
{
Console.WriteLine("We can't do anything here...");
return;
}
var instructions = Helpers.FixInstructions(str, customConfig.SteamPath);
// Console.WriteLine($"Attempting to compile mod.\n{JsonConvert.SerializeObject(instructions, Formatting.Indented)}");
if (debuggingRn) throw new Exception("tbh, i cba with this shi cuhhhh");
CompileMod(instructions, client.Guid);
}
catch (Exception ex1)
{
Console.Error.WriteLine($"Received malformed message: {ex1.Message}");
Console.Error.WriteLine(str);
}
finally
{
isBusy = false;
}
}
private static void CompileMod(ModCompileInstructions instructions, Guid remote)
{
var source = new List<string>();
if (!string.IsNullOrWhiteSpace(instructions.InsertSourceB64))
source.Add(Encoding.ASCII.GetString(Convert.FromBase64String(instructions.InsertSourceB64)));
if (File.Exists(instructions.OutputFileName))
File.Delete(instructions.OutputFileName);
// Console.WriteLine($"Compiling \"{instructions.MainClass}\"...");
DrawablesLol.ProgressBar(0, $"Finding source files for {instructions.MainClass}");
source.AddRange(from path in instructions.Paths where File.Exists(path) select File.ReadAllText(path));
var metadataReferenceList = new List<MetadataReference>();
foreach (var path in instructions.AssemblyReferenceLocations.Distinct())
{
try
{
var fromFile = MetadataReference.CreateFromFile(path);
metadataReferenceList.Add(fromFile);
}
catch (Exception ex)
{
Helpers.TrySendError($"Assembly referencing error: {ex.Message}", instructions.ID, remote);
return;
}
}
DrawablesLol.ProgressBar(25, $"Parsing {instructions.MainClass}");
var syntaxTreeList = new List<SyntaxTree>();
var csharpParseOptions = new CSharpParseOptions(LanguageVersion.CSharp7_3);
var dis = source.Distinct().ToList();
for (var i = 0; i < dis.Count; i++)
{
try {
var text = CSharpSyntaxTree.ParseText(dis[i], csharpParseOptions);
var src = text.GetRoot().DescendantNodes().ToArray();
var cl = src.OfType<ClassDeclarationSyntax>().First();
var p = (i+1 / dis.Count) * 25;
DrawablesLol.ProgressBar(25+p, $"Parsing {cl.Identifier.Text} ({i+1}/{dis.Count})");
if (instructions.RejectShadyCode) ScanTree(text);
syntaxTreeList.Add(text);
} catch (ShadyException ex) {
Helpers.TrySendError(ex.Message, instructions.ID, remote, true);
return;
} catch (Exception ex) {
Helpers.TrySendError($"Parsing error: {ex.Message}", instructions.ID, remote);
return;
}
}
if (syntaxTreeList.Count == 0)
{
Helpers.TrySendError("No source files could be succesfully parsed.", instructions.ID, remote);
return;
}
var csharpCompilation = CSharpCompilation.Create(Guid.NewGuid().ToString().Normalize(), syntaxTreeList,
metadataReferenceList, compilationOptions);
var diagnostics = csharpCompilation.GetDiagnostics();
var errors = diagnostics.Where(diag => diag.Severity == DiagnosticSeverity.Error).ToList();
var sb = new StringBuilder();
foreach (var error in errors) AppendDiagnostic(sb, error);
if (errors.Count > 0)
{
Helpers.TrySendError(sb.ToString(), instructions.ID, remote);
return;
}
if (string.IsNullOrWhiteSpace(instructions.OutputFileName) || instructions.OutputFileName == null)
{
Helpers.TrySendError("Output file name is null or empty.", instructions.ID, remote);
return;
}
DrawablesLol.ProgressBar(50, $"Compiling {instructions.MainClass}");
var emitResult = csharpCompilation.Emit(instructions.OutputFileName);
if (emitResult.Success)
{
DrawablesLol.ProgressBar(100, $"Successfully compiled {instructions.MainClass}!");
Helpers.TrySendSuccess(instructions.ID, remote);
return;
}
File.Delete(instructions.OutputFileName);
sb.Clear();
foreach (var diagnostic in emitResult.Diagnostics.Where(diagnostic =>
diagnostic.Severity == DiagnosticSeverity.Error)) AppendDiagnostic(sb, diagnostic);
Helpers.TrySendError(sb.ToString(), instructions.ID, remote);
}
private static void ScanTree(SyntaxTree tree)
{
var source = tree.GetRoot().DescendantNodes();
var syntaxNodes = source as SyntaxNode[] ?? source.ToArray();
if (syntaxNodes.OfType<ExternAliasDirectiveSyntax>().Any())
throw new Exception("External code is not allowed");
foreach (var usingDirectiveSyntax in syntaxNodes.OfType<UsingDirectiveSyntax>())
{
var str = usingDirectiveSyntax.ToString();
if (usingDirectiveSyntax.Alias != null)
throw new Exception("Using directives with aliases are not allowed");
if (str.Contains("System.Security", StringComparison.InvariantCultureIgnoreCase))
throw new ShadyException("Forbidden using directive: System.Security");
if (str.Contains("System.Web", StringComparison.InvariantCultureIgnoreCase))
throw new ShadyException("Forbidden using directive: System.Web");
if (str.Contains("UnityEngine.Networking", StringComparison.InvariantCultureIgnoreCase))
throw new ShadyException("Forbidden using directive: UnityEngine.Networking");
if (str.Contains("Steamworks", StringComparison.InvariantCultureIgnoreCase))
throw new ShadyException("Forbidden using directive: Steamworks");
if (str.Contains("System.Reflection", StringComparison.InvariantCultureIgnoreCase))
throw new ShadyException("Forbidden using directive: System.Reflection");
}
foreach (var simpleNameSyntax in syntaxNodes.OfType<IdentifierNameSyntax>())
{
var text = simpleNameSyntax.Identifier.Text;
switch (text)
{
case "AppDomain":
case "Application":
case "Assembly":
case "AssemblyBuilder":
case "BinaryReader":
case "BinaryWriter":
case "CodeDom":
case "CreateType":
case "Diagnostics":
case "Directory":
case "DirectoryInfo":
case "DllImport":
case "File":
case "FileInfo":
case "FileStream":
case "FromFile":
case "GetMethod":
case "GetMethods":
case "Http":
case "InteropServices":
case "IsolatedStorageFileStream":
case "LoadFile":
case "LoadURL":
case "MethodInfo":
case "NetworkStream":
case "OpenURL":
case "PipeStream":
case "Process":
case "Quit":
case "ReadFile":
case "RejectShadyCode":
case "Socket":
case "Steamworks":
case "StreamReader":
case "StreamWriter":
case "StringReader":
case "StringWriter":
case "TextReader":
case "TextWriter":
case "UnityWebRequest":
case "UserPreferenceManager":
case "WWW":
case "WebClient":
case "WebRequest":
case "WebSocket":
throw new ShadyException($"{text} is not allowed as an identifier");
default:
continue;
}
}
}
private static void AppendDiagnostic(StringBuilder sb, Diagnostic diag)
{
var startLinePosition = diag.Location.GetMappedLineSpan().StartLinePosition;
var str = diag.Location.SourceTree?.FilePath ?? "UNKNOWN FILE";
if (!string.IsNullOrWhiteSpace(str))
{
sb.Append("in");
sb.Append(str);
sb.Append(", ");
}
sb.Append(diag.GetMessage());
sb.Append(" at ");
sb.Append(startLinePosition);
sb.AppendLine();
}
}
}