-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPotatoWallUI.xaml.cs
1494 lines (1235 loc) · 58.5 KB
/
PotatoWallUI.xaml.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
/*
* This file is part of PotatoWall distribution (https://github.com/poqdavid/PotatoWall or http://poqdavid.github.io/PotatoWall/).
* Copyright (c) 2023 POQDavid
* Copyright (c) contributors
*
* PotatoWall is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PotatoWall is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PotatoWall. If not, see <https://www.gnu.org/licenses/>.
*/
using PotatoWall.MVVM.Model;
namespace PotatoWall;
/// <copyright file="MainWindow.xaml.cs" company="POQDavid">
/// Copyright (c) POQDavid. All rights reserved.
/// </copyright>
/// <author>POQDavid</author>
/// <summary>Interaction logic for MainWindow.xaml</summary>
public partial class PotatoWallUI : Window
{
///<summary>
/// Gets or sets the iSettings property.
///</summary>
///<value>Plugin Settings.</value>
public static Setting.Settings ISettings { get => PotatoWallClient.ISettings; set => PotatoWallClient.ISettings = value; }
private static Brush DefaultFrogroundC = Brushes.White;
public IPListCompact<BaseIPData> IpWhiteList { get; set; }
public IPListCompact<BaseIPData> IpBlackList { get; set; }
public IPListCompact<BaseIPData> IpAutoWhiteList { get; set; }
public IPList<SrcIPData> ActiveIPList { get; set; }
private Dictionary<string, Dictionary<int, int>> matchmaking_flow = new();
private readonly PotatoTimer IPActivityCheck = new();
private static IntPtr WinDFriesWallHandle = IntPtr.Zero;
private static volatile bool WinDFriesWallRunning = true;
private static IntPtr WinDFriesWallMonitorHandle = IntPtr.Zero;
private static volatile bool WinDFriesWallMonitorRunning = true;
private static volatile bool ModeBlockAll;
private static volatile bool ModeWhiteList;
private static volatile bool ModeBlackList;
private static volatile bool ModeAuto;
private static volatile bool AutoAddWhiteList;
private static volatile bool allowpacket = true;
private static readonly List<string> currentNICIPAddress = new();
private readonly Regex RegEX;
[GeneratedRegex("\\b[A-Fa-f0-9]{64}\\b")]
private static partial Regex SHA256RegEX();
[GeneratedRegex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")]
private static partial Regex IPV4RegEX();
private readonly List<string> hosts = new() { "http://whatismyip.akamai.com/", "http://checkip.amazonaws.com/", "http://icanhazip.com/" };
private static string externalIP = "255.255.255.255";
public string ExternalIP
{ get => externalIP; set { externalIP = value; Label_PublicIP.Dispatcher.InvokeOrExecute(() => { Label_PublicIP.GetBindingExpression(ContentProperty).UpdateTarget(); }); } }
private static string localIP = "127.0.0.1";
public string LocalIP
{ get => localIP; set { localIP = value; Label_LocalIP.Dispatcher.InvokeOrExecute(() => { Label_LocalIP.GetBindingExpression(ContentProperty).UpdateTarget(); }); } }
public static HttpClient HttpClient { get => httpClient; set => httpClient = value; }
private readonly AddIPViewModel addIPViewModel;
private readonly SettingsViewModel settingsViewModel;
private static HttpClient httpClient = new();
private static PaletteHelper paletteHelper = new();
public PotatoWallUI()
{
Thread.CurrentThread.Name = "PotatoWallUI";
PotatoWallClient.Logger.Information("Initializing resources for PotatoWallUI");
PotatoWallClient.Logger.Information("CurrentThread CurrentCulture: {CurrentCulture}", Thread.CurrentThread.CurrentCulture);
PotatoWallClient.Logger.Information("CurrentThread CurrentUICulture: {CurrentUICulture}", Thread.CurrentThread.CurrentUICulture);
ProductInfoHeaderValue productInfo = new("PotatoWall", Assembly.GetExecutingAssembly().GetName().Version.ToString());
ProductInfoHeaderValue moreInfo = new("(+https://poqdavid.github.io/PotatoWall/)");
httpClient.DefaultRequestHeaders.UserAgent.Add(productInfo);
httpClient.DefaultRequestHeaders.UserAgent.Add(moreInfo);
httpClient.Timeout = TimeSpan.FromSeconds(5);
settingsViewModel = new SettingsViewModel();
settingsViewModel.IColorData.Load();
ActiveIPList = new IPList<SrcIPData>(Application.Current.Dispatcher);
IpWhiteList = new IPListCompact<BaseIPData>(Application.Current.Dispatcher);
IpBlackList = new IPListCompact<BaseIPData>(Application.Current.Dispatcher);
IpAutoWhiteList = new IPListCompact<BaseIPData>(Application.Current.Dispatcher);
IpWhiteList = Json.Read<IPListCompact<BaseIPData>>(PotatoWallClient.WhiteListPath, "[]");
PotatoWallClient.Logger.Information("WhiteList Loaded");
IpBlackList = Json.Read<IPListCompact<BaseIPData>>(PotatoWallClient.BlackListPath, "[]");
PotatoWallClient.Logger.Information("BlackList Loaded");
InitializeComponent();
SetGUIMode(ISettings.GUI.Mode);
SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;
LocalIP = GetLocalIP();
if (!currentNICIPAddress.Contains(LocalIP)) { currentNICIPAddress.Add(LocalIP); }
PotatoWallClient.Logger.Information("Initialized resources for PotatoWallUI");
RegEX = new Regex(PotatoWallClient.ISettings.Firewall.RegEX);
PotatoWallClient.ISettings.PropertyChanged += ISettings_PropertyChanged;
PotatoWallClient.ISettings.GUI.PropertyChanged += GUI_PropertyChanged;
PotatoWallClient.ISettings.GUI.XTheme.PropertyChanged += ITheme_PropertyChanged;
PotatoWallClient.ISettings.WinDivert.PropertyChanged += WinDivert_PropertyChanged;
PotatoWallClient.ISettings.GeoIP.PropertyChanged += GeoIP_PropertyChanged;
PotatoWallClient.ISettings.Firewall.PropertyChanged += Firewall_PropertyChanged;
settingsViewModel.SelectionChangedEvent += Theme_P_SelectionChanged;
addIPViewModel = new AddIPViewModel();
addIPViewModel.AddIPBlackListEvent += Button_AddIPBlackList_Click;
addIPViewModel.AddIPWhiteListEvent += Button_AddIPWhiteList_Click;
addIPViewModel.AddIPAutoWhiteListEvent += Button_AddIPAutoWhiteList_Click;
IpWhiteList.CollectionChanged += IpWhiteList_CollectionChanged;
IpBlackList.CollectionChanged += IpBlackList_CollectionChanged;
}
private void IpWhiteList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
try
{
Json.Write(PotatoWallClient.WhiteListPath, IpWhiteList);
}
catch (Exception ex)
{
PotatoWallClient.Logger.Error(ex, "Error: Saving Whitelist");
}
}
private void IpBlackList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
try
{
Json.Write(PotatoWallClient.BlackListPath, IpBlackList);
}
catch (Exception ex)
{
PotatoWallClient.Logger.Error(ex, "Error: Saving Blacklist");
}
}
private void Firewall_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Setting.Settings.SaveSetting();
}
private void GUI_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
SetGUIMode(ISettings.GUI.Mode);
Setting.Settings.SaveSetting();
}
private void GeoIP_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Setting.Settings.SaveSetting();
}
private void WinDivert_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Setting.Settings.SaveSetting();
}
private void ITheme_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Setting.Settings.SaveSetting();
}
private void ISettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Button_RegEX_Icon.Foreground = PotatoWallClient.ISettings.Firewall.EnableRegEX ? Brushes.LimeGreen : DefaultFrogroundC;
Setting.Settings.SaveSetting();
}
private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
if (e.Category == UserPreferenceCategory.General && ISettings.GUI.Mode.ToLower() == "auto")
{
ITheme itheme = paletteHelper.GetTheme();
itheme.SetBaseTheme(GetSystemTheme());
paletteHelper.SetTheme(itheme);
}
}
private IBaseTheme GetSystemTheme()
{
string regPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
string valName = "AppsUseLightTheme";
using RegistryKey regKey = Registry.CurrentUser.OpenSubKey(regPath);
return regKey.GetValue<uint>(valName, 0).ToTheme();
}
private void Window_Client_Loaded(object sender, RoutedEventArgs e)
{
PotatoWallClient.PotatoWriter = new TextBlockWriter(TextBlock_Console, ScrollViewer_Console);
Console.SetOut(PotatoWallClient.PotatoWriter);
SelfLog.Enable(PotatoWallClient.PotatoWriter);
Button_RegEX_Icon.Foreground = PotatoWallClient.ISettings.Firewall.EnableRegEX ? Brushes.LimeGreen : DefaultFrogroundC;
DefaultFrogroundC = Button_Setting_Icon.Foreground;
IPActivityCheck.PotatoTimerEvent += IPActivityCheck_Event;
IPActivityCheck.Start(TimeSpan.FromSeconds(1));
PotatoWallClient.Logger.Information("Window Client Loaded");
}
private void Window_client_Closing(object sender, CancelEventArgs e)
{
StopWinDivert();
}
protected static string GetLocalIP()
{
try
{
using Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, 0);
socket.Connect("9.9.9.9", 53);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address.ToString();
}
catch (Exception)
{
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(address => address.AddressFamily == AddressFamily.InterNetwork).First().ToString();
}
}
protected async Task<string> GetExtIPAsync()
{
string extip = "0.0.0.0";
foreach (string hosturl in hosts)
{
try
{
PotatoWallClient.Logger.Warning("Checking public IP by {hosturl}...", hosturl);
HttpResponseMessage response = await httpClient.GetAsync(hosturl);
Thread.CurrentThread.Name = "PotatoWallUI-Enable";
PotatoWallClient.Logger.Warning("Response status code: {statuscode}", response.StatusCode);
if (response.IsSuccessStatusCode)
{
extip = IPV4RegEX().Match(await response.Content.ReadAsStringAsync()).ToString();
if (extip != "0.0.0.0")
{
return extip;
}
}
Thread.CurrentThread.Name = "PotatoWallUI-Enable";
}
catch (WebException webex)
{
PotatoWallClient.Logger.Error(webex, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
catch (InvalidOperationException ioex)
{
PotatoWallClient.Logger.Error(ioex, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
catch (TaskCanceledException tcex)
{
PotatoWallClient.Logger.Error(tcex, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
catch (HttpRequestException httpex)
{
PotatoWallClient.Logger.Error(httpex, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
catch (SocketException socketex)
{
PotatoWallClient.Logger.Error(socketex, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
catch (AggregateException aex)
{
foreach (Exception exx in aex.InnerExceptions)
{
PotatoWallClient.Logger.Error(exx, "Error: URL: {hosturl}...", hosturl);
PotatoWallClient.Logger.Information("");
}
}
}
return extip;
}
private void IPActivityCheck_Event(object sender, PotatoTimerEventEventArgs e)
{
try
{
if (e.TimerState == TimerStates.Running)
{
foreach (SrcIPData iPData in ActiveIPList.ToArray())
{
if (DateTime.Now.Subtract(iPData.LastActivity).Seconds >= PotatoWallClient.ISettings.Firewall.IPActivityTime)
{
_ = ActiveIPList.Remove(iPData);
}
}
}
}
catch (Exception ex) { PotatoWallClient.Logger.Error(ex, ex.Message); }
}
private void DialogHost_Button_CLOSE_Click(object sender, RoutedEventArgs e)
{
WinDivert_CheckFilter();
}
private void Button_Enable_Click(object sender, RoutedEventArgs e)
{
if (Button_Enable.IsChecked == true)
{
Button_Enable.IsEnabled = false;
new Thread(() =>
{
Thread.CurrentThread.Name = "PotatoWallUI-Enable";
PotatoWallClient.Logger.Warning("Please wait checking connection...");
LocalIP = GetLocalIP();
if (!currentNICIPAddress.Contains(LocalIP)) { currentNICIPAddress.Add(LocalIP); }
PotatoWallClient.Logger.Information("Local IP: {localip}", LocalIP);
PotatoWallClient.Logger.Information("");
ExternalIP = GetExtIPAsync().Result;
PotatoWallClient.Logger.Information("Public IP: {externalip}", ExternalIP);
PotatoWallClient.Logger.Information("");
WinDFriesWallRunning = true;
WinDivertInit("PotatoFriesWall", ref WinDFriesWallHandle, WinDivertOpenFlags.None);
RunBackgroundThread(PotatoFriesWall, "PotatoFriesWall", ThreadPriority.Highest);
WinDFriesWallMonitorRunning = true;
WinDivertInit("PotatoFriesWallMonitor", ref WinDFriesWallMonitorHandle, WinDivertOpenFlags.Sniff);
RunBackgroundThread(PotatoFriesWallMonitor, "PotatoFriesWallMonitor", ThreadPriority.Highest);
PotatoWallClient.Logger.Information("");
_ = Button_Enable.Dispatcher.BeginInvoke((Action)delegate ()
{
Button_Enable.IsEnabled = true;
});
})
{ IsBackground = true }.Start();
}
else
{
Button_Enable.IsEnabled = false;
new Thread(() =>
{
Thread.CurrentThread.Name = "PotatoWallUI-Disable";
WinDFriesWallRunning = false;
if (WinDFriesWallHandle != IntPtr.Zero)
{
_ = WinDivert.WinDivertClose(WinDFriesWallHandle);
}
WinDFriesWallMonitorRunning = false;
if (WinDFriesWallMonitorHandle != IntPtr.Zero)
{
_ = WinDivert.WinDivertClose(WinDFriesWallMonitorHandle);
}
StopWinDivert();
_ = Button_Enable.Dispatcher.BeginInvoke((Action)delegate ()
{
Button_Enable.IsEnabled = true;
});
})
{ IsBackground = true }.Start();
}
}
private void Button_BlockAll_Click(object sender, RoutedEventArgs e)
{
if (ModeBlockAll)
{
ModeBlockAll = false;
Button_BlockAll_Icon.Foreground = DefaultFrogroundC;
}
else
{
ModeWhiteList = false;
ModeBlackList = false;
ModeAuto = false;
IpAutoWhiteList.Clear();
Button_WhiteList_Icon.Foreground = DefaultFrogroundC;
Button_BlackList_Icon.Foreground = DefaultFrogroundC;
Button_AutoList_Icon.Foreground = DefaultFrogroundC;
ModeBlockAll = true;
Button_BlockAll_Icon.Foreground = Brushes.LimeGreen;
}
}
private void Button_RegEX_Click(object sender, RoutedEventArgs e)
{
if (PotatoWallClient.ISettings.Firewall.EnableRegEX)
{
PotatoWallClient.ISettings.Firewall.EnableRegEX = false;
Button_RegEX_Icon.Foreground = DefaultFrogroundC;
}
else
{
PotatoWallClient.ISettings.Firewall.EnableRegEX = true;
Button_RegEX_Icon.Foreground = Brushes.LimeGreen;
}
}
private void Button_WhiteList_Click(object sender, RoutedEventArgs e)
{
if (ModeWhiteList)
{
ModeWhiteList = false;
Button_WhiteList_Icon.Foreground = DefaultFrogroundC;
}
else
{
ModeBlockAll = false;
ModeBlackList = false;
ModeAuto = false;
IpAutoWhiteList.Clear();
Button_BlockAll_Icon.Foreground = DefaultFrogroundC;
Button_BlackList_Icon.Foreground = DefaultFrogroundC;
Button_AutoList_Icon.Foreground = DefaultFrogroundC;
ModeWhiteList = true;
Button_WhiteList_Icon.Foreground = Brushes.LimeGreen;
}
}
private void Button_BlackList_Click(object sender, RoutedEventArgs e)
{
if (ModeBlackList)
{
ModeBlackList = false;
Button_BlackList_Icon.Foreground = DefaultFrogroundC;
}
else
{
ModeWhiteList = false;
ModeBlockAll = false;
ModeAuto = false;
IpAutoWhiteList.Clear();
Button_WhiteList_Icon.Foreground = DefaultFrogroundC;
Button_BlockAll_Icon.Foreground = DefaultFrogroundC;
Button_AutoList_Icon.Foreground = DefaultFrogroundC;
ModeBlackList = true;
Button_BlackList_Icon.Foreground = Brushes.LimeGreen;
}
}
private void Button_AutoList_Click(object sender, RoutedEventArgs e)
{
if (ModeAuto)
{
ModeAuto = false;
Button_AutoList_Icon.Foreground = DefaultFrogroundC;
IpAutoWhiteList.Clear();
}
else
{
ModeWhiteList = false;
ModeBlackList = false;
ModeBlockAll = false;
Button_WhiteList_Icon.Foreground = DefaultFrogroundC;
Button_BlackList_Icon.Foreground = DefaultFrogroundC;
Button_BlockAll_Icon.Foreground = DefaultFrogroundC;
RunIPScan();
Button_AutoList_Icon.Foreground = Brushes.LimeGreen;
}
}
private void Button_AutoScanList_Click(object sender, RoutedEventArgs e)
{
RunIPScan();
}
private void RunIPScan()
{
PotatoWallClient.Logger.Warning("Please wait {ipsearchduration} seconds adding IPs...", PotatoWallClient.ISettings.Firewall.IPSearchDuration);
Button_AutoScanList.IsEnabled = false;
new Thread(() =>
{
AutoAddWhiteList = true;
for (int i = 1; i < (PotatoWallClient.ISettings.Firewall.IPSearchDuration + 1); i++)
{
Thread.Sleep(1000);
if (i == 10)
{
AutoAddWhiteList = false;
Thread.Sleep(1000);
ModeAuto = true;
_ = Button_AutoScanList.Dispatcher.BeginInvoke((Action)delegate ()
{
Button_AutoScanList.IsEnabled = true;
});
PotatoWallClient.Logger.Warning("Done finished adding IPs.");
}
}
})
{ IsBackground = true }.Start();
}
private void Theme_P_SelectionChanged(object sender, ComboBoxSelectionChangedEventArgs e)
{
if (grid_loading.Visibility == Visibility.Hidden)
{
if (e.SelectedItem is ColorDataList list)
{
if (list.ColorMetadata == "REC")
{
SetTheme(list.ColorName);
}
else if (list.ColorMetadata != "SEP")
{
string cdata = list.ColorMetadata;
Color cx = ColorConverter.ConvertFromString(cdata).CastTo<Color>();
SetTheme(cx);
}
}
}
}
private void SetGUIMode(string mode)
{
ITheme itheme = paletteHelper.GetTheme();
switch (mode.ToLower())
{
case "dark":
itheme.SetBaseTheme(Theme.Dark);
break;
case "light":
itheme.SetBaseTheme(Theme.Light);
break;
case "auto":
itheme.SetBaseTheme(GetSystemTheme());
break;
}
paletteHelper.SetTheme(itheme);
}
public static void SetTheme(string cname)
{
SwatchesProvider swatchesProvider = new();
Swatch color = swatchesProvider.Swatches.FirstOrDefault(a => a.Name == cname);
paletteHelper.ReplacePrimaryColor(color);
}
public static void SetTheme(Color c)
{
PaletteHelper paletteHelper = new();
paletteHelper.ChangePrimaryColor(c);
}
private void Window_Client_ContentRendered(object sender, EventArgs e)
{
PotatoWallClient.Logger.Information("Finished rendering content for PotatoWallUI");
PotatoWallClient.Logger.Information("");
if (settingsViewModel.IColorData.ColorDataList[PotatoWallClient.ISettings.GUI.XTheme.Color] is ColorDataList list)
{
if (list.ColorMetadata == "REC")
{
SetTheme(list.ColorName);
}
else if (list.ColorMetadata != "SEP")
{
string cdata = list.ColorMetadata;
Color cx = ColorConverter.ConvertFromString(cdata).CastTo<Color>();
SetTheme(cx);
}
}
grid_loading.Visibility = Visibility.Hidden;
}
private void Button_Setting_Click(object sender, RoutedEventArgs e)
{
_ = DialogHost.Show(settingsViewModel, "RootDialog");
}
private void Button_AddIP_Click(object sender, RoutedEventArgs e)
{
_ = DialogHost.Show(addIPViewModel, "RootDialog");
}
private static void WinDivert_CheckFilter()
{
uint errorPos = 0;
if (!WinDivert.WinDivertHelperCheckFilter(PotatoWallClient.ISettings.WinDivert.Filter, WinDivertLayer.Network, out string errorMessage, ref errorPos))
{
PotatoWallClient.Logger.Warning("Filter string is invalid at position {errorpos}.\nError Message:\n{errormessage}", errorPos, errorMessage);
}
}
private void PotatoFriesWall()
{
WinDivertBuffer packet = new();
WinDivertAddress addr = new();
uint readLen = 0;
IntPtr recvEvent = IntPtr.Zero;
NativeOverlapped recvOverlapped;
uint recvAsyncIoLen = 0;
do
{
try
{
if (WinDFriesWallRunning)
{
readLen = 0;
recvEvent = Kernel32.CreateEventW(IntPtr.Zero, false, false, IntPtr.Zero);
string SrcIPAddress = "0.0.0.0";
ushort SrcPort = 0;
string DstIPAddress = "0.0.0.0";
ushort DstPort = 0;
allowpacket = true;
if (recvEvent == IntPtr.Zero)
{
PotatoWallClient.Logger.Warning("Failed to initialize receive IO event.");
continue;
}
addr.Reset();
if (PotatoWallClient.ISettings.WinDivert.WinDivertRecvEx)
{
recvAsyncIoLen = 0;
recvOverlapped = new NativeOverlapped
{
EventHandle = recvEvent
};
unsafe
{
if (!WinDivert.WinDivertRecvEx(WinDFriesWallHandle, packet, 0, ref addr, ref readLen, &recvOverlapped))
{
int error = Marshal.GetLastWin32Error();
if (error != 997)
{
PotatoWallClient.Logger.Warning("Unknown IO error ID {error} while awaiting result.", error);
Debug.Assert(Kernel32.CloseHandle(recvEvent));
continue;
}
while (Kernel32.WaitForSingleObject(recvEvent, 1000) == (uint)WaitForSingleObjectResult.WaitTimeout) { }
if (!Kernel32.GetOverlappedResult(WinDFriesWallHandle, &recvOverlapped, ref recvAsyncIoLen, false))
{
PotatoWallClient.Logger.Warning("Failed to get overlapped result.");
Debug.Assert(Kernel32.CloseHandle(recvEvent));
continue;
}
readLen = recvAsyncIoLen;
}
}
}
else if (PotatoWallClient.ISettings.WinDivert.WinDivertRecv)
{
if (!WinDivert.WinDivertRecv(WinDFriesWallHandle, packet, ref addr, ref readLen))
{
int error = Marshal.GetLastWin32Error();
// 997 == ERROR_IO_PENDING
if (error != 997)
{
PotatoWallClient.Logger.Warning("Unknown IO error ID {error} while awaiting result.");
_ = Kernel32.CloseHandle(recvEvent);
continue;
}
while (Kernel32.WaitForSingleObject(recvEvent, 1000) == (uint)WaitForSingleObjectResult.WaitTimeout)
{
}
}
}
_ = Kernel32.CloseHandle(recvEvent);
WinDivertParseResult WD_PR = WinDivert.WinDivertHelperParsePacket(packet, readLen);
unsafe
{
if (WD_PR.IPv4Header != null && WD_PR.UdpHeader != null)
{
//WriteToConsole($"V4 UDP packet {addr.Direction} from {WD_PR.IPv4Header->SrcAddr}:{WD_PR.UdpHeader->SrcPort.SWPOrder()} to {WD_PR.IPv4Header->DstAddr}:{WD_PR.UdpHeader->DstPort.SWPOrder()}", Brushes.Yellow);
SrcIPAddress = $"{WD_PR.IPv4Header->SrcAddr}";
SrcPort = WD_PR.UdpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv4Header->DstAddr}";
DstPort = WD_PR.UdpHeader->DstPort;
}
else if (WD_PR.IPv6Header != null && WD_PR.UdpHeader != null)
{
SrcIPAddress = $"{WD_PR.IPv6Header->SrcAddr}";
SrcPort = WD_PR.UdpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv6Header->DstAddr}";
DstPort = WD_PR.UdpHeader->DstPort;
}
if (WD_PR.IPv4Header != null && WD_PR.TcpHeader != null)
{
//WriteToConsole($"V4 TCP packet {addr.Direction} from {WD_PR.IPv4Header->SrcAddr}:{WD_PR.TcpHeader->SrcPort.SWPOrder()} to {WD_PR.IPv4Header->DstAddr}:{WD_PR.TcpHeader->DstPort.SWPOrder()}", Brushes.Yellow);
SrcIPAddress = $"{WD_PR.IPv4Header->SrcAddr}";
SrcPort = WD_PR.TcpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv4Header->DstAddr}";
DstPort = WD_PR.TcpHeader->DstPort;
}
else if (WD_PR.IPv6Header != null && WD_PR.TcpHeader != null)
{
SrcIPAddress = $"{WD_PR.IPv6Header->SrcAddr}";
SrcPort = WD_PR.TcpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv6Header->DstAddr}";
DstPort = WD_PR.TcpHeader->DstPort;
}
}
//string ChkIPAddress = SrcIPAddress;
string Direction = addr.Direction.ToString();
if (ModeBlockAll) { allowpacket = false || ((RegEX.IsMatch(SrcIPAddress) && PotatoWallClient.ISettings.Firewall.EnableRegEX)); }
if (ModeBlackList)
{
allowpacket = !IpBlackList.Contains(SrcIPAddress) || IpBlackList.Count == 0 || IsPacketAllowed(SrcIPAddress, packet, WD_PR.PacketPayloadLength, "BlackList");
}
if (ModeWhiteList)
{
allowpacket = IpWhiteList.Contains(SrcIPAddress) || (RegEX.IsMatch(SrcIPAddress) && PotatoWallClient.ISettings.Firewall.EnableRegEX) || IsPacketAllowed(SrcIPAddress, packet, WD_PR.PacketPayloadLength, "WhiteList");
}
if (ModeAuto)
{
allowpacket = IpAutoWhiteList.Contains(SrcIPAddress) || (RegEX.IsMatch(SrcIPAddress) && PotatoWallClient.ISettings.Firewall.EnableRegEX) || IsPacketAllowed(SrcIPAddress, packet, WD_PR.PacketPayloadLength, "WhiteList");
}
if (!ModeBlockAll && !ModeBlackList && !ModeWhiteList && !ModeAuto)
{
allowpacket = true;
}
if (SrcIPAddress == LocalIP) { allowpacket = true; }
if (SrcIPAddress == ExternalIP) { allowpacket = true; }
if (allowpacket)
{
if (PotatoWallClient.ISettings.WinDivert.WinDivertRecvEx)
{
if (!WinDivert.WinDivertSendEx(WinDFriesWallHandle, packet, readLen, 0, ref addr))
{
PotatoWallClient.Logger.Warning("Write Err: {getlastwin32error}", Marshal.GetLastWin32Error());
}
}
else if (PotatoWallClient.ISettings.WinDivert.WinDivertRecv)
{
if (!WinDivert.WinDivertSend(WinDFriesWallHandle, packet, readLen, ref addr))
{
PotatoWallClient.Logger.Warning("Write Err: {getlastwin32error}", Marshal.GetLastWin32Error());
}
}
}
}
}
catch (Exception ex) { PotatoWallClient.Logger.Error(ex, ex.Message); }
}
while (WinDFriesWallRunning);
}
private void PotatoFriesWallMonitor()
{
WinDivertBuffer packet = new();
WinDivertAddress addr = new();
uint readLen = 0;
IntPtr recvEvent = IntPtr.Zero;
NativeOverlapped recvOverlapped;
uint recvAsyncIoLen = 0;
do
{
try
{
if (WinDFriesWallMonitorRunning)
{
readLen = 0;
recvEvent = Kernel32.CreateEventW(IntPtr.Zero, false, false, IntPtr.Zero);
string SrcIPAddress = "0.0.0.0";
ushort SrcPort = 0;
string DstIPAddress = "0.0.0.0";
ushort DstPort = 0;
if (recvEvent == IntPtr.Zero)
{
PotatoWallClient.Logger.Warning("Failed to initialize receive IO event.");
continue;
}
addr.Reset();
if (PotatoWallClient.ISettings.WinDivert.WinDivertRecvEx)
{
recvAsyncIoLen = 0;
recvOverlapped = new NativeOverlapped
{
EventHandle = recvEvent
};
unsafe
{
if (!WinDivert.WinDivertRecvEx(WinDFriesWallMonitorHandle, packet, 0, ref addr, ref readLen, &recvOverlapped))
{
int error = Marshal.GetLastWin32Error();
if (error != 997)
{
PotatoWallClient.Logger.Warning("Unknown IO error ID {error} while awaiting result.", error);
Debug.Assert(Kernel32.CloseHandle(recvEvent));
continue;
}
while (Kernel32.WaitForSingleObject(recvEvent, 1000) == (uint)WaitForSingleObjectResult.WaitTimeout) { }
if (!Kernel32.GetOverlappedResult(WinDFriesWallMonitorHandle, &recvOverlapped, ref recvAsyncIoLen, false))
{
PotatoWallClient.Logger.Warning("Failed to get overlapped result.");
Debug.Assert(Kernel32.CloseHandle(recvEvent));
continue;
}
readLen = recvAsyncIoLen;
}
}
}
else if (PotatoWallClient.ISettings.WinDivert.WinDivertRecv)
{
if (!WinDivert.WinDivertRecv(WinDFriesWallMonitorHandle, packet, ref addr, ref readLen))
{
int error = Marshal.GetLastWin32Error();
// 997 == ERROR_IO_PENDING
if (error != 997)
{
PotatoWallClient.Logger.Warning("Unknown IO error ID {error} while awaiting result.", error);
_ = Kernel32.CloseHandle(recvEvent);
continue;
}
while (Kernel32.WaitForSingleObject(recvEvent, 1000) == (uint)WaitForSingleObjectResult.WaitTimeout)
{
}
}
}
_ = Kernel32.CloseHandle(recvEvent);
WinDivertParseResult WD_PR = WinDivert.WinDivertHelperParsePacket(packet, readLen);
unsafe
{
if (WD_PR.IPv4Header != null && WD_PR.UdpHeader != null)
{
//WriteToConsole($"V4 UDP packet {addr.Direction} from {WD_PR.IPv4Header->SrcAddr}:{WD_PR.UdpHeader->SrcPort.SWPOrder()} to {WD_PR.IPv4Header->DstAddr}:{WD_PR.UdpHeader->DstPort.SWPOrder()}", Brushes.Yellow);
SrcIPAddress = $"{WD_PR.IPv4Header->SrcAddr}";
SrcPort = WD_PR.UdpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv4Header->DstAddr}";
DstPort = WD_PR.UdpHeader->DstPort;
}
else if (WD_PR.IPv6Header != null && WD_PR.UdpHeader != null)
{
SrcIPAddress = $"{WD_PR.IPv6Header->SrcAddr}";
SrcPort = WD_PR.UdpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv6Header->DstAddr}";
DstPort = WD_PR.UdpHeader->DstPort;
}
if (WD_PR.IPv4Header != null && WD_PR.TcpHeader != null)
{
//WriteToConsole($"V4 TCP packet {addr.Direction} from {WD_PR.IPv4Header->SrcAddr}:{WD_PR.TcpHeader->SrcPort.SWPOrder()} to {WD_PR.IPv4Header->DstAddr}:{WD_PR.TcpHeader->DstPort.SWPOrder()}", Brushes.Yellow);
SrcIPAddress = $"{WD_PR.IPv4Header->SrcAddr}";
SrcPort = WD_PR.TcpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv4Header->DstAddr}";
DstPort = WD_PR.TcpHeader->DstPort;
}
else if (WD_PR.IPv6Header != null && WD_PR.TcpHeader != null)
{
SrcIPAddress = $"{WD_PR.IPv6Header->SrcAddr}";
SrcPort = WD_PR.TcpHeader->SrcPort;
DstIPAddress = $"{WD_PR.IPv6Header->DstAddr}";
DstPort = WD_PR.TcpHeader->DstPort;
}
}
string ChkIPAddress = SrcIPAddress;
string Direction = addr.Direction.ToString();
if (AutoAddWhiteList)
{
if (!IpAutoWhiteList.Contains(SrcIPAddress))
{
if (addr.Direction == WinDivertDirection.Inbound)
{
PotatoWallClient.Logger.Information("Added IP {srcipaddress} to auto white list by scan", SrcIPAddress);