-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cs
699 lines (621 loc) · 28.9 KB
/
Server.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
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
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Dalamud.Interface.ImGuiNotification;
using gfoidl.Base64;
using Heliosphere.Ui;
using Heliosphere.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using StrawberryShake;
namespace Heliosphere;
internal partial class Server : IDisposable {
[LibraryImport("user32.dll")]
private static partial short GetAsyncKeyState(int vKey);
private const int Shift = 0x10;
private static bool HoldingShift => (GetAsyncKeyState(Shift) & 0x8000) > 0;
private Plugin Plugin { get; }
private HttpListener Listener { get; }
internal bool Listening => this.Listener.IsListening;
private bool _disposed;
internal Server(Plugin plugin) {
this.Plugin = plugin;
this.Listener = new HttpListener {
Prefixes = { "http://localhost:27389/" },
};
try {
this.StartServer();
} catch (HttpListenerException ex) {
ErrorHelper.Handle(ex, "Could not start HTTP server");
}
}
public void Dispose() {
this._disposed = true;
((IDisposable) this.Listener).Dispose();
}
internal void StartServer() {
if (this.Listener.IsListening) {
return;
}
new Thread(() => {
while (!this._disposed) {
try {
this.Listener.Start();
} catch (HttpListenerException) {
Thread.Sleep(TimeSpan.FromSeconds(3));
continue;
} catch (ObjectDisposedException) {
return;
}
// ReSharper disable RedundantJumpStatement
while (this.Listener.IsListening) {
try {
this.HandleConnection();
} catch (HttpListenerException ex) when (ex.ErrorCode is 995 or 64 or 87) {
// 995 - I don't remember
// 64 - "The specified network name is no longer available."
// this is the error when the other side has closed
// 87 - "The parameter is incorrect." - what am I
// supposed to do with that?
continue;
} catch (SEHException) {
continue;
} catch (InvalidOperationException) {
return;
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error handling request");
}
}
// ReSharper restore RedundantJumpStatement
}
}).Start();
}
/// <summary>
/// Read and deserialise JSON from a HTTP request to a C# type.
/// </summary>
/// <param name="req">Request to read from</param>
/// <typeparam name="T">The type to attempt deserialisation to</typeparam>
/// <returns>
/// If the input data was
/// <list type="bullet">
/// <item>valid data: the deserialised object/array</item>
/// <item>"null": null</item>
/// <item>invalid data: null</item>
/// </list>
/// </returns>
private static T? ReadJson<T>(HttpListenerRequest req) {
try {
using var reader = new StreamReader(req.InputStream);
var json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(json);
} catch {
return default;
}
}
private void HandleConnection() {
HttpListenerContext ctx;
try {
ctx = this.Listener.GetContext();
} catch (HttpListenerException ex) {
Plugin.Log.Warning(ex, "Could not get request context");
return;
}
var req = ctx.Request;
var resp = ctx.Response;
var url = req.Url?.AbsolutePath ?? "/";
var method = req.HttpMethod.ToLowerInvariant();
int statusCode;
object? response = null;
var holdingShift = HoldingShift;
IActiveNotification? notif = null;
switch (url) {
case "/install" when method == "post": {
var info = ReadJson<InstallRequest>(req);
if (info == null) {
statusCode = 400;
break;
}
var oneClick = this.OneClickPassed(info.OneClickPassword, holdingShift);
SentrySdk.AddBreadcrumb(
"Processing install request",
"user",
data: new Dictionary<string, string> {
[nameof(info.VersionId)] = info.VersionId.ToCrockford(),
["OneClickedPassed"] = oneClick.ToString(),
}
);
Task.Run(async () => {
if (oneClick) {
try {
if (!this.Plugin.Config.UseNotificationProgress) {
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: "Installing a mod...",
initialDuration: TimeSpan.MaxValue
);
}
if (this.Plugin.Penumbra.TryGetModDirectory(out var modDir)) {
await this.Plugin.AddDownloadAsync(new DownloadTask {
Plugin = this.Plugin,
ModDirectory = modDir,
PackageId = info.PackageId,
VariantId = info.VariantId,
VersionId = info.VersionId,
IncludeTags = this.Plugin.Config.IncludeTags,
OpenInPenumbra = this.Plugin.Config.OpenPenumbraAfterInstall,
PenumbraCollection = this.Plugin.Config.OneClickCollectionId,
DownloadKey = info.DownloadCode,
Full = true,
Options = [],
Notification = this.Plugin.Config.UseNotificationProgress
? notif
: null,
});
if (!this.Plugin.Config.UseNotificationProgress) {
notif?.DismissNow();
}
} else {
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Cannot install mod: Penumbra is not set up.",
autoDuration: true
);
}
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error performing one-click install");
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Error performing one-click install.",
autoDuration: true
);
}
return;
}
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: "Opening mod installer, please wait...",
initialDuration: TimeSpan.MaxValue
);
try {
var window = await PromptWindow.Open(this.Plugin, info.PackageId, info.VersionId, info.DownloadCode);
await this.Plugin.PluginUi.AddToDrawAsync(window);
notif.DismissNow();
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error opening prompt window");
notif.Type = NotificationType.Error;
notif.Content = "Error opening installer prompt.";
notif.InitialDuration = TimeSpan.FromSeconds(5);
}
});
statusCode = 204;
break;
}
case "/multi-install" when method == "post": {
var info = ReadJson<MultiVariantInstallRequest>(req);
if (info == null) {
statusCode = 400;
break;
}
var oneClick = this.OneClickPassed(info.OneClickPassword, holdingShift);
SentrySdk.AddBreadcrumb(
"Processing multiple install request",
"user",
data: new Dictionary<string, string> {
[nameof(info.VariantIds)] = string.Join(", ", info.VariantIds.Select(v => v.ToCrockford())),
["OneClickedPassed"] = oneClick.ToString(),
}
);
Task.Run(async () => {
if (oneClick) {
try {
if (!this.Plugin.Config.UseNotificationProgress) {
var plural = info.VariantIds.Length == 1 ? "" : "s";
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: $"Installing a mod with {info.VariantIds.Length} variant{plural}...",
initialDuration: TimeSpan.MaxValue
);
}
var resp = await Plugin.GraphQl.MultiVariantInstall.ExecuteAsync(info.PackageId);
resp.EnsureNoErrors();
if (this.Plugin.Penumbra.TryGetModDirectory(out var modDir) && resp.Data?.Package?.Variants != null) {
foreach (var variant in resp.Data.Package.Variants) {
if (variant.Versions.Count <= 0) {
continue;
}
await this.Plugin.AddDownloadAsync(new DownloadTask {
Plugin = this.Plugin,
ModDirectory = modDir,
PackageId = info.PackageId,
VariantId = variant.Id,
VersionId = variant.Versions[0].Id,
IncludeTags = this.Plugin.Config.IncludeTags,
OpenInPenumbra = this.Plugin.Config.OpenPenumbraAfterInstall && variant.Id == resp.Data.Package.Variants[0].Id,
PenumbraCollection = this.Plugin.Config.OneClickCollectionId,
DownloadKey = info.DownloadCode,
Full = true,
Options = [],
Notification = this.Plugin.Config.UseNotificationProgress
? notif
: null,
});
if (!this.Plugin.Config.UseNotificationProgress) {
notif?.DismissNow();
}
}
} else {
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Cannot install mod: Penumbra is not set up.",
autoDuration: true
);
}
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error performing one-click install");
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Error performing one-click install.",
autoDuration: true
);
}
return;
}
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: "Opening mod installer, please wait...",
initialDuration: TimeSpan.MaxValue
);
try {
var window = await MultiVariantPromptWindow.Open(this.Plugin, info.PackageId, info.VariantIds, info.DownloadCode);
await this.Plugin.PluginUi.AddToDrawAsync(window);
notif.DismissNow();
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error opening prompt window");
notif.Type = NotificationType.Error;
notif.Content = "Error opening installer prompt.";
notif.InitialDuration = TimeSpan.FromSeconds(5);
}
});
statusCode = 204;
break;
}
case "/install-multiple" when method == "post": {
var info = ReadJson<InstallMultipleRequest>(req);
if (info == null) {
statusCode = 400;
break;
}
var oneClick = this.OneClickPassed(info.OneClickPassword, holdingShift);
SentrySdk.AddBreadcrumb(
"Processing install multiple request",
"user",
data: new Dictionary<string, string> {
["VersionIds"] = string.Join(", ", info.Installs.Select(i => i.VersionId.ToCrockford())),
["OneClickedPassed"] = oneClick.ToString(),
}
);
if (!this.Plugin.Penumbra.TryGetModDirectory(out var modDir)) {
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Cannot install mod: Penumbra is not set up.",
autoDuration: true
);
return;
}
Task.Run(async () => {
if (oneClick) {
if (!this.Plugin.Config.UseNotificationProgress) {
var plural = info.Installs.Length == 1 ? "" : "s";
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: $"Installing {info.Installs.Length} mod{plural}...",
initialDuration: TimeSpan.MaxValue
);
}
foreach (var install in info.Installs) {
try {
await this.Plugin.AddDownloadAsync(new DownloadTask {
Plugin = this.Plugin,
ModDirectory = modDir,
PackageId = install.PackageId,
VariantId = install.VariantId,
VersionId = install.VersionId,
IncludeTags = this.Plugin.Config.IncludeTags,
OpenInPenumbra = this.Plugin.Config.OpenPenumbraAfterInstall && install.VersionId == info.Installs[0].VersionId,
PenumbraCollection = this.Plugin.Config.OneClickCollectionId,
DownloadKey = install.DownloadCode,
Full = true,
Options = [],
Notification = this.Plugin.Config.UseNotificationProgress
? notif
: null,
});
if (!this.Plugin.Config.UseNotificationProgress) {
notif?.DismissNow();
}
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error performing one-click install");
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Error,
content: "Error performing one-click install.",
autoDuration: true
);
}
}
return;
}
notif = notif.AddOrUpdate(
this.Plugin.NotificationManager,
type: NotificationType.Info,
content: "Opening mod installer, please wait...",
initialDuration: TimeSpan.MaxValue
);
try {
var window = await MultiPromptWindow.Open(this.Plugin, info.Installs);
await this.Plugin.PluginUi.AddToDrawAsync(window);
notif.DismissNow();
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error opening prompt window");
notif.Type = NotificationType.Error;
notif.Content = "Error opening installer prompt.";
notif.InitialDuration = TimeSpan.FromSeconds(5);
}
});
statusCode = 204;
break;
}
case "/mods/installed" when method == "get": {
var mods = this.Plugin.State.Installed.Values
.SelectMany(mod => mod.Variants)
.Select(meta => new {
PackageId = $"{meta.Id:N}",
VariantId = $"{meta.VariantId:N}",
VersionId = $"{meta.VersionId:N}",
})
.ToArray();
statusCode = 200;
response = mods;
break;
}
case "/version" when method == "get": {
statusCode = 200;
response = new {
Plugin.Version,
};
break;
}
case "/first-time" when method == "post": {
if (this.Plugin.FirstTimeSetupKey is not { } key) {
statusCode = 400;
break;
}
var info = ReadJson<FirstTimeSetup>(req);
if (info == null) {
statusCode = 400;
break;
}
// TODO: do we care about timing attacks
if (info.Key != key) {
statusCode = 401;
break;
}
statusCode = 204;
if (info.Options == null) {
statusCode = 200;
response = new {
Plugin.Version,
Options = new FirstTimeSetupConfigOptions {
AutoUpdate = this.Plugin.Config.AutoUpdate,
ShowPreviews = this.Plugin.Config.Penumbra.ShowImages,
ShowInPenumbra = this.Plugin.Config.OpenPenumbraAfterInstall,
TitlePrefix = this.Plugin.Config.TitlePrefix,
PenumbraFolder = this.Plugin.Config.PenumbraFolder,
OneClick = this.Plugin.Config.OneClick,
},
};
break;
}
var oneClickWasEnabled = this.Plugin.Config.OneClick;
this.Plugin.Config.AutoUpdate = info.Options.AutoUpdate;
this.Plugin.Config.Penumbra.ShowImages = info.Options.ShowPreviews;
this.Plugin.Config.OpenPenumbraAfterInstall = info.Options.ShowInPenumbra;
this.Plugin.Config.TitlePrefix = info.Options.TitlePrefix;
this.Plugin.Config.PenumbraFolder = info.Options.PenumbraFolder;
this.Plugin.Config.OneClick = info.Options.OneClick;
if (!oneClickWasEnabled && info.Options.OneClick) {
// one-click was enabled
var password = this.Plugin.PluginUi.Settings.GenerateOneClickKey();
statusCode = 200;
response = new {
OneClickPassword = password,
};
}
// NOTE: this calls saveconfig
this.Plugin.EndFirstTimeSetup();
break;
}
default: {
if (method == "options") {
statusCode = 200;
break;
}
statusCode = 404;
response = new {
Error = "not found",
};
break;
}
}
resp.StatusCode = statusCode;
#if LOCAL
resp.AddHeader("Access-Control-Allow-Origin", "https://192.168.174.246");
#else
resp.AddHeader("Access-Control-Allow-Origin", "https://heliosphere.app");
#endif
resp.AddHeader("Access-Control-Allow-Headers", "Content-Type");
if (response != null) {
var json = JsonConvert.SerializeObject(response, Formatting.None, new JsonSerializerSettings {
ContractResolver = new DefaultContractResolver {
NamingStrategy = new SnakeCaseNamingStrategy(),
},
});
resp.AddHeader("content-type", "application/json");
var buffer = Encoding.UTF8.GetBytes(json);
resp.ContentLength64 = buffer.Length;
resp.OutputStream.Write(buffer, 0, buffer.Length);
resp.OutputStream.Close();
}
resp.Close();
}
private bool OneClickPassed(string? providedPassword, bool holdingShift) {
if (holdingShift || this.Plugin.Config is not { OneClick: true, OneClickHash: not null, OneClickSalt: not null } || providedPassword == null) {
return false;
}
try {
var password = Base64.Default.Decode(providedPassword);
var hash = HashHelper.Argon2id(this.Plugin.Config.OneClickSalt, password);
return CryptographicOperations.FixedTimeEquals(
hash,
Base64.Default.Decode(this.Plugin.Config.OneClickHash)
);
} catch (Exception ex) {
Plugin.Log.Warning(ex, "Failed to decode one-click password");
}
return false;
}
internal static void StartInstall(
Plugin plugin,
bool oneClick,
Guid packageId,
Guid variantId,
Guid versionId,
string? downloadCode,
IActiveNotification? notif = null
) {
Task.Run(async () => {
if (oneClick) {
try {
if (!plugin.Config.UseNotificationProgress) {
notif = notif.AddOrUpdate(
plugin.NotificationManager,
type: NotificationType.Info,
content: "Installing a mod..."
);
}
if (plugin.Penumbra.TryGetModDirectory(out var modDir)) {
await plugin.AddDownloadAsync(new DownloadTask {
Plugin = plugin,
ModDirectory = modDir,
PackageId = packageId,
VariantId = variantId,
VersionId = versionId,
IncludeTags = plugin.Config.IncludeTags,
OpenInPenumbra = plugin.Config.OpenPenumbraAfterInstall,
PenumbraCollection = plugin.Config.OneClickCollectionId,
DownloadKey = downloadCode,
Full = true,
Options = [],
Notification = notif,
});
} else {
notif = notif.AddOrUpdate(
plugin.NotificationManager,
type: NotificationType.Error,
content: "Cannot install mod: Penumbra is not set up.",
initialDuration: TimeSpan.FromSeconds(5)
);
}
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error performing one-click install");
notif = notif.AddOrUpdate(
plugin.NotificationManager,
type: NotificationType.Error,
content: "Error performing one-click install.",
initialDuration: TimeSpan.FromSeconds(5)
);
}
return;
}
notif = notif.AddOrUpdate(
plugin.NotificationManager,
type: NotificationType.Info,
content: "Opening mod installer, please wait...",
initialDuration: TimeSpan.MaxValue
);
try {
var window = await PromptWindow.Open(plugin, packageId, versionId, downloadCode);
await plugin.PluginUi.AddToDrawAsync(window);
notif.DismissNow();
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Error opening prompt window");
notif.Type = NotificationType.Error;
notif.Content = "Error opening installer prompt.";
notif.InitialDuration = TimeSpan.FromSeconds(5);
}
});
}
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class InstallRequest {
public Guid PackageId { get; set; }
public Guid VariantId { get; set; }
public Guid VersionId { get; set; }
public string? OneClickPassword { get; set; }
public string? DownloadCode { get; set; }
// values to display in a temp window while grabbing metadata?
// public string PackageName { get; set; }
// public string VariantName { get; set; }
// public string Version { get; set; }
// public string AuthorName { get; set; }
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class MultiVariantInstallRequest {
public Guid PackageId { get; set; }
public Guid[] VariantIds { get; set; }
public string? OneClickPassword { get; set; }
public string? DownloadCode { get; set; }
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class InstallMultipleRequest {
public InstallInfo[] Installs { get; set; }
public string? OneClickPassword { get; set; }
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class InstallInfo {
public Guid PackageId { get; set; }
public Guid VariantId { get; set; }
public Guid VersionId { get; set; }
public string? DownloadCode { get; set; }
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class FirstTimeSetup {
public string Key { get; set; }
public FirstTimeSetupConfigOptions? Options { get; set; }
}
[Serializable]
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
internal class FirstTimeSetupConfigOptions {
public bool AutoUpdate { get; set; }
public bool ShowPreviews { get; set; }
public string TitlePrefix { get; set; }
public string PenumbraFolder { get; set; }
public bool OneClick { get; set; }
public bool ShowInPenumbra { get; set; }
}