Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions GW-Router-Logger.TrayMode.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ function Get-AppDataRoot {
return $programDataPath
}
catch {
Write-Verbose "An error occurred and was ignored."
# Fall back to a per-user app data folder when ProgramData is not writable.
}
}
Expand Down Expand Up @@ -397,6 +398,7 @@ function Write-AppLog {
Add-Content -LiteralPath (Get-AppLogPath) -Value $line -Encoding UTF8
}
catch {
Write-Verbose "An error occurred and was ignored."
# Diagnostic logging must never break the tray app.
}
}
Expand Down Expand Up @@ -983,15 +985,15 @@ function Initialize-FirewallRule {
return
}
catch {
$args = @(
$netshArgs = @(
'advfirewall', 'firewall', 'add', 'rule',
('name="{0}"' -f $ruleName),
'dir=in',
'action=allow',
('protocol={0}' -f $Protocol),
('localport={0}' -f $Port)
)
$process = Start-Process -FilePath 'netsh.exe' -ArgumentList $args -Wait -PassThru -WindowStyle Hidden
$process = Start-Process -FilePath 'netsh.exe' -ArgumentList $netshArgs -Wait -PassThru -WindowStyle Hidden
if ($process.ExitCode -ne 0) {
throw "netsh failed while adding firewall rule $ruleName."
}
Expand All @@ -1002,15 +1004,15 @@ function Add-FirewallRulesForConfig {
param([hashtable] $Config)

if (-not (Test-IsAdministrator)) {
$args = @(
$processArgs = @(
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', ('"{0}"' -f (Get-LauncherScriptPath)),
'-FirewallOnly',
'-FirewallUdpPort', ([string] $(if ([bool] $Config.UdpEnabled) { [int] $Config.UdpPort } else { 0 })),
'-FirewallTcpPort', ([string] $(if ([bool] $Config.TcpEnabled) { [int] $Config.TcpPort } else { 0 }))
)
Start-Process -FilePath "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList $args -Verb RunAs | Out-Null
Start-Process -FilePath "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList $processArgs -Verb RunAs | Out-Null
return
}

Expand All @@ -1023,6 +1025,7 @@ function Add-FirewallRulesForConfig {
}

function Invoke-FirewallOnlyMode {
param([int]$FirewallUdpPort, [int]$FirewallTcpPort)
if (-not (Test-IsAdministrator)) {
throw 'Firewall setup requires Administrator rights.'
}
Expand Down Expand Up @@ -1178,7 +1181,6 @@ function Initialize-ListenerScriptBlock {
function Write-LogRecord {
param(
[string] $Category,
[string] $SourceName,
[string] $Message
)

Expand Down Expand Up @@ -1226,8 +1228,8 @@ function Initialize-ListenerScriptBlock {
}

$messageLine = '{0} [{1}] {2}' -f $Address, $Protocol, $RawMessage.Trim()
Write-LogRecord -Category 'source' -SourceName $sourceIdentity -Message $messageLine
Write-LogRecord -Category 'server' -SourceName 'server' -Message ('Received {0} message from {1}: {2}' -f $Protocol, $sourceIdentity, (Get-SyslogSummary -RawMessage $RawMessage))
Write-LogRecord -Category 'source' -Message $messageLine
Write-LogRecord -Category 'server' -Message ('Received {0} message from {1}: {2}' -f $Protocol, $sourceIdentity, (Get-SyslogSummary -RawMessage $RawMessage))
}

function Get-CompletedTcpMessage {
Expand Down Expand Up @@ -1276,13 +1278,13 @@ function Initialize-ListenerScriptBlock {
$udpEndpoint = New-Object System.Net.IPEndPoint $bindIp, ([int] $Settings.UdpPort)
$udpClient = New-Object System.Net.Sockets.UdpClient
$udpClient.Client.Bind($udpEndpoint)
Write-LogRecord -Category 'server' -SourceName 'server' -Message ('UDP listener started on {0}:{1}.' -f $Settings.BindAddress, $Settings.UdpPort)
Write-LogRecord -Category 'server' -Message ('UDP listener started on {0}:{1}.' -f $Settings.BindAddress, $Settings.UdpPort)
}

if ([bool] $Settings.TcpEnabled) {
$tcpListener = New-Object System.Net.Sockets.TcpListener $bindIp, ([int] $Settings.TcpPort)
$tcpListener.Start()
Write-LogRecord -Category 'server' -SourceName 'server' -Message ('TCP listener started on {0}:{1}.' -f $Settings.BindAddress, $Settings.TcpPort)
Write-LogRecord -Category 'server' -Message ('TCP listener started on {0}:{1}.' -f $Settings.BindAddress, $Settings.TcpPort)
}

$Runtime.Running = $true
Expand Down Expand Up @@ -1314,7 +1316,7 @@ function Initialize-ListenerScriptBlock {
LastActivity = Get-Date
}
[void] $tcpClients.Add($clientState)
Write-LogRecord -Category 'server' -SourceName 'server' -Message ('TCP client connected: {0}' -f $clientState.Address)
Write-LogRecord -Category 'server' -Message ('TCP client connected: {0}' -f $clientState.Address)
}
}

Expand All @@ -1327,7 +1329,7 @@ function Initialize-ListenerScriptBlock {
if ($clientState.Buffer) {
Register-ReceivedMessage -Protocol 'TCP' -Address $clientState.Address -RawMessage $clientState.Buffer
}
Write-LogRecord -Category 'server' -SourceName 'server' -Message ('TCP client idle timeout: {0}' -f $clientState.Address)
Write-LogRecord -Category 'server' -Message ('TCP client idle timeout: {0}' -f $clientState.Address)
$removeClient = $true
}
elseif (Test-TcpClientClosed -TcpClient $clientState.Client) {
Expand All @@ -1352,7 +1354,7 @@ function Initialize-ListenerScriptBlock {
}
catch {
$Runtime.LastError = 'TCP client error: ' + $_.Exception.Message
Write-LogRecord -Category 'server' -SourceName 'server' -Message $Runtime.LastError
Write-LogRecord -Category 'server' -Message $Runtime.LastError
$removeClient = $true
}

Expand Down Expand Up @@ -1389,7 +1391,7 @@ function Initialize-ListenerScriptBlock {
try { $tcpListener.Stop() } catch { Write-Verbose "An error occurred and was ignored." }
}
try {
Write-LogRecord -Category 'server' -SourceName 'server' -Message 'Listener stopped.'
Write-LogRecord -Category 'server' -Message 'Listener stopped.'
}
catch { Write-Verbose "An error occurred and was ignored." }
$Runtime.Running = $false
Expand Down Expand Up @@ -2148,6 +2150,13 @@ function Invoke-UpdateCheckSelfTest {
'UPDATE_CHECK_OK {0} {1}' -f $releaseInfo.Version, $releaseInfo.AssetName
}

<#
.SYNOPSIS
Initializes and runs the GW Router Logger tray application.

.DESCRIPTION
Sets up the context menu, system tray icon, and background task processing.
#>
function Initialize-GWRouterLoggerTrayApp {
param(
[switch] $FirewallOnly,
Expand All @@ -2160,7 +2169,7 @@ function Initialize-GWRouterLoggerTrayApp {
)

if ($FirewallOnly) {
Invoke-FirewallOnlyMode
Invoke-FirewallOnlyMode -FirewallUdpPort $FirewallUdpPort -FirewallTcpPort $FirewallTcpPort
return
}

Expand Down
27 changes: 17 additions & 10 deletions GW-Router-Logger.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification='CLI UI')]
param(
[switch] $TrayApp,
[switch] $FirewallOnly,
Expand Down Expand Up @@ -68,7 +70,7 @@ if ($TrayApp -or $FirewallOnly -or $SelfTest -or $ListenerSelfTest -or $UpdateCh
}

Import-Module -Name $trayModulePath -Force -DisableNameChecking
Start-GWRouterLoggerTrayApp `
Initialize-GWRouterLoggerTrayApp `
-FirewallOnly:$FirewallOnly `
-SelfTest:$SelfTest `
-ListenerSelfTest:$ListenerSelfTest `
Expand Down Expand Up @@ -310,6 +312,8 @@ function Merge-TextFileIntoPath {
}

function Remove-DirectoryIfEmpty {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
param([string] $Path)

if (-not (Test-Path -LiteralPath $Path)) {
Expand Down Expand Up @@ -367,6 +371,8 @@ function Get-TimestampString {
}

function New-RuntimeState {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
param([hashtable] $Settings)

return @{
Expand Down Expand Up @@ -802,7 +808,7 @@ function Get-SafeLogPath {
return (Join-Path -Path $Directory -ChildPath ('{0}-{1}{2}' -f $trimmed, $hash, $Suffix))
}

function Archive-LogFile {
function Compress-LogFile {
param(
[Parameter(Mandatory = $true)] [string] $LogFilePath,
[Parameter(Mandatory = $true)] [string] $ArchiveDirectory,
Expand Down Expand Up @@ -894,7 +900,6 @@ function Write-LogRecord {
[hashtable] $Settings,
[hashtable] $State,
[string] $Category,
[string] $SourceName,
[string] $Message
)

Expand All @@ -911,7 +916,7 @@ function Write-LogRecord {
$line = '{0} [{1}] {2}' -f $timestamp, $Category.ToUpperInvariant(), $Message
try {
Add-Content -LiteralPath $targetPath -Value $line -Encoding UTF8
$rotated = Archive-LogFile -LogFilePath $targetPath -ArchiveDirectory $archiveRoot -State $State
$rotated = Compress-LogFile -LogFilePath $targetPath -ArchiveDirectory $archiveRoot -State $State
if ($rotated) {
Limit-CompressedArchive -RootPath $Settings.LogRoot -State $State
}
Expand All @@ -931,7 +936,7 @@ function Write-ServerEvent {
[string] $Message
)

Write-LogRecord -Settings $Settings -State $State -Category 'server' -SourceName 'server' -Message $Message
Write-LogRecord -Settings $Settings -State $State -Category 'server' -Message $Message
}

function Resolve-SourceIdentity {
Expand Down Expand Up @@ -1191,7 +1196,7 @@ function Register-ReceivedMessage {
# 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-LogRecord -Settings $Settings -State $State -Category 'source' -Message $messageLine
Write-ServerEvent -Settings $Settings -State $State -Message ("Received {0} message from {1}: {2}" -f $Protocol, $sourceIdentity, $summary)
}

Expand Down Expand Up @@ -1299,8 +1304,8 @@ function Show-StatusScreen {
}

$recentEventsText = ''
foreach ($event in $State.RecentEvents) {
$recentEventsText += $event + "`n"
foreach ($recentEvent in $State.RecentEvents) {
$recentEventsText += $recentEvent + "`n"
}

$signature = '{0}|{1}|{2}|{3}|{4}|{5}|{6}' -f `
Expand Down Expand Up @@ -1360,9 +1365,9 @@ function Show-StatusScreen {
Write-UiLine ' Waiting for activity...' DarkGray
}
else {
foreach ($event in $State.RecentEvents) {
foreach ($recentEvent in $State.RecentEvents) {
Write-Host ' ' -NoNewline
Write-UiLine $event Gray
Write-UiLine $recentEvent Gray
}
}

Expand All @@ -1376,6 +1381,8 @@ function Show-StatusScreen {
}

function Start-LogServer {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
param([hashtable] $Settings)

# This is the core runtime wrapper. Everything needed for environment validation happens
Expand Down
2 changes: 2 additions & 0 deletions Install-GWRouterLogger.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification='CLI UI')]
param(
[string] $InstallPath,
[switch] $DoNotStartAfterInstall,
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,7 @@ While the listener is running:
## License

This project is released under the MIT License. See [LICENSE](LICENSE).

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.
2 changes: 2 additions & 0 deletions Uninstall-GWRouterLogger.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification='CLI UI')]
param(
[switch] $Quiet,
[switch] $RemoveData
Expand Down