-
Notifications
You must be signed in to change notification settings - Fork 809
Expand file tree
/
Copy pathPortScannerViewModel.cs
More file actions
570 lines (462 loc) · 15.2 KB
/
PortScannerViewModel.cs
File metadata and controls
570 lines (462 loc) · 15.2 KB
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
using log4net;
using MahApps.Metro.Controls;
using MahApps.Metro.SimpleChildWindow;
using NETworkManager.Controls;
using NETworkManager.Localization.Resources;
using NETworkManager.Models.Export;
using NETworkManager.Models.Network;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using NETworkManager.Views;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
namespace NETworkManager.ViewModels;
/// <summary>
/// ViewModel for the Port Scanner feature.
/// </summary>
public class PortScannerViewModel : ViewModelBase
{
#region Variables
private static readonly ILog Log = LogManager.GetLogger(typeof(PortScannerViewModel));
private CancellationTokenSource _cancellationTokenSource;
private readonly Guid _tabId;
private bool _firstLoad = true;
private bool _closed;
/// <summary>
/// Gets or sets the host to scan.
/// </summary>
public string Host
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the collection view for the host history.
/// </summary>
public ICollectionView HostHistoryView { get; }
/// <summary>
/// Gets or sets the ports to scan (e.g., "80, 443, 1-100").
/// </summary>
public string Ports
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the collection view for the ports history.
/// </summary>
public ICollectionView PortsHistoryView { get; }
/// <summary>
/// Gets or sets a value indicating whether the scan is currently running.
/// </summary>
public bool IsRunning
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the scan is being canceled.
/// </summary>
public bool IsCanceling
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets the collection of scan results.
/// </summary>
public ObservableCollection<PortScannerPortInfo> Results
{
get;
set
{
if (field != null && value == field)
return;
field = value;
}
} = [];
/// <summary>
/// Gets the collection view for the scan results.
/// </summary>
public ICollectionView ResultsView { get; }
/// <summary>
/// Gets or sets the currently selected scan result.
/// </summary>
public PortScannerPortInfo SelectedResult
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets the list of currently selected scan results (for multi-selection).
/// </summary>
public IList SelectedResults
{
get;
set
{
if (Equals(value, field))
return;
field = value;
OnPropertyChanged();
}
} = new ArrayList();
/// <summary>
/// Gets or sets the total number of ports to scan.
/// </summary>
public int PortsToScan
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets the number of ports already scanned.
/// </summary>
public int PortsScanned
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the scan is being prepared.
/// </summary>
public bool PreparingScan
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the status message is displayed.
/// </summary>
public bool IsStatusMessageDisplayed
{
get;
set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
/// <summary>
/// Gets the status message to display.
/// </summary>
public string StatusMessage
{
get;
private set
{
if (value == field)
return;
field = value;
OnPropertyChanged();
}
}
#endregion
#region Constructor, load settings, shutdown
/// <summary>
/// Initializes a new instance of the <see cref="PortScannerViewModel"/> class.
/// </summary>
/// <param name="tabId">The unique identifier for the tab.</param>
/// <param name="host">The initial host to scan.</param>
/// <param name="port">The initial ports to scan.</param>
public PortScannerViewModel(Guid tabId, string host, string port)
{
ConfigurationManager.Current.PortScannerTabCount++;
_tabId = tabId;
Host = host;
Ports = port;
// Set collection view
HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_HostHistory);
PortsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortHistory);
// Result view
ResultsView = CollectionViewSource.GetDefaultView(Results);
ResultsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PortScannerPortInfo.HostAsString)));
LoadSettings();
}
private void LoadSettings()
{
}
public void OnLoaded()
{
if (!_firstLoad)
return;
if (!string.IsNullOrEmpty(Host) && !string.IsNullOrEmpty(Ports))
_ = Start();
_firstLoad = false;
}
public void OnClose()
{
// Prevent multiple calls
if (_closed)
return;
_closed = true;
// Stop scan
if (IsRunning)
Stop();
ConfigurationManager.Current.PortScannerTabCount--;
}
#endregion
#region ICommands & Actions
public ICommand OpenPortProfileSelectionCommand =>
new RelayCommand(_ => OpenPortProfileSelectionAction(), OpenPortProfileSelection_CanExecute);
private bool OpenPortProfileSelection_CanExecute(object parameter)
{
return Application.Current.MainWindow != null &&
!((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen &&
!ConfigurationManager.Current.IsChildWindowOpen;
}
private void OpenPortProfileSelectionAction()
{
_ = OpenPortProfileSelection();
}
public ICommand ScanCommand => new RelayCommand(_ => ScanAction(), Scan_CanExecute);
private bool Scan_CanExecute(object parameter)
{
return Application.Current.MainWindow != null &&
!((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen &&
!ConfigurationManager.Current.IsChildWindowOpen;
}
private void ScanAction()
{
if (IsRunning)
Stop();
else
_ = Start();
}
public ICommand ExportCommand => new RelayCommand(_ => ExportAction());
private void ExportAction()
{
_ = Export();
}
#endregion
#region Methods
private async Task OpenPortProfileSelection()
{
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
var childWindow = new PortProfilesChildWindow(window);
var childWindowViewModel = new PortProfilesViewModel(async instance =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
Ports = string.Join("; ", instance.GetSelectedPortProfiles().Select(x => x.Ports));
}, async _ =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
});
childWindow.Title = Strings.SelectPortProfile;
childWindow.DataContext = childWindowViewModel;
ConfigurationManager.Current.IsChildWindowOpen = true;
await window.ShowChildWindowAsync(childWindow);
}
private async Task Start()
{
IsStatusMessageDisplayed = false;
StatusMessage = string.Empty;
IsRunning = true;
PreparingScan = true;
Results.Clear();
DragablzTabItem.SetTabHeader(_tabId, Host);
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = new CancellationTokenSource();
// Resolve hostnames
(List<(IPAddress ipAddress, string hostname)> hosts, List<string> hostnamesNotResolved) hosts;
try
{
hosts = await HostRangeHelper.ResolveAsync(HostRangeHelper.CreateListFromInput(Host),
SettingsManager.Current.Network_ResolveHostnamePreferIPv4, _cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
UserHasCanceled(this, EventArgs.Empty);
return;
}
// Show error message if (some) hostnames could not be resolved
if (hosts.hostnamesNotResolved.Count > 0)
{
StatusMessage =
$"{Strings.TheFollowingHostnamesCouldNotBeResolved} {string.Join(", ", hosts.hostnamesNotResolved)}";
IsStatusMessageDisplayed = true;
}
// Convert ports to int array
var ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Ports);
PortsToScan = ports.Length * hosts.hosts.Count;
PortsScanned = 0;
PreparingScan = false;
// Add host(s) to the history
AddHostToHistory(Host);
AddPortToHistory(Ports);
var portScanner = new PortScanner(new PortScannerOptions(
SettingsManager.Current.PortScanner_MaxHostThreads,
SettingsManager.Current.PortScanner_MaxPortThreads,
SettingsManager.Current.PortScanner_Timeout,
SettingsManager.Current.PortScanner_ResolveHostname,
SettingsManager.Current.PortScanner_ShowAllResults
));
portScanner.PortScanned += PortScanned;
portScanner.ScanComplete += ScanComplete;
portScanner.ProgressChanged += ProgressChanged;
portScanner.UserHasCanceled += UserHasCanceled;
portScanner.ScanAsync(hosts.hosts, ports, _cancellationTokenSource.Token);
}
private void Stop()
{
IsCanceling = true;
_cancellationTokenSource.Cancel();
}
private Task Export()
{
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
var childWindow = new ExportChildWindow();
var childWindowViewModel = new ExportViewModel(async instance =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
try
{
ExportManager.Export(instance.FilePath, instance.FileType,
instance.ExportAll
? Results
: new ObservableCollection<PortScannerPortInfo>(SelectedResults.Cast<PortScannerPortInfo>()
.ToArray()));
}
catch (Exception ex)
{
Log.Error("Error while exporting data as " + instance.FileType, ex);
await DialogHelper.ShowMessageAsync(window, Strings.Error,
Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine +
Environment.NewLine + ex.Message, ChildWindowIcon.Error);
}
SettingsManager.Current.PortScanner_ExportFileType = instance.FileType;
SettingsManager.Current.PortScanner_ExportFilePath = instance.FilePath;
}, _ =>
{
childWindow.IsOpen = false;
ConfigurationManager.Current.IsChildWindowOpen = false;
}, [
ExportFileType.Csv, ExportFileType.Xml, ExportFileType.Json
], true, SettingsManager.Current.PortScanner_ExportFileType,
SettingsManager.Current.PortScanner_ExportFilePath);
childWindow.Title = Strings.Export;
childWindow.DataContext = childWindowViewModel;
ConfigurationManager.Current.IsChildWindowOpen = true;
return window.ShowChildWindowAsync(childWindow);
}
private void AddHostToHistory(string host)
{
// Create the new list
var list = ListHelper.Modify(SettingsManager.Current.PortScanner_HostHistory.ToList(), host,
SettingsManager.Current.General_HistoryListEntries);
// Clear the old items
SettingsManager.Current.PortScanner_HostHistory.Clear();
OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared
// Fill with the new items
list.ForEach(x => SettingsManager.Current.PortScanner_HostHistory.Add(x));
}
private void AddPortToHistory(string port)
{
// Create the new list
var list = ListHelper.Modify(SettingsManager.Current.PortScanner_PortHistory.ToList(), port,
SettingsManager.Current.General_HistoryListEntries);
// Clear the old items
SettingsManager.Current.PortScanner_PortHistory.Clear();
OnPropertyChanged(nameof(Ports)); // Raise property changed again, after the collection has been cleared
// Fill with the new items
list.ForEach(x => SettingsManager.Current.PortScanner_PortHistory.Add(x));
}
#endregion
#region Events
private void PortScanned(object sender, PortScannerPortScannedArgs e)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(delegate { Results.Add(e.Args); }));
}
private void ProgressChanged(object sender, ProgressChangedArgs e)
{
PortsScanned = e.Value;
}
private void ScanComplete(object sender, EventArgs e)
{
// Run in UI thread with lower priority than PortScanned event
// to ensure all results are added first #3285
Application.Current.Dispatcher.Invoke(() =>
{
if (Results.Count == 0)
{
StatusMessage = Strings.NoOpenPortsFound;
IsStatusMessageDisplayed = true;
}
IsCanceling = false;
IsRunning = false;
}, DispatcherPriority.Background);
}
private void UserHasCanceled(object sender, EventArgs e)
{
StatusMessage = Strings.CanceledByUserMessage;
IsStatusMessageDisplayed = true;
IsCanceling = false;
IsRunning = false;
}
#endregion
}