This repository has been archived by the owner on Feb 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
frmMain.cs
582 lines (507 loc) · 19.9 KB
/
frmMain.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
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Security.Policy;
using WinCFScan.Classes;
using WinCFScan.Classes.Config;
using WinCFScan.Classes.HTTPRequest;
using WinCFScan.Classes.IP;
using static System.Net.Mime.MediaTypeNames;
namespace WinCFScan
{
public partial class frmMain : Form
{
private const string ourGitHubUrl = "https://github.com/goingfine/WinCFScan";
ConfigManager configManager;
bool oneTimeChecked = false; // config checked once?
ScanEngine scanEngine;
private List<ResultItem> currentScanResults = new();
private bool scanFnished = false;
private bool isUpdatinglistCFIP;
private bool isAppCongigValid = true;
public frmMain()
{
InitializeComponent();
// load configs
configManager = new();
if(!configManager.isConfigValid()) {
addTextLog("App config is not valid! we can not continue.");
if(configManager.errorMessage != "")
{
addTextLog(configManager.errorMessage);
}
isAppCongigValid = false;
}
scanEngine = new ScanEngine();
loadLastResultsComboList();
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
.AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $" - {version}";
this.Text += displayableVersion;
}
// add text log to log textbox
delegate void SetTextCallback(string log);
public void addTextLog(string log)
{
try
{
if (this.txtLog.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(addTextLog);
this.Invoke(d, new object[] { log });
}
else
{
txtLog.AppendText(log + Environment.NewLine);
}
}
catch (Exception)
{
}
}
private void btnScanInPrevResults_Click(object sender, EventArgs e)
{
startStopScan(true);
}
private void btnStart_Click(object sender, EventArgs e)
{
startStopScan(false);
}
private void startStopScan(bool inPrevResult = false)
{
if(!isAppCongigValid)
{
showCanNotContinueMessage();
return;
}
if (scanEngine.progressInfo.isScanRunning)
{
// stop scan
waitUntilScannerStoped();
updateUIControlls(false);
}
else
{ // start scan
if (!inPrevResult)
{
// set cf ip list to scan engine
string[] ipRanges = getCheckedCFIPList();
if (ipRanges.Length == 0)
{
tabControl1.SelectTab(0);
MessageBox.Show($"No Cloudflare IP ranges are selected. Please select some IP ranges.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
scanEngine.setCFIPRangeList(ipRanges);
addTextLog($"Start scanning {ipRanges.Length} Cloudflare IP ranges...");
}
else
{
if(currentScanResults.Count == 0)
{
addTextLog("Current result list is empty!");
return;
}
addTextLog($"Start scanning {currentScanResults.Count} IPs in previous result...");
}
updateUIControlls(true);
scanEngine.workingIPsFromPrevScan = inPrevResult ? currentScanResults : null;
var scanType = inPrevResult ? ScanType.SCAN_IN_PERV_RESULTS : ScanType.SCAN_CLOUDFLARE_IPS;
// start scan job in new thread
Task.Factory.StartNew(() => scanEngine.start(scanType))
.ContinueWith(done => {
scanFnished = true;
this.currentScanResults = scanEngine.progressInfo.scanResults.workingIPs;
addTextLog($"{scanEngine.progressInfo.totalCheckedIP:n0} IPs tested and found {scanEngine.progressInfo.scanResults.totalFoundWorkingIPs:n0} working IPs.");
});
tabControl1.SelectTab(1);
}
}
private void updateUIControlls(bool isStarting)
{
if (isStarting)
{
loadLastResultsComboList();
listResults.Items.Clear();
btnStart.Text = "Stop Scan";
btnScanInPrevResults.Enabled = false;
btnDeleteResult.Enabled = false;
comboConcurrent.Enabled = false;
timerProgress.Enabled = true;
btnSkipCurRange.Enabled = true;
comboResults.Enabled = false;
tabPageCFRanges.Enabled = false;
}
else
{ // is stopping
btnStart.Text = "Start Scan";
btnScanInPrevResults.Enabled = true;
btnDeleteResult.Enabled = true;
timerProgress.Enabled = false;
btnSkipCurRange.Enabled = false;
comboResults.Enabled = true;
comboConcurrent.Enabled = true;
tabPageCFRanges.Enabled = true;
// save result file if found working IPs
var scanResults = scanEngine.progressInfo.scanResults;
if (scanResults.totalFoundWorkingIPs != 0)
{
// save results into disk
if (! scanResults.save())
{
addTextLog($"Could not save scan result into the file: {scanResults.resultsFileName}");
}
}
else
{
// delete result file if there is no woriking ip
scanResults.remove();
}
loadLastResultsComboList();
}
}
private void timerBase_Tick(object sender, EventArgs e)
{
oneTimeChecks();
if (scanFnished)
{
scanFnished = false;
updateConrtolsProgress(true);
updateUIControlls(false);
}
}
private void timerProgress_Tick(object sender, EventArgs e)
{
updateConrtolsProgress();
}
private void updateConrtolsProgress(bool forceUpdate = false)
{
var pInf = scanEngine.progressInfo;
if (scanEngine.progressInfo.isScanRunning || forceUpdate)
{
lblLastIPRange.Text = $"Current IP range: {pInf.currentIPRange} ({pInf.currentIPRangesNumber:n0}/{pInf.totalIPRanges:n0})";
labelLastIPChecked.Text = $"Last checked IP: {pInf.lastCheckedIP} ({pInf.totalCheckedIPInCurIPRange:n0}/{pInf.currentIPRangeTotalIPs:n0})";
lblTotalWorkingIPs.Text = $"Total working IPs found: {pInf.scanResults.totalFoundWorkingIPs:n0}";
if(pInf.scanResults.fastestIP !=null)
{
txtFastestIP.Text = $"{pInf.scanResults.fastestIP.ip} - {pInf.scanResults.fastestIP.delay:n0} ms";
}
prgOveral.Maximum = pInf.totalIPRanges;
prgOveral.Value = pInf.currentIPRangesNumber;
prgCurRange.Maximum = pInf.currentIPRangeTotalIPs;
prgCurRange.Value = pInf.totalCheckedIPInCurIPRange;
fetchWorkingIPResults();
pInf.scanResults.autoSave();
}
}
// fetch new woriking ips and add to the list view while scanning
private void fetchWorkingIPResults()
{
List<ResultItem> scanResults = scanEngine.progressInfo.scanResults.fetchWorkingIPs();
addResulItemsToListView(scanResults);
}
private void btnSkipCurRange_Click(object sender, EventArgs e)
{
scanEngine.skipCurrentIPRange();
}
private void loadLastResultsComboList()
{
comboResults.Items.Clear();
comboResults.Items.Add("Current Scan Results");
var resultFiles = Directory.GetFiles("results/", "*.json");
foreach (var resultFile in resultFiles)
{
comboResults.Items.Add(resultFile);
}
comboResults.SelectedIndex= 0;
}
private void comboResults_SelectedIndexChanged(object sender, EventArgs e)
{
string? filename = getSelectedScanResultFilename();
if (filename != null)
{
fillResultsListView(filename);
}
}
// get filename of selected scan result
private string? getSelectedScanResultFilename()
{
string? filename = comboResults.SelectedItem.ToString();
if (filename != null && File.Exists(filename) && filename != "Current Scan Results")
{
return filename;
}
return null;
}
// load previous results into list view
private void fillResultsListView(string resultsFileName)
{
var results = new ScanResults(resultsFileName);
if (results.load())
{
listResults.Items.Clear();
var loaded = results.getLoadedInstance();
this.currentScanResults = loaded.workingIPs;
addResulItemsToListView(currentScanResults);
addTextLog($"'{resultsFileName}' loaded with {loaded.totalFoundWorkingIPs:n0} working IPs, scan time: {loaded.startDate}");
}
else
{
addTextLog($"Could not load scan result file from disk: {resultsFileName}");
}
}
private void addResulItemsToListView(List<ResultItem>? workingIPs)
{
if (workingIPs != null)
{
foreach (ResultItem resultItem in workingIPs)
{
listResults.Items.Add(new ListViewItem(new string[] { resultItem.delay.ToString(), resultItem.ip }));
}
lblPrevListTotalIPs.Text = $"{listResults.Items.Count:n0} IPs";
}
}
private void oneTimeChecks()
{
if (!oneTimeChecked && isAppCongigValid)
{
//Load cf ip ranges
loadCFIPListView();
// check if config real file is exists and update
if (configManager.getRealConfig() != null && configManager.getRealConfig().isConfigRealOld())
{
addTextLog("Updating real config from remote...");
bool result = configManager.getRealConfig().remoteUpdateConfigReal();
if (result)
{
addTextLog("'real config' is successfully updated.");
if (!configManager.getRealConfig().isConfigValid())
{
addTextLog("'real config' data is not valid!");
}
}
else
{
addTextLog("Failed to update real config. check your internet connection or maybe real config update url is blocked by your ISP!");
}
}
// check fronting domain
Task.Factory.StartNew(() =>
{
var checker = new CheckIPWorking();
if (!checker.checkFronting(false, 5))
{
addTextLog($"Fronting domain is not accesible! you might need to get new frontig url from our github or check your internet connection.");
}
});
oneTimeChecked = true;
}
}
private void comboConcurrent_TextChanged(object sender, EventArgs e)
{
var con = getConcurentProcess();
comboConcurrent.Text = con.ToString();
scanEngine.concurrentProcess = con;
}
private int getConcurentProcess()
{
int val = 0;
bool isInteger = int.TryParse(comboConcurrent.Text, out val);
if (!isInteger || val < 1 || val > 16)
{
val = 4;
}
return val;
}
private void btnCopyFastestIP_Click(object sender, EventArgs e)
{
try
{
if (scanEngine.progressInfo.scanResults?.fastestIP != null)
{
Clipboard.SetText(scanEngine.progressInfo.scanResults.fastestIP.ip);
}
}
catch (Exception ex) { }
}
// delete result
private void btnDeleteResult_Click(object sender, EventArgs e)
{
string? filename = getSelectedScanResultFilename();
if (filename != null)
{
var result = MessageBox.Show($"Are you sure you want to delete {filename}?",
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
try
{
File.Delete(filename);
addTextLog($"'{filename}' has been deleted.");
loadLastResultsComboList();
listResults.Items.Clear();
currentScanResults = new();
lblPrevListTotalIPs.Text = "0 IPs";
}
catch (Exception){
addTextLog($"Could not delete '{filename}'");
}
}
}
}
// user selected ip list of cloudflare
private string[] getCheckedCFIPList(bool getIPCount = false)
{
return listCFIPList.CheckedItems.Cast<ListViewItem>()
.Select(item => {
return getIPCount ? item.SubItems[1].Text : item.SubItems[0].Text;
})
.ToArray<string>();
}
// list view right click
private void listResults_MouseClick(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right) {
mnuListViewCopyIP.Text = "Copy IP Address " + getSelectedIPAddress();
mnuListView.Show(listResults, e.X, e.Y);
}
}
// add cloudflare ip ranges to list view
private void loadCFIPListView()
{
if(scanEngine.cfIPList == null)
{
addTextLog("Cloudflare IP range file is not found!");
lblCFIPListStatus.Text = "Failed to load IP ranges.";
lblCFIPListStatus.ForeColor = Color.Red;
return;
}
listCFIPList.BeginUpdate();
isUpdatinglistCFIP = true;
uint totalIPs = 0;
addTextLog($"Loading Cloudflare IPs ranges...");
foreach (var ipRange in scanEngine.cfIPList)
{
if (ipRange != "")
{
var rangeTotalIPs = IPAddressExtensions.getIPRangeTotalIPs(ipRange);
var item = listCFIPList.Items.Add(new ListViewItem(new string[] { ipRange, $"{rangeTotalIPs:n0}" }));
item.Checked = true;
totalIPs += rangeTotalIPs;
}
}
listCFIPList.EndUpdate();
isUpdatinglistCFIP = false;
addTextLog($"Total {totalIPs:n0} Cloudflare IPs are ready to be scanned.");
updateCFIPListStatusText();
}
private void mnuListViewTestThisIPAddress_Click(object sender, EventArgs e)
{
var IPAddress = getSelectedIPAddress();
if(IPAddress != null)
{
testSingleIP(IPAddress);
}
}
private void testSingleIP(string IPAddress)
{
addTextLog($"Testing {IPAddress} ...");
var checker = new CheckIPWorking(IPAddress);
var success = checker.check();
if (success)
addTextLog($"{IPAddress} is working. Delay: {checker.downloadDuration:n0} ms.");
else
addTextLog($"{IPAddress} is NOT working.");
}
private string? getSelectedIPAddress()
{
try
{
return listResults.SelectedItems[0].SubItems[1].Text;
}
catch (Exception ex) {}
return null;
}
private void listResults_MouseDoubleClick(object sender, MouseEventArgs e)
{
var IPAddress = getSelectedIPAddress();
if (IPAddress != null)
{
testSingleIP(IPAddress);
}
}
private void updateCFIPListStatusText()
{
var ipRangeCounts = getCheckedCFIPList(true);
uint sum = 0;
foreach (var item in ipRangeCounts)
{
sum += uint.Parse(item.Replace(",",""));
}
lblCFIPListStatus.Text = $"{ipRangeCounts.Length} Cloudflare IP ranges are selected, contains {sum:n0} IPs";
}
private void btnSelectAllIPRanges_Click(object sender, EventArgs e)
{
changeCFListViewItemsCheckState(true);
}
private void btnSelectNoneIPRanges_Click(object sender, EventArgs e)
{
changeCFListViewItemsCheckState(false);
}
private void changeCFListViewItemsCheckState(bool isChecked)
{
listCFIPList.BeginUpdate();
isUpdatinglistCFIP = true;
foreach (ListViewItem item in listCFIPList.Items)
{
item.Checked = isChecked;
}
listCFIPList.EndUpdate();
isUpdatinglistCFIP = false;
updateCFIPListStatusText();
}
private void listCFIPList_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if(!isUpdatinglistCFIP)
updateCFIPListStatusText();
}
private void showCanNotContinueMessage()
{
MessageBox.Show("App configuration file is not valid. We can not continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
addTextLog("Exiting...");
waitUntilScannerStoped();
}
private void waitUntilScannerStoped()
{
if (scanEngine.progressInfo.isScanRunning)
{
// stop scan
scanEngine.stop();
do
{
System.Windows.Forms.Application.DoEvents();
Thread.Sleep(100);
} while (scanEngine.progressInfo.isScanRunning);
}
}
private void linkGithub_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
ProcessStartInfo sInfo = new ProcessStartInfo(ourGitHubUrl) { UseShellExecute = true };
Process.Start(sInfo);
}
catch (Exception)
{
addTextLog($"Visit us on {ourGitHubUrl}");
throw;
}
}
}
}