-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConfigSync.cs
1461 lines (1240 loc) · 51.1 KB
/
ConfigSync.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#nullable enable
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using BepInEx;
using BepInEx.Configuration;
// ReSharper disable CheckNamespace
// ReSharper disable RedundantDefaultMemberInitializer
// ReSharper disable UnusedMember.Local
// ReSharper disable Unity.NoNullPropagation
namespace ServerSync;
[PublicAPI]
public abstract class OwnConfigEntryBase
{
public object? LocalBaseValue;
public abstract ConfigEntryBase BaseConfig { get; }
public bool SynchronizedConfig = true;
}
[PublicAPI]
public class SyncedConfigEntry<T> : OwnConfigEntryBase
{
public override ConfigEntryBase BaseConfig => SourceConfig;
public readonly ConfigEntry<T> SourceConfig;
public SyncedConfigEntry(ConfigEntry<T> sourceConfig) { SourceConfig = sourceConfig; }
public T Value
{
get => SourceConfig.Value;
set => SourceConfig.Value = value;
}
public void AssignLocalValue(T value)
{
if (LocalBaseValue == null)
{
Value = value;
} else
{
LocalBaseValue = value;
}
}
}
public abstract class CustomSyncedValueBase
{
public event Action? ValueChanged;
public object? LocalBaseValue;
public readonly string Identifier;
public readonly Type Type;
private object? boxedValue;
public object? BoxedValue
{
get => boxedValue;
set
{
boxedValue = value;
ValueChanged?.Invoke();
}
}
protected bool localIsOwner;
public readonly int Priority;
protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
{
Priority = priority;
Identifier = identifier;
Type = type;
configSync.AddCustomValue(this);
localIsOwner = configSync.IsSourceOfTruth;
configSync.SourceOfTruthChanged += truth => localIsOwner = truth;
}
}
[PublicAPI]
public sealed class CustomSyncedValue<T> : CustomSyncedValueBase
{
public T Value
{
get => (T)BoxedValue!;
set => BoxedValue = value;
}
public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default!, int priority = 0) : base(
configSync, identifier, typeof(T), priority)
{
Value = value;
}
public void AssignLocalValue(T value)
{
if (localIsOwner)
{
Value = value;
} else
{
LocalBaseValue = value;
}
}
}
internal class ConfigurationManagerAttributes
{
[UsedImplicitly] public bool? ReadOnly = false;
}
[PublicAPI]
public class ConfigSync
{
public static bool ProcessingServerUpdate = false;
public readonly string Name;
public string? DisplayName;
public string? CurrentVersion;
public string? MinimumRequiredVersion;
public bool ModRequired = false;
private bool? forceConfigLocking;
public bool IsLocked
{
get =>
(forceConfigLocking ?? lockedConfig != null
&& ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0)
&& !lockExempt;
set => forceConfigLocking = value;
}
public bool IsAdmin => lockExempt || isSourceOfTruth;
private bool isSourceOfTruth = true;
public bool IsSourceOfTruth
{
get => isSourceOfTruth;
private set
{
if (value != isSourceOfTruth)
{
isSourceOfTruth = value;
SourceOfTruthChanged?.Invoke(value);
}
}
}
public bool InitialSyncDone { get; private set; } = false;
public event Action<bool>? SourceOfTruthChanged;
private static readonly HashSet<ConfigSync> configSyncs = new();
private readonly HashSet<OwnConfigEntryBase> allConfigs = new();
private HashSet<CustomSyncedValueBase> allCustomValues = new();
private static bool isServer;
private static bool lockExempt = false;
private OwnConfigEntryBase? lockedConfig = null;
private event Action? lockedConfigChanged;
static ConfigSync() { RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); }
public ConfigSync(string name)
{
Name = name;
configSyncs.Add(this);
_ = new VersionCheck(this);
}
public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
{
if (configData(configEntry) is not SyncedConfigEntry<T> syncedEntry)
{
syncedEntry = new SyncedConfigEntry<T>(configEntry);
AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(
configEntry.Description,
new object[] { new ConfigurationManagerAttributes() }
.Concat(configEntry.Description.Tags ?? Array.Empty<object>()).Concat(new[] { syncedEntry })
.ToArray());
configEntry.SettingChanged += (_, _) =>
{
if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
{
Broadcast(ZRoutedRpc.Everybody, configEntry);
}
};
allConfigs.Add(syncedEntry);
}
return syncedEntry;
}
public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
{
if (lockedConfig != null)
{
throw new Exception("Cannot initialize locking ConfigEntry twice");
}
lockedConfig = AddConfigEntry(lockingConfig);
lockingConfig.SettingChanged += (_, _) => lockedConfigChanged?.Invoke();
return (SyncedConfigEntry<T>)lockedConfig;
}
internal void AddCustomValue(CustomSyncedValueBase customValue)
{
if (allCustomValues.Select(v => v.Identifier).Concat(new[] { "serverversion" })
.Contains(customValue.Identifier))
{
throw new Exception(
"Cannot have multiple settings with the same name or with a reserved name (serverversion)");
}
allCustomValues.Add(customValue);
allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending(v => v.Priority));
customValue.ValueChanged += () =>
{
if (!ProcessingServerUpdate)
{
Broadcast(ZRoutedRpc.Everybody, customValue);
}
};
}
[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
private static class SnatchCurrentlyHandlingRPC
{
public static ZRpc? currentRpc;
[HarmonyPrefix]
private static void Prefix(ZRpc __instance) => currentRpc = __instance;
}
[HarmonyPatch(typeof(ZNet), "Awake")]
internal static class RegisterRPCPatch
{
[HarmonyPostfix]
private static void Postfix(ZNet __instance)
{
try
{
isServer = __instance.IsServer();
foreach (ConfigSync configSync in configSyncs)
{
ZRoutedRpc.instance.Register<ZPackage>(configSync.Name + " ConfigSync",
configSync.RPC_FromOtherClientConfigSync);
if (isServer)
{
configSync.InitialSyncDone = true;
Debug($"Registered '{configSync.Name} ConfigSync' RPC - waiting for incoming connections");
}
}
IEnumerator WatchAdminListChanges()
{
SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList")
.GetValue(ZNet.instance);
List<string> CurrentList = new(adminList.GetList());
for (;;)
{
yield return new WaitForSeconds(30);
if (!adminList.GetList().SequenceEqual(CurrentList))
{
CurrentList = new List<string>(adminList.GetList());
void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
{
ZPackage package = ConfigsToPackage(packageEntries: new[]
{
new PackageEntry
{
section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin
},
});
if (configSyncs.First() is { } configSync)
{
ZNet.instance.StartCoroutine(configSync.sendZPackage(peers, package));
}
}
List<ZNetPeer> adminPeer = ZNet.instance.GetPeers()
.Where(p => adminList.Contains(p.m_rpc.GetSocket().GetHostName())).ToList();
List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
SendAdmin(nonAdminPeer, false);
SendAdmin(adminPeer, true);
}
}
// ReSharper disable once IteratorNeverReturns
}
if (isServer)
{
__instance.StartCoroutine(WatchAdminListChanges());
}
}
catch (Exception)
{
// ignored
}
}
}
[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
private static class RegisterClientRPCPatch
{
[HarmonyPostfix]
private static void Postfix(ZNet __instance, ZNetPeer peer)
{
if (!__instance.IsServer())
{
foreach (ConfigSync configSync in configSyncs)
{
peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", configSync.RPC_FromServerConfigSync);
}
}
}
}
private const byte PARTIAL_CONFIGS = 1;
private const byte FRAGMENTED_CONFIG = 2;
private const byte COMPRESSED_CONFIG = 4;
private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new();
private readonly List<KeyValuePair<long, string>> cacheExpirations = new(); // avoid leaking memory
private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
{
lockedConfigChanged += serverLockedSettingChanged;
IsSourceOfTruth = false;
if (HandleConfigSyncRPC(0, package, false))
{
InitialSyncDone = true;
}
}
private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) =>
HandleConfigSyncRPC(sender, package, true);
private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
{
try
{
if (isServer && IsLocked && SnatchCurrentlyHandlingRPC.currentRpc?.GetSocket()?.GetHostName() is { } client)
{
MethodInfo? listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId");
SyncedList adminList =
(SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
bool exempt = listContainsId is null
? adminList.Contains(client)
: (bool)listContainsId.Invoke(ZNet.instance, new object[] { adminList, client });
if (!exempt)
{
return false;
}
}
cacheExpirations.RemoveAll(kv =>
{
if (kv.Key < DateTimeOffset.Now.Ticks)
{
configValueCache.Remove(kv.Value);
return true;
}
return false;
});
byte packageFlags = package.ReadByte();
if ((packageFlags & FRAGMENTED_CONFIG) != 0)
{
long uniqueIdentifier = package.ReadLong();
string cacheKey = sender.ToString() + uniqueIdentifier;
if (!configValueCache.TryGetValue(cacheKey, out SortedDictionary<int, byte[]> dataFragments))
{
dataFragments = new SortedDictionary<int, byte[]>();
configValueCache[cacheKey] = dataFragments;
cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60).Ticks,
cacheKey));
}
int fragment = package.ReadInt();
int fragments = package.ReadInt();
dataFragments.Add(fragment, package.ReadByteArray());
if (dataFragments.Count < fragments)
{
return false;
}
configValueCache.Remove(cacheKey);
package = new ZPackage(dataFragments.Values.SelectMany(a => a).ToArray());
packageFlags = package.ReadByte();
}
ProcessingServerUpdate = true;
if ((packageFlags & COMPRESSED_CONFIG) != 0)
{
byte[] data = package.ReadByteArray();
MemoryStream input = new(data);
MemoryStream output = new();
using (DeflateStream deflateStream = new(input, CompressionMode.Decompress))
{
deflateStream.CopyTo(output);
}
package = new ZPackage(output.ToArray());
packageFlags = package.ReadByte();
}
if ((packageFlags & PARTIAL_CONFIGS) == 0)
{
resetConfigsFromServer();
}
ParsedConfigs configs = ReadConfigsFromPackage(package);
foreach (KeyValuePair<OwnConfigEntryBase, object?> configKv in configs.configValues)
{
if (!isServer && configKv.Key.LocalBaseValue == null)
{
configKv.Key.LocalBaseValue = configKv.Key.BaseConfig.BoxedValue;
}
configKv.Key.BaseConfig.BoxedValue = configKv.Value;
}
foreach (KeyValuePair<CustomSyncedValueBase, object?> configKv in configs.customValues)
{
if (!isServer)
{
configKv.Key.LocalBaseValue ??= configKv.Key.BoxedValue;
}
configKv.Key.BoxedValue = configKv.Value;
}
Debug(
$"Received {configs.configValues.Count} configs and {configs.customValues.Count} custom values from {(isServer || clientUpdate ? $"client {sender}" : "the server")} for mod {DisplayName ?? Name}");
if (!isServer)
{
serverLockedSettingChanged(); // Re-evaluate for intial locking
}
return true;
}
finally
{
ProcessingServerUpdate = false;
}
}
private class ParsedConfigs
{
public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new();
public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new();
}
private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
{
ParsedConfigs configs = new();
Dictionary<string, OwnConfigEntryBase> configMap = allConfigs.Where(c => c.SynchronizedConfig)
.ToDictionary(c => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, c => c);
Dictionary<string, CustomSyncedValueBase> customValueMap =
allCustomValues.ToDictionary(c => c.Identifier, c => c);
int valueCount = package.ReadInt();
for (int i = 0; i < valueCount; ++i)
{
string groupName = package.ReadString();
string configName = package.ReadString();
string typeName = package.ReadString();
Type? type = Type.GetType(typeName);
if (typeName == "" || type != null)
{
object? value;
try
{
value = typeName == "" ? null : ReadValueWithTypeFromZPackage(package, type!);
}
catch (InvalidDeserializationTypeException e)
{
DebugWarning(
$"Got unexpected struct internal type {e.received} for field {e.field} struct {typeName} for {configName} in section {groupName} for mod {DisplayName ?? Name}, expecting {e.expected}");
continue;
}
if (groupName == "Internal")
{
if (configName == "serverversion")
{
if (value?.ToString() != CurrentVersion)
{
DebugWarning(
$"Received server version is not equal: server version = {value?.ToString() ?? "null"}; local version = {CurrentVersion ?? "unknown"}");
}
} else if (configName == "lockexempt")
{
if (value is bool exempt)
{
lockExempt = exempt;
}
} else if (customValueMap.TryGetValue(configName, out CustomSyncedValueBase config))
{
if ((typeName == ""
&& (!config.Type.IsValueType || Nullable.GetUnderlyingType(config.Type) != null))
|| GetZPackageTypeString(config.Type) == typeName)
{
configs.customValues[config] = value;
} else
{
DebugWarning(
$"Got unexpected type {typeName} for internal value {configName} for mod {DisplayName ?? Name}, expecting {config.Type.AssemblyQualifiedName}");
}
}
} else if (configMap.TryGetValue(groupName + "_" + configName, out OwnConfigEntryBase config))
{
Type expectedType = configType(config.BaseConfig);
if ((typeName == ""
&& (!expectedType.IsValueType || Nullable.GetUnderlyingType(expectedType) != null))
|| GetZPackageTypeString(expectedType) == typeName)
{
configs.configValues[config] = value;
} else
{
DebugWarning(
$"Got unexpected type {typeName} for {configName} in section {groupName} for mod {DisplayName ?? Name}, expecting {expectedType.AssemblyQualifiedName}");
}
} else
{
DebugWarning(
$"Received unknown config entry {configName} in section {groupName} for mod {DisplayName ?? Name}. This may happen if client and server versions of the mod do not match.");
}
} else
{
DebugWarning($"Got invalid type {typeName}, abort reading of received configs");
return new ParsedConfigs();
}
}
return configs;
}
[HarmonyPatch(typeof(ZNet), "Shutdown")]
private class ResetConfigsOnShutdown
{
[HarmonyPostfix]
private static void Postfix()
{
ProcessingServerUpdate = true;
foreach (ConfigSync serverSync in configSyncs)
{
serverSync.resetConfigsFromServer();
serverSync.IsSourceOfTruth = true;
serverSync.InitialSyncDone = false;
}
ProcessingServerUpdate = false;
}
}
private static bool isWritableConfig(OwnConfigEntryBase config)
{
if (configSyncs.FirstOrDefault(cs => cs.allConfigs.Contains(config)) is not { } configSync)
{
return true;
}
return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null
|| (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
}
private void serverLockedSettingChanged()
{
foreach (OwnConfigEntryBase configEntryBase in allConfigs)
{
configAttribute<ConfigurationManagerAttributes>(configEntryBase.BaseConfig).ReadOnly =
!isWritableConfig(configEntryBase);
}
}
private void resetConfigsFromServer()
{
foreach (OwnConfigEntryBase config in allConfigs.Where(config => config.LocalBaseValue != null))
{
config.BaseConfig.BoxedValue = config.LocalBaseValue;
config.LocalBaseValue = null;
}
foreach (CustomSyncedValueBase config in allCustomValues.Where(config => config.LocalBaseValue != null))
{
config.BoxedValue = config.LocalBaseValue;
config.LocalBaseValue = null;
}
lockedConfigChanged -= serverLockedSettingChanged;
serverLockedSettingChanged();
}
private static long packageCounter = 0;
private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
{
if (ZRoutedRpc.instance is not { } rpc)
{
yield break;
}
const int packageSliceSize = 250000;
const int maximumSendQueueSize = 20000;
IEnumerable<bool> waitForQueue()
{
float timeout = Time.time + 30;
while (peer.m_socket.GetSendQueueSize() > maximumSendQueueSize)
{
if (Time.time > timeout)
{
Debug($"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
peer.m_rpc.Invoke("Error", ZNet.ConnectionStatus.ErrorConnectFailed);
ZNet.instance.Disconnect(peer);
yield break;
}
yield return false;
}
}
void SendPackage(ZPackage pkg)
{
string method = Name + " ConfigSync";
if (isServer)
{
peer.m_rpc.Invoke(method, pkg);
} else
{
rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, method, pkg);
}
}
if (package.GetArray() is { LongLength: > packageSliceSize } data)
{
int fragments = (int)(1 + (data.LongLength - 1) / packageSliceSize);
long packageIdentifier = ++packageCounter;
for (int fragment = 0; fragment < fragments; ++fragment)
{
foreach (bool wait in waitForQueue())
{
yield return wait;
}
if (!peer.m_socket.IsConnected())
{
yield break;
}
ZPackage fragmentedPackage = new();
fragmentedPackage.Write(FRAGMENTED_CONFIG);
fragmentedPackage.Write(packageIdentifier);
fragmentedPackage.Write(fragment);
fragmentedPackage.Write(fragments);
fragmentedPackage.Write(data.Skip(packageSliceSize * fragment).Take(packageSliceSize).ToArray());
SendPackage(fragmentedPackage);
if (fragment != fragments - 1)
{
yield return true;
}
}
} else
{
foreach (bool wait in waitForQueue())
{
yield return wait;
}
SendPackage(package);
}
}
private IEnumerator sendZPackage(long target, ZPackage package)
{
if (!ZNet.instance)
{
return Enumerable.Empty<object>().GetEnumerator();
}
List<ZNetPeer> peers =
(List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
if (target != ZRoutedRpc.Everybody)
{
peers = peers.Where(p => p.m_uid == target).ToList();
}
return sendZPackage(peers, package);
}
private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
{
if (!ZNet.instance)
{
yield break;
}
const int compressMinSize = 10000;
if (package.GetArray() is { LongLength: > compressMinSize } rawData)
{
ZPackage compressedPackage = new();
compressedPackage.Write(COMPRESSED_CONFIG);
MemoryStream output = new();
using (DeflateStream deflateStream = new(output, System.IO.Compression.CompressionLevel.Optimal))
{
deflateStream.Write(rawData, 0, rawData.Length);
}
compressedPackage.Write(output.ToArray());
package = compressedPackage;
}
List<IEnumerator<bool>> writers = peers.Where(peer => peer.IsReady())
.Select(p => distributeConfigToPeers(p, package)).ToList();
writers.RemoveAll(writer => !writer.MoveNext());
while (writers.Count > 0)
{
yield return null;
writers.RemoveAll(writer => !writer.MoveNext());
}
}
[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
private class SendConfigsAfterLogin
{
private class BufferingSocket : ISocket
{
public volatile bool finished = false;
public volatile int versionMatchQueued = -1;
public readonly List<ZPackage> Package = new();
public readonly ISocket Original;
public BufferingSocket(ISocket original) { Original = original; }
public bool IsConnected() => Original.IsConnected();
public ZPackage Recv() => Original.Recv();
public int GetSendQueueSize() => Original.GetSendQueueSize();
public int GetCurrentSendRate() => Original.GetCurrentSendRate();
public bool IsHost() => Original.IsHost();
public void Dispose() => Original.Dispose();
public bool GotNewData() => Original.GotNewData();
public void Close() => Original.Close();
public string GetEndPointString() => Original.GetEndPointString();
public void GetAndResetStats(out int totalSent, out int totalRecv) =>
Original.GetAndResetStats(out totalSent, out totalRecv);
public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping,
out float outByteSec, out float inByteSec) =>
Original.GetConnectionQuality(out localQuality, out remoteQuality, out ping, out outByteSec,
out inByteSec);
public ISocket Accept() => Original.Accept();
public int GetHostPort() => Original.GetHostPort();
public bool Flush() => Original.Flush();
public string GetHostName() => Original.GetHostName();
public void VersionMatch()
{
if (finished)
{
Original.VersionMatch();
} else
{
versionMatchQueued = Package.Count;
}
}
public void Send(ZPackage pkg)
{
int oldPos = pkg.GetPos();
pkg.SetPos(0);
int methodHash = pkg.ReadInt();
if ((methodHash == "PeerInfo".GetStableHashCode() || methodHash == "RoutedRPC".GetStableHashCode()
|| methodHash == "ZDOData".GetStableHashCode())
&& !finished)
{
ZPackage newPkg = new(pkg.GetArray());
newPkg.SetPos(oldPos);
Package.Add(newPkg); // the original ZPackage gets reused, create a new one
} else
{
pkg.SetPos(oldPos);
Original.Send(pkg);
}
}
}
[HarmonyPriority(Priority.First)]
[HarmonyPrefix]
private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
{
if (__instance.IsServer())
{
BufferingSocket bufferingSocket = new(rpc.GetSocket());
AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
// Don't replace on steam sockets, RPC_PeerInfo does peer.m_socket as ZSteamSocket - which will cause a nullref when replaced
if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new[] { typeof(ZRpc) })
.Invoke(__instance, new object[] { rpc }) is ZNetPeer peer
&& ZNet.m_onlineBackend != OnlineBackendType.Steamworks)
{
AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(peer, bufferingSocket);
}
__state ??= new Dictionary<Assembly, BufferingSocket>();
__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
}
}
[HarmonyPostfix]
private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
{
if (!__instance.IsServer())
{
return;
}
void SendBufferedData()
{
if (rpc.GetSocket() is BufferingSocket bufferingSocket)
{
AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new[] { typeof(ZRpc) })
.Invoke(__instance, new object[] { rpc }) is ZNetPeer netPeer)
{
AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket")
.SetValue(netPeer, bufferingSocket.Original);
}
}
bufferingSocket = __state[Assembly.GetExecutingAssembly()];
bufferingSocket.finished = true;
for (int i = 0; i < bufferingSocket.Package.Count; ++i)
{
if (i == bufferingSocket.versionMatchQueued)
{
bufferingSocket.Original.VersionMatch();
}
bufferingSocket.Original.Send(bufferingSocket.Package[i]);
}
if (bufferingSocket.Package.Count == bufferingSocket.versionMatchQueued)
{
bufferingSocket.Original.VersionMatch();
}
}
if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new[] { typeof(ZRpc) })
.Invoke(__instance, new object[] { rpc }) is not ZNetPeer peer)
{
SendBufferedData();
return;
}
IEnumerator sendAsync()
{
foreach (ConfigSync configSync in configSyncs)
{
List<PackageEntry> entries = new();
if (configSync.CurrentVersion != null)
{
entries.Add(new PackageEntry
{
section = "Internal", key = "serverversion", type = typeof(string),
value = configSync.CurrentVersion
});
}
MethodInfo? listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId");
SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList")
.GetValue(ZNet.instance);
entries.Add(new PackageEntry
{
section = "Internal", key = "lockexempt", type = typeof(bool),
value = listContainsId is null
? adminList.Contains(rpc.GetSocket().GetHostName())
: listContainsId.Invoke(ZNet.instance,
new object[] { adminList, rpc.GetSocket().GetHostName() })
});
ZPackage package = ConfigsToPackage(configSync.allConfigs.Select(c => c.BaseConfig),
configSync.allCustomValues, entries, false);
yield return __instance.StartCoroutine(
configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
}
SendBufferedData();
}
__instance.StartCoroutine(sendAsync());
}
}
private class PackageEntry
{
public string section = null!;
public string key = null!;
public Type type = null!;
public object? value;
}
private void Broadcast(long target, params ConfigEntryBase[] configs)
{
if (!IsLocked || isServer)
{
ZPackage package = ConfigsToPackage(configs);
ZNet.instance?.StartCoroutine(sendZPackage(target, package));
}
}
private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
{
if (!IsLocked || isServer)
{
ZPackage package = ConfigsToPackage(customValues: customValues);
ZNet.instance?.StartCoroutine(sendZPackage(target, package));
}
}
private static OwnConfigEntryBase? configData(ConfigEntryBase config)
{
return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
}
public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
{
return config.Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
}
private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); }
private static Type configType(ConfigEntryBase config) => configType(config.SettingType);
private static Type configType(Type type) => type.IsEnum ? Enum.GetUnderlyingType(type) : type;
[HarmonyPatch(typeof(ConfigEntryBase), nameof(ConfigEntryBase.GetSerializedValue))]
private static class PreventSavingServerInfo
{
[HarmonyPrefix]
private static bool Prefix(ConfigEntryBase __instance, ref string __result)
{
if (configData(__instance) is not { } data || isWritableConfig(data))
{
return true;
}
__result = TomlTypeConverter.ConvertToString(data.LocalBaseValue, __instance.SettingType);
return false;
}
}
[HarmonyPatch(typeof(ConfigEntryBase), nameof(ConfigEntryBase.SetSerializedValue))]
private static class PreventConfigRereadChangingValues
{
[HarmonyPrefix]
private static bool Prefix(ConfigEntryBase __instance, string value)
{
if (configData(__instance) is not { } data || data.LocalBaseValue == null)
{
return true;
}
try
{
data.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);