-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGW-Router-Logger.ps1
More file actions
1477 lines (1284 loc) · 50 KB
/
GW-Router-Logger.ps1
File metadata and controls
1477 lines (1284 loc) · 50 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
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
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 2
# GW Router Logger
# This script is intentionally organized as small functions so that later features can be
# added without rewriting the listener loop, menu flow, or log retention logic.
try {
Add-Type -AssemblyName System.IO.Compression.FileSystem
}
catch {
throw 'The built-in compression assembly could not be loaded. This script requires standard .NET compression support.'
}
# These script-scoped values act as the main tuning points for future maintenance.
# Keeping them together makes it easier to adjust behavior without searching the file.
$script:AppName = 'GW Router Logger'
$script:MaxCompressedBytes = 100MB
$script:ActiveLogRotateBytes = 5MB
$script:ActiveLogRotateMinutes = 60
$script:RecentEventsMax = 12
$script:StatusRefreshMilliseconds = 2000
$script:DefaultUdpPort = 514
$script:DefaultTcpPort = 514
$script:LastSettings = $null
function Write-Rule {
param(
[int] $Width = 72,
[ConsoleColor] $Color = [ConsoleColor]::DarkCyan
)
Write-UiLine (''.PadLeft($Width, '=')) $Color
}
function Write-TitleBlock {
param(
[string] $Title,
[string] $Subtitle = ''
)
Write-Rule
Write-UiLine (' {0}' -f $Title) Cyan
if (-not [string]::IsNullOrWhiteSpace($Subtitle)) {
Write-UiLine (' {0}' -f $Subtitle) DarkGray
}
Write-Rule
}
function Show-StartupSplash {
Clear-Host
Write-Rule -Width 78 -Color DarkCyan
Write-UiLine ' _______ _______ _______ _ _______ _______ ' Cyan
Write-UiLine ' ( ____ \|\ /|( ___ )( ____ \| \ /\( ____ )( ____ \' Cyan
Write-UiLine ' | ( \/| ) ( || ( ) || ( \/| \ / /| ( )|| ( \/' Cyan
Write-UiLine ' | | | | _ | || (___) || (_____ | (_/ / | (____)|| (__ ' Cyan
Write-UiLine ' | | ____ | |( )| || ___ |(_____ )| _ ( | __)| __) ' Cyan
Write-UiLine ' | | \_ )| || || || ( ) | ) || ( \ \ | (\ ( | ( ' Cyan
Write-UiLine ' | (___) || () () || ) ( |/\____) || / \ \| ) \ \__| (____/\' Cyan
Write-UiLine ' (_______)(_______)|/ \|\_______)|_/ \/|/ \__/(_______/' Cyan
Write-Rule -Width 78 -Color DarkCyan
Write-UiLine ' GW ROUTER LOGGER' White
Write-UiLine ' Residential-friendly PowerShell syslog collector' DarkGray
Write-Host
Write-LabelValue -Label 'Mode' -Value 'Menu-driven foreground listener' -ValueColor Gray
Write-LabelValue -Label 'Defaults' -Value 'Router-friendly setup with defensive validation' -ValueColor Gray
Write-LabelValue -Label 'Storage' -Value 'Rolling compressed logs capped at 100 MB' -ValueColor Gray
Write-Host
Write-UiLine ' Starting...' DarkCyan
Start-Sleep -Milliseconds 900
}
function Write-LabelValue {
param(
[string] $Label,
[string] $Value,
[ConsoleColor] $ValueColor = [ConsoleColor]::Gray
)
Write-Host ('{0,-15}' -f $Label) -NoNewline
Write-Host ' ' -NoNewline
$original = [Console]::ForegroundColor
try {
[Console]::ForegroundColor = $ValueColor
Write-Host $Value
}
finally {
[Console]::ForegroundColor = $original
}
}
function Get-StatusColor {
param([string] $Status)
switch ($Status) {
'Running' { return [ConsoleColor]::Green }
'Starting' { return [ConsoleColor]::Yellow }
'Stopped' { return [ConsoleColor]::DarkGray }
default { return [ConsoleColor]::Gray }
}
}
function Write-UiLine {
param(
[string] $Message,
[ConsoleColor] $Color = [ConsoleColor]::Gray
)
$original = [Console]::ForegroundColor
try {
[Console]::ForegroundColor = $Color
Write-Host $Message
}
finally {
[Console]::ForegroundColor = $original
}
}
function Test-IsAdministrator {
try {
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentIdentity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
catch {
return $false
}
}
function Test-EnvironmentCompatibility {
if ($PSVersionTable.PSVersion.Major -lt 3) {
throw 'PowerShell 3.0 or later is required.'
}
}
function Ensure-Elevation {
if (Test-IsAdministrator) {
return $true
}
if (-not $PSCommandPath) {
Write-UiLine 'This script must run as Administrator.' Yellow
Write-UiLine 'Open PowerShell as Administrator and run the script again from the file path.' Yellow
return $false
}
try {
$quotedScript = '"' + $PSCommandPath + '"'
$encodedArgs = '-NoProfile -ExecutionPolicy Bypass -File ' + $quotedScript
Start-Process -FilePath 'powershell.exe' -ArgumentList $encodedArgs -Verb RunAs | Out-Null
return $false
}
catch {
Write-UiLine 'Administrator rights are required and self-elevation did not succeed.' Yellow
Write-UiLine 'Please right-click PowerShell and choose "Run as administrator", then run this script again.' Yellow
return $false
}
}
function Pause-ForUser {
param([string] $Message = 'Press Enter to continue')
Write-Host
Read-Host $Message | Out-Null
}
function Get-ScriptRootPath {
if ($PSScriptRoot) {
return $PSScriptRoot
}
if ($PSCommandPath) {
return (Split-Path -Path $PSCommandPath -Parent)
}
return (Get-Location).Path
}
function Ensure-Directory {
param([Parameter(Mandatory = $true)] [string] $Path)
if (-not (Test-Path -LiteralPath $Path)) {
[void] (New-Item -ItemType Directory -Path $Path -Force)
}
return (Resolve-Path -LiteralPath $Path).Path
}
function Get-TimestampString {
return (Get-Date).ToString('yyyy-MM-dd HH:mm:ss.fff')
}
function New-RuntimeState {
param([hashtable] $Settings)
return @{
StartTime = Get-Date
Status = 'Starting'
LastError = ''
LastReceiveTime = $null
LastSender = ''
LastProtocol = ''
MessageCount = 0
UdpCount = 0
TcpCount = 0
SourceCounts = @{}
RecentEvents = New-Object System.Collections.ArrayList
Settings = $Settings
ForceRefresh = $true
LastScreenRenderTime = $null
LastScreenSignature = ''
}
}
function Add-RecentEvent {
param(
[hashtable] $State,
[string] $Message
)
$timestamped = '{0} {1}' -f (Get-Date).ToString('HH:mm:ss'), $Message
[void] $State.RecentEvents.Add($timestamped)
while ($State.RecentEvents.Count -gt $script:RecentEventsMax) {
$State.RecentEvents.RemoveAt(0)
}
$State.ForceRefresh = $true
}
function Get-SafeFileName {
param([string] $Value)
if ([string]::IsNullOrWhiteSpace($Value)) {
return 'unknown-source'
}
$invalidChars = [IO.Path]::GetInvalidFileNameChars()
$safeValue = $Value
foreach ($char in $invalidChars) {
$safeValue = $safeValue.Replace([string] $char, '_')
}
$safeValue = $safeValue -replace '\s+', '_'
$safeValue = $safeValue.Trim(' ._')
if ([string]::IsNullOrWhiteSpace($safeValue)) {
return 'unknown-source'
}
if (Test-IsReservedFileStem -Value $safeValue) {
return ('device-{0}' -f $safeValue.ToLowerInvariant())
}
return $safeValue
}
function Get-LocalIpv4Addresses {
$results = New-Object System.Collections.ArrayList
try {
foreach ($nic in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if ($nic.OperationalStatus -ne [System.Net.NetworkInformation.OperationalStatus]::Up) {
continue
}
if ($nic.NetworkInterfaceType -eq [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback) {
continue
}
$properties = $nic.GetIPProperties()
foreach ($unicast in $properties.UnicastAddresses) {
if ($unicast.Address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
continue
}
$entry = [PSCustomObject] @{
Name = $nic.Name
Description = $nic.Description
Address = $unicast.Address.IPAddressToString
}
[void] $results.Add($entry)
}
}
}
catch {
}
return @($results | Sort-Object Address -Unique)
}
function Get-PrimaryGatewayAddressInfo {
$addresses = Get-LocalIpv4Addresses
if (-not $addresses -or $addresses.Count -eq 0) {
return $null
}
try {
foreach ($nic in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if ($nic.OperationalStatus -ne [System.Net.NetworkInformation.OperationalStatus]::Up) {
continue
}
if ($nic.NetworkInterfaceType -eq [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback) {
continue
}
$properties = $nic.GetIPProperties()
$hasIpv4Gateway = $false
foreach ($gateway in $properties.GatewayAddresses) {
if ($gateway.Address -and $gateway.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) {
if ($gateway.Address.IPAddressToString -ne '0.0.0.0') {
$hasIpv4Gateway = $true
$gatewayAddress = $gateway.Address.IPAddressToString
break
}
}
}
if (-not $hasIpv4Gateway) {
continue
}
foreach ($unicast in $properties.UnicastAddresses) {
if ($unicast.Address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
continue
}
return [PSCustomObject] @{
InterfaceName = $nic.Name
LocalAddress = $unicast.Address.IPAddressToString
GatewayAddress = $gatewayAddress
}
}
}
}
catch {
}
return $null
}
function Read-ValidatedPort {
param(
[string] $Prompt,
[int] $Default
)
while ($true) {
$rawValue = Read-Host "$Prompt [$Default] or type 0 to disable"
if ([string]::IsNullOrWhiteSpace($rawValue)) {
return $Default
}
$port = 0
if (-not [int]::TryParse($rawValue, [ref] $port)) {
Write-UiLine 'Please enter a valid whole number between 0 and 65535.' Yellow
continue
}
if ($port -lt 0 -or $port -gt 65535) {
Write-UiLine 'Port must be between 0 and 65535.' Yellow
continue
}
return $port
}
}
function Read-ValidatedPositiveInt {
param(
[string] $Prompt,
[int] $Default,
[int] $Minimum = 1
)
while ($true) {
$rawValue = Read-Host ('{0} [{1}]' -f $Prompt, $Default)
if ([string]::IsNullOrWhiteSpace($rawValue)) {
return $Default
}
$value = 0
if (-not [int]::TryParse($rawValue, [ref] $value)) {
Write-UiLine 'Please enter a valid whole number.' Yellow
continue
}
if ($value -lt $Minimum) {
Write-UiLine ('Please enter a number greater than or equal to {0}.' -f $Minimum) Yellow
continue
}
return $value
}
}
function Read-BooleanChoice {
param(
[string] $Prompt,
[bool] $Default
)
$defaultText = if ($Default) { 'Y/n' } else { 'y/N' }
while ($true) {
$rawValue = Read-Host "$Prompt [$defaultText]"
if ([string]::IsNullOrWhiteSpace($rawValue)) {
return $Default
}
switch -Regex ($rawValue.Trim()) {
'^(y|yes)$' { return $true }
'^(n|no)$' { return $false }
default { Write-UiLine 'Please answer yes or no.' Yellow }
}
}
}
function Read-MenuChoice {
param(
[string] $Prompt,
[string[]] $ValidChoices,
[string] $DefaultChoice
)
while ($true) {
$rawValue = Read-Host $Prompt
if ([string]::IsNullOrWhiteSpace($rawValue)) {
if ($DefaultChoice) {
return $DefaultChoice
}
}
else {
$normalized = $rawValue.Trim().ToUpperInvariant()
if ($ValidChoices -contains $normalized) {
return $normalized
}
}
Write-UiLine ('Please enter one of: {0}' -f ($ValidChoices -join ', ')) Yellow
}
}
function Select-BindAddress {
param([string] $DefaultAddress)
$addresses = Get-LocalIpv4Addresses
$gatewayInfo = Get-PrimaryGatewayAddressInfo
if ($gatewayInfo) {
Write-UiLine 'Detected the adapter currently using the default gateway.' Cyan
Write-Host ('Suggested local IP: {0} (gateway {1}, adapter {2})' -f $gatewayInfo.LocalAddress, $gatewayInfo.GatewayAddress, $gatewayInfo.InterfaceName)
$useSuggested = Read-MenuChoice -Prompt 'Use this local IP for listening? [Y/n]' -ValidChoices @('Y', 'N') -DefaultChoice 'Y'
if ($useSuggested -eq 'Y') {
return $gatewayInfo.LocalAddress
}
}
if ($addresses.Count -eq 0) {
Write-UiLine 'No active IPv4 addresses were detected. Enter the local IP manually.' Yellow
}
else {
Write-UiLine 'Available IPv4 addresses:' Cyan
for ($index = 0; $index -lt $addresses.Count; $index++) {
$entry = $addresses[$index]
Write-Host ('[{0}] {1} ({2})' -f ($index + 1), $entry.Address, $entry.Name)
}
Write-Host '[M] Enter a custom IP address'
if ($DefaultAddress) {
Write-Host "[Enter] Use previous choice: $DefaultAddress"
}
}
while ($true) {
$rawValue = Read-Host 'Select a bind address'
if ([string]::IsNullOrWhiteSpace($rawValue) -and $DefaultAddress) {
return $DefaultAddress
}
$selectedIndex = 0
if ($addresses.Count -gt 0 -and [int]::TryParse($rawValue, [ref] $selectedIndex)) {
if ($selectedIndex -ge 1 -and $selectedIndex -le $addresses.Count) {
return $addresses[$selectedIndex - 1].Address
}
}
if ($rawValue -match '^(m|manual)$') {
$manual = Read-Host 'Enter the local IPv4 address to bind'
try {
$parsed = [System.Net.IPAddress]::Parse($manual)
if ($parsed.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
throw 'IPv4 required'
}
return $parsed.IPAddressToString
}
catch {
Write-UiLine 'Please enter a valid IPv4 address.' Yellow
continue
}
}
try {
$parsed = [System.Net.IPAddress]::Parse($rawValue)
if ($parsed.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
throw 'IPv4 required'
}
return $parsed.IPAddressToString
}
catch {
Write-UiLine 'Choose a listed number or enter a valid IPv4 address.' Yellow
}
}
}
function Get-RunSettings {
$defaultBind = $null
$defaultUdp = $script:DefaultUdpPort
$defaultTcp = $script:DefaultTcpPort
$defaultLookup = $true
$defaultLogPath = Join-Path -Path (Get-ScriptRootPath) -ChildPath 'GW-ROUTER-LOGS'
if ($script:LastSettings) {
$defaultBind = $script:LastSettings.BindAddress
$defaultUdp = [int] $script:LastSettings.UdpPort
$defaultTcp = [int] $script:LastSettings.TcpPort
$defaultLookup = [bool] $script:LastSettings.ResolveHostNames
$defaultLogPath = $script:LastSettings.LogRoot
}
Clear-Host
Write-TitleBlock -Title 'GW ROUTER LOGGER' -Subtitle 'Listener configuration'
Write-Host
Write-UiLine 'Most residential routers use UDP port 514.' Cyan
Write-UiLine 'Press Enter to use the common router defaults: UDP 514 and TCP disabled.' DarkGray
$modeChoice = Read-MenuChoice -Prompt 'Use common router defaults? [Y/n]' -ValidChoices @('Y', 'N') -DefaultChoice 'Y'
$bindAddress = Select-BindAddress -DefaultAddress $defaultBind
if ($modeChoice -eq 'Y') {
$udpPort = 514
$tcpPort = 0
Write-UiLine 'Using router defaults: UDP 514, TCP disabled.' DarkGreen
}
else {
$udpPort = Read-ValidatedPort -Prompt 'UDP syslog port' -Default $defaultUdp
$tcpPort = Read-ValidatedPort -Prompt 'TCP syslog port' -Default $defaultTcp
}
if ($udpPort -eq 0 -and $tcpPort -eq 0) {
throw 'At least one listener must be enabled.'
}
$resolveHostNames = Read-BooleanChoice -Prompt 'Resolve source IPs to host names when possible' -Default $defaultLookup
$useDefaultLogPath = Read-MenuChoice -Prompt ('Use default path for logs? [Y/n] {0}' -f $defaultLogPath) -ValidChoices @('Y', 'N') -DefaultChoice 'Y'
if ($useDefaultLogPath -eq 'Y') {
$logRoot = $defaultLogPath
}
else {
while ($true) {
$logRootInput = Read-Host 'Enter the full folder path for logs'
if ([string]::IsNullOrWhiteSpace($logRootInput)) {
Write-UiLine 'Please enter a folder path.' Yellow
continue
}
try {
$logRoot = Get-NormalizedPath -Path $logRootInput.Trim('"')
break
}
catch {
Write-UiLine $_.Exception.Message Yellow
}
}
}
$settings = @{
BindAddress = $bindAddress
UdpPort = $udpPort
TcpPort = $tcpPort
ResolveHostNames = $resolveHostNames
LogRoot = $logRoot
SourceLogRoot = Join-Path -Path $logRoot -ChildPath 'sources'
ServerLogRoot = Join-Path -Path $logRoot -ChildPath 'server'
}
$script:LastSettings = $settings.Clone()
return $settings
}
function Resolve-LogPaths {
param([hashtable] $Settings)
$Settings.LogRoot = Ensure-Directory -Path $Settings.LogRoot
$Settings.SourceLogRoot = Ensure-Directory -Path $Settings.SourceLogRoot
$Settings.ServerLogRoot = Ensure-Directory -Path $Settings.ServerLogRoot
}
function Get-ShortHash {
param([string] $Value)
$bytes = [Text.Encoding]::UTF8.GetBytes($Value)
$sha1 = [Security.Cryptography.SHA1]::Create()
try {
$hash = $sha1.ComputeHash($bytes)
}
finally {
$sha1.Dispose()
}
return ([BitConverter]::ToString($hash)).Replace('-', '').Substring(0, 10).ToLowerInvariant()
}
function Get-SafeLogPath {
param(
[Parameter(Mandatory = $true)] [string] $Directory,
[Parameter(Mandatory = $true)] [string] $BaseName,
[Parameter(Mandatory = $true)] [string] $Suffix
)
$safeName = Get-SafeFileName -Value $BaseName
$candidate = Join-Path -Path $Directory -ChildPath ($safeName + $Suffix)
if ($candidate.Length -le 240) {
return $candidate
}
$hash = Get-ShortHash -Value $BaseName
$trimmed = $safeName
if ($trimmed.Length -gt 48) {
$trimmed = $trimmed.Substring(0, 48)
}
return (Join-Path -Path $Directory -ChildPath ('{0}-{1}{2}' -f $trimmed, $hash, $Suffix))
}
function Rotate-And-CompressLog {
param(
[Parameter(Mandatory = $true)] [string] $LogFilePath,
[Parameter(Mandatory = $true)] [string] $ArchiveDirectory,
[hashtable] $State
)
if (-not (Test-Path -LiteralPath $LogFilePath)) {
return
}
# Rotate active logs on either size or age so quiet systems still archive regularly
# and busy systems do not let a single active file grow too large.
$fileInfo = Get-Item -LiteralPath $LogFilePath
$ageMinutes = ((Get-Date) - $fileInfo.LastWriteTime).TotalMinutes
$shouldRotateBySize = $fileInfo.Length -ge $script:ActiveLogRotateBytes
$shouldRotateByAge = $ageMinutes -ge $script:ActiveLogRotateMinutes
if (-not $shouldRotateBySize -and -not $shouldRotateByAge) {
return
}
Ensure-Directory -Path $ArchiveDirectory | Out-Null
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$archiveBaseName = '{0}-{1}' -f $fileInfo.BaseName, $timestamp
$rotatedPath = Get-SafeLogPath -Directory $ArchiveDirectory -BaseName $archiveBaseName -Suffix '.log'
$zipPath = Get-SafeLogPath -Directory $ArchiveDirectory -BaseName $archiveBaseName -Suffix '.zip'
try {
Move-Item -LiteralPath $LogFilePath -Destination $rotatedPath -Force
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
try {
[void] [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zipArchive, $rotatedPath, ([IO.Path]::GetFileName($rotatedPath)), [System.IO.Compression.CompressionLevel]::Optimal)
}
finally {
$zipArchive.Dispose()
}
Remove-Item -LiteralPath $rotatedPath -Force -ErrorAction SilentlyContinue
if ($State) {
Add-RecentEvent -State $State -Message ('Archived {0}' -f [IO.Path]::GetFileName($zipPath))
}
}
catch {
if ($State) {
$State.LastError = 'Log rotation error: ' + $_.Exception.Message
Add-RecentEvent -State $State -Message $State.LastError
}
}
}
function Enforce-CompressedArchiveCap {
param(
[Parameter(Mandatory = $true)] [string] $RootPath,
[hashtable] $State
)
try {
$archives = @(Get-ChildItem -LiteralPath $RootPath -Recurse -File -Filter '*.zip' | Sort-Object LastWriteTimeUtc)
$totalBytes = 0
foreach ($archive in $archives) {
$totalBytes += [int64] $archive.Length
}
foreach ($archive in $archives) {
if ($totalBytes -le $script:MaxCompressedBytes) {
break
}
$length = $archive.Length
Remove-Item -LiteralPath $archive.FullName -Force -ErrorAction Stop
$totalBytes -= $length
if ($State) {
Add-RecentEvent -State $State -Message ('Pruned archive {0}' -f $archive.Name)
}
}
}
catch {
if ($State) {
$State.LastError = 'Archive pruning error: ' + $_.Exception.Message
Add-RecentEvent -State $State -Message $State.LastError
}
}
}
function Write-LogRecord {
param(
[hashtable] $Settings,
[hashtable] $State,
[string] $Category,
[string] $SourceName,
[string] $Message
)
$timestamp = Get-TimestampString
if ($Category -eq 'server') {
$targetPath = Get-SafeLogPath -Directory $Settings.ServerLogRoot -BaseName 'server-current' -Suffix '.log'
$archiveRoot = Join-Path -Path $Settings.ServerLogRoot -ChildPath 'archive'
}
else {
$targetPath = Get-SafeLogPath -Directory $Settings.SourceLogRoot -BaseName ($SourceName + '-current') -Suffix '.log'
$archiveRoot = Join-Path -Path $Settings.SourceLogRoot -ChildPath 'archive'
}
$line = '{0} [{1}] {2}' -f $timestamp, $Category.ToUpperInvariant(), $Message
try {
Add-Content -LiteralPath $targetPath -Value $line -Encoding UTF8
Rotate-And-CompressLog -LogFilePath $targetPath -ArchiveDirectory $archiveRoot -State $State
Enforce-CompressedArchiveCap -RootPath $Settings.LogRoot -State $State
}
catch {
if ($State) {
$State.LastError = 'Write log error: ' + $_.Exception.Message
Add-RecentEvent -State $State -Message $State.LastError
}
}
}
function Write-ServerEvent {
param(
[hashtable] $Settings,
[hashtable] $State,
[string] $Message
)
Write-LogRecord -Settings $Settings -State $State -Category 'server' -SourceName 'server' -Message $Message
}
function Resolve-SourceIdentity {
param(
[string] $Address,
[bool] $ResolveHostNames
)
if (-not $ResolveHostNames) {
return $Address
}
try {
$entry = [System.Net.Dns]::GetHostEntry($Address)
if ($entry.HostName) {
return '{0}_{1}' -f $entry.HostName, $Address
}
}
catch {
}
return $Address
}
function Test-IsReservedFileStem {
param([string] $Value)
$reserved = @(
'CON', 'PRN', 'AUX', 'NUL',
'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
)
return $reserved -contains $Value.ToUpperInvariant()
}
function Get-NormalizedPath {
param([Parameter(Mandatory = $true)] [string] $Path)
try {
return [IO.Path]::GetFullPath($Path)
}
catch {
throw "Invalid path: $Path"
}
}
function Test-PathWritable {
param([Parameter(Mandatory = $true)] [string] $DirectoryPath)
try {
$resolved = Ensure-Directory -Path $DirectoryPath
$probeFile = Join-Path -Path $resolved -ChildPath ('write-test-{0}.tmp' -f ([guid]::NewGuid().ToString('N')))
Set-Content -LiteralPath $probeFile -Value 'ok' -Encoding ASCII
Remove-Item -LiteralPath $probeFile -Force
return $true
}
catch {
return $false
}
}
function Resolve-PreferredLogRoot {
param([hashtable] $Settings)
# The script prefers the launch folder, but it should not fail there if permissions or
# path policies are different on another machine. These fallbacks are ordered by usefulness.
$candidates = New-Object System.Collections.ArrayList
[void] $candidates.Add((Get-NormalizedPath -Path $Settings.LogRoot))
[void] $candidates.Add((Join-Path -Path $env:ProgramData -ChildPath 'GW-ROUTER-LOGS'))
[void] $candidates.Add((Join-Path -Path $env:TEMP -ChildPath 'GW-ROUTER-LOGS'))
foreach ($candidate in $candidates) {
if ([string]::IsNullOrWhiteSpace($candidate)) {
continue
}
if (Test-PathWritable -DirectoryPath $candidate) {
$Settings.LogRoot = Ensure-Directory -Path $candidate
$Settings.SourceLogRoot = Ensure-Directory -Path (Join-Path -Path $Settings.LogRoot -ChildPath 'sources')
$Settings.ServerLogRoot = Ensure-Directory -Path (Join-Path -Path $Settings.LogRoot -ChildPath 'server')
return
}
}
throw 'No writable log folder was found. Try a different location or confirm disk permissions.'
}
function Test-PortAvailable {
param(
[string] $Address,
[int] $Port,
[ValidateSet('UDP', 'TCP')] [string] $Protocol
)
if ($Port -eq 0) {
return $true
}
try {
$endpoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Parse($Address)), $Port
if ($Protocol -eq 'UDP') {
$client = New-Object System.Net.Sockets.UdpClient
try {
$client.Client.Bind($endpoint)
}
finally {
$client.Dispose()
}
}
else {
$listener = New-Object System.Net.Sockets.TcpListener ([System.Net.IPAddress]::Parse($Address)), $Port
try {
$listener.Start()
}
finally {
$listener.Stop()
}
}
return $true
}
catch {
return $false
}
}
function Ensure-FirewallRule {
param(
[ValidateSet('UDP', 'TCP')] [string] $Protocol,
[int] $Port
)
if ($Port -eq 0) {
return
}
$ruleName = '{0} {1} {2}' -f $script:AppName, $Protocol, $Port
try {
if (Get-Command -Name Get-NetFirewallRule -ErrorAction SilentlyContinue) {
$existing = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
if ($existing) {
$null = $existing | Remove-NetFirewallRule -ErrorAction SilentlyContinue
}
New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Allow -Protocol $Protocol -LocalPort $Port -Profile Any | Out-Null
return
}
$arguments = @(
'advfirewall', 'firewall', 'delete', 'rule',
('name={0}' -f $ruleName)
)
& netsh @arguments | Out-Null
$arguments = @(
'advfirewall', 'firewall', 'add', 'rule',
('name={0}' -f $ruleName),
'dir=in',
'action=allow',
('protocol={0}' -f $Protocol),
('localport={0}' -f $Port)
)
& netsh @arguments | Out-Null
}
catch {
throw "Firewall update failed for $Protocol/$Port. $($_.Exception.Message)"
}
}
function Get-SyslogSummary {
param([string] $RawMessage)
$priority = ''
$content = $RawMessage.Trim()
if ($content -match '^<(?<pri>\d{1,3})>(?<rest>.*)$') {
$priority = $Matches.pri
$content = $Matches.rest.Trim()
}
$preview = $content
if ($preview.Length -gt 120) {
$preview = $preview.Substring(0, 120) + '...'
}
if ($priority) {
return "PRI=$priority $preview"
}
return $preview
}
function Register-ReceivedMessage {
param(
[hashtable] $Settings,
[hashtable] $State,
[string] $Protocol,
[string] $Address,
[string] $RawMessage
)
if ([string]::IsNullOrWhiteSpace($RawMessage)) {
return
}
$sourceIdentity = Resolve-SourceIdentity -Address $Address -ResolveHostNames $Settings.ResolveHostNames
$summary = Get-SyslogSummary -RawMessage $RawMessage
$State.Status = 'Running'
$State.LastReceiveTime = Get-Date
$State.LastSender = $sourceIdentity
$State.LastProtocol = $Protocol
$State.MessageCount++
if ($Protocol -eq 'UDP') {
$State.UdpCount++
}
else {
$State.TcpCount++
}
if (-not $State.SourceCounts.ContainsKey($sourceIdentity)) {
$State.SourceCounts[$sourceIdentity] = 0
}
$State.SourceCounts[$sourceIdentity]++
$State.ForceRefresh = $true
# Every inbound log updates both the console state and the durable log files so that
# troubleshooting can continue even after the console session ends.
Add-RecentEvent -State $State -Message ("$Protocol message from $sourceIdentity")
$messageLine = '{0} [{1}] {2}' -f $Address, $Protocol, $RawMessage.Trim()
Write-LogRecord -Settings $Settings -State $State -Category 'source' -SourceName $sourceIdentity -Message $messageLine
Write-ServerEvent -Settings $Settings -State $State -Message ("Received {0} message from {1}: {2}" -f $Protocol, $sourceIdentity, $summary)
}
function Show-NoLogGuidance {
param([hashtable] $Settings)
Clear-Host
Write-UiLine $script:AppName Yellow
Write-Host 'No logs have been received after 2 minutes.'
Write-Host
Write-Host 'Things to verify:'
Write-Host ('1. The router is sending syslog to this IP: {0}' -f $Settings.BindAddress)
if ($Settings.UdpPort -gt 0) {
Write-Host ('2. The router syslog port matches UDP {0}' -f $Settings.UdpPort)