Skip to content

Commit

Permalink
Fixes regarding previous commit (wasn't skipping notifications for sa…
Browse files Browse the repository at this point in the history
…me app in "simple" mode for NotificationWindow, wasn't handling the new entries properly in EventsLog).
  • Loading branch information
wokhan committed Dec 3, 2020
1 parent a832a03 commit 4d3bcce
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 80 deletions.
78 changes: 47 additions & 31 deletions Common/Security/EventLogAsyncReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
Expand Down Expand Up @@ -80,7 +81,7 @@ public static bool IsFirewallEventAllowed(long instanceId)
}
}

public sealed class EventLogAsyncReader<T> : IPagedSourceProviderAsync<T>, IDisposable where T : class, new()
public sealed class EventLogAsyncReader<T> : IPagedSourceProviderAsync<T>, INotifyPropertyChanged, IDisposable where T : class, new()
{
public Func<EventLogEntry, bool>? FilterPredicate { get; set; }

Expand All @@ -97,11 +98,7 @@ public EventLogAsyncReader(string eventLogName, Func<EventLogEntry, int, T?> pro
_projection = projection;

eventLog = new EventLog(eventLogName);
eventLog.BeginInit();
// eventLog.EntryWritten += DefaultEntryWrittenEventHandler;
firstEventTimeWritten = DateTime.Now;
eventLog.EnableRaisingEvents = true;
eventLog.EndInit();

paginationManager = new PaginationManager<T>(this, pageSize: pageSize);

Expand All @@ -120,7 +117,9 @@ public EventLogAsyncReader(string eventLogName, Func<EventLogEntry, int, T?> pro
public void OnReset(int count)
{
firstEventTimeWritten = DateTime.Now;
newEntriesOffset = 0;
NewEntriesCount = 0;
NewMatchingEntriesCount = 0;
firstLoad = true;
filteredPagesMap.Clear();
}

Expand All @@ -136,13 +135,18 @@ public async Task<PagedSourceItemsPacket<T>> GetItemsAtAsync(int pageoffset, int

private readonly T placeHolder = new T();
private int matchesCount;
private int newEntriesOffset;
private bool firstLoad = true;
private DateTime firstEventTimeWritten;
private readonly PaginationManager<T> paginationManager;
//private int newMatchingEntries;

public event PropertyChangedEventHandler PropertyChanged;

public int NewMatchingEntriesCount { get; private set; }
public int NewEntriesCount { get; private set; }

public VirtualizingObservableCollection<T> Entries { get; }
public bool AutoUpdate { get; set; }

//public bool AutoUpdate { get; set; }

public T GetPlaceHolder(int index, int _ignored, int _alsoignored)
{
Expand All @@ -161,6 +165,14 @@ public async Task<int> IndexOfAsync(T item)

public PagedSourceItemsPacket<T> GetItemsAt(int pageoffset, int count, bool usePlaceholder)
{
if (firstLoad)
{
firstLoad = false;
eventLog.EntryWritten -= DefaultEntryWrittenEventHandler;
eventLog.EntryWritten += DefaultEntryWrittenEventHandler;
firstEventTimeWritten = DateTime.Now;
}

pageoffset = filteredPagesMap.GetValueOrDefault(pageoffset, pageoffset);

var ret = new PagedSourceItemsPacket<T>
Expand Down Expand Up @@ -193,7 +205,7 @@ private IEnumerable<T> GetAsEnumerable(int pageoffset, int count)
T? ret = null;
try
{
EventLogEntry? entry = eventLog.Entries[^(i + newEntriesOffset)];
EventLogEntry? entry = eventLog.Entries[^(i + NewEntriesCount)];
if (FilterPredicate?.Invoke(entry) ?? true)
{
matchesCount++;
Expand Down Expand Up @@ -223,27 +235,31 @@ private IEnumerable<T> GetAsEnumerable(int pageoffset, int count)
}
}

// TODO: fix and enable back. As of now AutoUpdate cannot be used.
//private void DefaultEntryWrittenEventHandler(object sender, EntryWrittenEventArgs e)
//{
// if (e.Entry.TimeWritten <= firstEventTimeWritten)
// {
// return;
// }

// newEntriesOffset++;

// if (FilterPredicate?.Invoke(e.Entry) ?? true)
// {
// newMatchingEntries++;
// if (AutoUpdate)
// {
// newEntriesOffset = 0;
// paginationManager.AddOrUpdateAdjustment(0, -1);
// newMatchingEntries = 0;
// }
// }
//}
private void DefaultEntryWrittenEventHandler(object sender, EntryWrittenEventArgs e)
{
if (e.Entry.TimeWritten <= firstEventTimeWritten)
{
return;
}

NewEntriesCount++;

if (FilterPredicate?.Invoke(e.Entry) ?? true)
{
NewMatchingEntriesCount++;

// TODO: fix and enable back. As of now AutoUpdate cannot be used.
//if (AutoUpdate)
//{
// NewEntriesCount = 0;
// paginationManager.AddOrUpdateAdjustment(0, -1);
// NewMatchingEntriesCount = 0;
//}
}

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NewEntriesCount)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NewMatchingEntriesCount)));
}

public void Dispose()
{
Expand Down
4 changes: 2 additions & 2 deletions Console/UI/Pages/EventsLog.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
<ContentControl Style="{StaticResource ToolBarPanel}">
<Grid IsEnabled="{Binding IsElevated,Source={x:Static Application.Current}}">
<StackPanel>
<Button ext:CustomAdorner.Image="{StaticResource Image_Refresh}" Content="Refresh" ToolTip="Reload to show the newest events" IsEnabled="{Binding NewEntriesCount,Converter={StaticResource objectToBool}}" Click="Refresh_Click" />
<Button ext:CustomAdorner.Image="{StaticResource Image_Refresh}" Content="Refresh" ToolTip="Reload to show the newest events" IsEnabled="{Binding EventsReader.NewMatchingEntriesCount,Converter={StaticResource objectToBool}}" Click="Refresh_Click" />
<Button Content="Locate" ext:CustomAdorner.Image="{StaticResource Image_Locate}" Click="btnLocate_Click" ToolTip="Locate the selected item" IsEnabled="{Binding SelectedItem,ElementName=gridLog,Converter={StaticResource objectToBool}}" />
<Button x:Name="btnEventLogVwr" ext:CustomAdorner.Image="/WFN;component/Resources/Images/btnLEvents.Image.png" Content="Events log viewer" Click="btnEventLogVwr_Click" />
<TextBlock VerticalAlignment="Center" Text="{Binding NewEntriesCount, StringFormat='{}{0} new event(s)', FallbackValue=''}" />
<TextBlock VerticalAlignment="Center" Text="{Binding EventsReader.NewMatchingEntriesCount, StringFormat='{}{0} new event(s)', FallbackValue='',TargetNullValue=''}" />
</StackPanel>
<StackPanel HorizontalAlignment="Right" Margin="3,0,3,0">
<TextBox ext:CustomAdorner.Header="Filter" x:Name="txtFilter" Width="149" Margin="3,0,3,0" Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" Background="White" Padding="3,0,3,0" Height="20" ToolTip="Filter to be applied for App, Service or Remote IP"/>
Expand Down
44 changes: 12 additions & 32 deletions Console/UI/Pages/EventsLog.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

using Wokhan.ComponentModel.Extensions;
using Wokhan.UI.Extensions;
using Wokhan.WindowsFirewallNotifier.Common.Config;
using Wokhan.WindowsFirewallNotifier.Common.Logging;
using Wokhan.WindowsFirewallNotifier.Common.Net.WFP;
using Wokhan.WindowsFirewallNotifier.Common.Processes;
using Wokhan.WindowsFirewallNotifier.Common.Security;
using Wokhan.WindowsFirewallNotifier.Common.UI.ViewModels;
Expand All @@ -23,18 +19,12 @@ namespace Wokhan.WindowsFirewallNotifier.Console.UI.Pages
/// </summary>
public sealed partial class EventsLog : Page, INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
public EventLogAsyncReader<LogEntryViewModel> EventsReader { get; set; }

private EventLogAsyncReader<LogEntryViewModel> eventsReader;
public ICollectionView dataView;
private readonly EventsLogFilters eventsLogFilters;

private uint newEntriesCount;
public uint NewEntriesCount
{
get => newEntriesCount;
set => this.SetValue(ref newEntriesCount, value, NotifyPropertyChanged);
}
public event PropertyChangedEventHandler PropertyChanged;

public bool IsTCPOnlyEnabled
{
Expand Down Expand Up @@ -81,16 +71,16 @@ private void StartHandlingSecurityLogEvents(bool reset = false)
{
try
{
if (reset || eventsReader is null)
if (reset || EventsReader is null)
{
NewEntriesCount = 0;
eventsReader?.Dispose();
eventsReader = new EventLogAsyncReader<LogEntryViewModel>(EventLogAsyncReader.EVENTLOG_SECURITY, LogEntryViewModel.CreateFromEventLogEntry)
EventsReader?.Dispose();
EventsReader = new EventLogAsyncReader<LogEntryViewModel>(EventLogAsyncReader.EVENTLOG_SECURITY, LogEntryViewModel.CreateFromEventLogEntry)
{
FilterPredicate = EventLogAsyncReader.IsFirewallEvent
};
eventsReader.EntryWritten += EntryWritten;
dataView = CollectionViewSource.GetDefaultView(eventsReader.Entries);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EventsReader)));

dataView = CollectionViewSource.GetDefaultView(EventsReader.Entries);
gridLog.ItemsSource = dataView;
}

Expand All @@ -105,15 +95,10 @@ private void StartHandlingSecurityLogEvents(bool reset = false)

private void StopHandlingSecurityLogEvents()
{
eventsReader?.Dispose();
eventsReader = null;
EventsReader?.Dispose();
EventsReader = null;
}

private void EntryWritten(object sender, EntryWrittenEventArgs e)
{
NewEntriesCount++;
}


private void btnLocate_Click(object sender, RoutedEventArgs e)
{
var selectedLog = (LogEntryViewModel)gridLog.SelectedItem;
Expand All @@ -133,12 +118,7 @@ private void btnEventLogVwr_Click(object sender, RoutedEventArgs e)

public void Dispose()
{
eventsReader?.Dispose();
}

private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
EventsReader?.Dispose();
}

private void Refresh_Click(object sender, RoutedEventArgs e)
Expand Down
36 changes: 21 additions & 15 deletions Notifier/UI/Windows/NotificationWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,15 +364,10 @@ private void btnSkip_Click(object sender, RoutedEventArgs e)

private void btnSkipProgram_Click(object sender, RoutedEventArgs e)
{
if (lstConnections.SelectedItem is null)
{
return;
}

SkipAllEntriesForPath(((CurrentConn)lstConnections.SelectedItem).Path);
SkipAllEntriesFromPath(((CurrentConn)lstConnections.SelectedItem).Path);
}

private void SkipAllEntriesForPath(string path)
private void SkipAllEntriesFromPath(string path)
{
var toRemove = lstConnections.Items.Cast<CurrentConn>()
.Where(connection => connection.Path == path)
Expand Down Expand Up @@ -479,15 +474,13 @@ private void createRule(bool doAllow)
if (success)
{
LogHelper.Info("New rule for connection successfully created!");

for (int i = ((App)Application.Current).Connections.Count - 1; i >= 0; i--)
if (!createWithAdvancedOptions)
{
var c = ((App)Application.Current).Connections[i];
if (FirewallHelper.GetMatchingRules(c.Path, c.CurrentAppPkgId, c.RawProtocol, c.TargetIP, c.TargetPort, c.SourcePort, c.CurrentService, c.CurrentLocalUserOwner, false).Any()) //FIXME: LocalPort may have multiple!)
{
LogHelper.Debug("Auto-removing a similar connection...");
((App)Application.Current).Connections.Remove(c);
}
SkipAllEntriesFromPath(activeConn.Path);
}
else
{
SkipAllEntriesFromRules();
}

if (((App)Application.Current).Connections.Count == 0)
Expand All @@ -502,6 +495,19 @@ private void createRule(bool doAllow)
}
}

private static void SkipAllEntriesFromRules()
{
for (int i = ((App)Application.Current).Connections.Count - 1; i >= 0; i--)
{
var c = ((App)Application.Current).Connections[i];
if (FirewallHelper.GetMatchingRules(c.Path, c.CurrentAppPkgId, c.RawProtocol, c.TargetIP, c.TargetPort, c.SourcePort, c.CurrentService, c.CurrentLocalUserOwner, false).Any()) //FIXME: LocalPort may have multiple!)
{
LogHelper.Debug("Auto-removing a similar connection...");
((App)Application.Current).Connections.Remove(c);
}
}
}

private bool createBlockRule(CurrentConn activeConn, string[] services, bool createWithAdvancedOptions, bool createTempRule, string ruleName)
{
bool success;
Expand Down

0 comments on commit 4d3bcce

Please sign in to comment.