Skip to content
Merged
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
11 changes: 11 additions & 0 deletions src/changelog/3.5.0/323-deprecate-twoargaction.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="changed">
<issue id="323" link="https://github.com/apache/logging-log4net/pull/323"/>
<description format="asciidoc">Deprecate `log4net.Util.TwoArgAction`. It existed for the callback
the logical context stack used to register itself, which now holds its owning
`LogicalThreadContextStacks` instead, so nothing in log4net uses the delegate. It will be removed
in version 4 (implemented by @FreeAndNil)</description>
</entry>
13 changes: 13 additions & 0 deletions src/changelog/3.5.0/323-logging-event-fix-cache.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="323" link="https://github.com/apache/logging-log4net/pull/323"/>
<description format="asciidoc">Stop a repeated `LoggingEvent.Fix` from reopening the value cache of an
already fixed event. The cache was unlocked before the fields still to fix were determined, so a
redundant call reopened it even when there was nothing to do, and another thread reading a field
the event never captured stored its own thread name, identity or location in it. It is now
unlocked only while fields are actually being fixed (audit da18b6fd-f039, fixed by
@FreeAndNil)</description>
</entry>
12 changes: 12 additions & 0 deletions src/changelog/3.5.0/323-logical-stack-dispose.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="323" link="https://github.com/apache/logging-log4net/pull/323"/>
<description format="asciidoc">Stop a disposed `LogicalThreadContext.Stacks` frame from bringing removed
frames back. Disposing the object returned by `Push` rebuilt the stack from the copy taken at push
time, so a frame disposed after `Clear`, or after the stack had been popped below its depth,
reinstated the earlier frames in the current flow. Disposing now trims the stack registered in the
flow and never grows it (audit da18b6fd-f044, fixed by @FreeAndNil)</description>
</entry>
72 changes: 72 additions & 0 deletions src/log4net.Tests/Context/LogicalThreadContextTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,78 @@ private static async Task<string> SomeWorkStack(string stackName)
return stringAppender.GetString();
}

/// <summary>
/// A frame disposed after <see cref="LogicalThreadContextStack.Clear"/> must not bring the
/// cleared frames back.
/// </summary>
[Test]
public void DisposingAFrameAfterClearKeepsTheStackEmpty()
{
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val1");
IDisposable inner = LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val2");
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Clear();

inner.Dispose();

Assert.That(LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count, Is.EqualTo(0));
}

/// <summary>
/// A frame disposed after the stack was popped below its depth must not bring the popped frames back.
/// </summary>
[Test]
public void DisposingAFrameAfterPoppingBelowItKeepsTheStackEmpty()
{
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val1");
IDisposable inner = LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val2");
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Pop();
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Pop();

inner.Dispose();

Assert.That(LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count, Is.EqualTo(0));
}

/// <summary>
/// Disposing a frame trims the stack to the depth of that frame, including frames pushed after it.
/// </summary>
[Test]
public void DisposingAFrameTrimsTheStackToItsDepth()
{
using (LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val1"))
{
IDisposable inner = LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val2");
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val3");

inner.Dispose();

Assert.That(LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count, Is.EqualTo(1));
}

Assert.That(LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count, Is.EqualTo(0));
}

/// <summary>
/// A frame disposed in another flow trims that flow only, and does not resurrect its own frames.
/// </summary>
[Test]
public async Task DisposingAFrameInAnotherFlowDoesNotResurrectIt()
{
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val1");
IDisposable inner = LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push("val2");

int countInOtherFlow = await Task.Run(() =>
{
LogicalThreadContext.Stacks[TestUtils.PropertyKey].Clear();
inner.Dispose();
return LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count;
}).ConfigureAwait(false);

Assert.That(countInOtherFlow, Is.EqualTo(0));
Assert.That(LogicalThreadContext.Stacks[TestUtils.PropertyKey].Count, Is.EqualTo(2),
"the other flow must not change this one");
}

static async Task MoreWorkStack(ILog log, string stackName)
{
using (LogicalThreadContext.Stacks[TestUtils.PropertyKey].Push(stackName))
Expand Down
41 changes: 41 additions & 0 deletions src/log4net.Tests/Core/FixingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

using System;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;

using log4net.Core;
using log4net.Util;
Expand Down Expand Up @@ -210,6 +212,45 @@ public void UserNameIsCapturedWhenItIsFixed()
Assert.That(loggingEvent.UserName, Is.Not.EqualTo(SystemInfo.NotAvailableText));
}

/// <summary>
/// A redundant Fix must not reopen the cache: a thread reading a field the event never captured
/// would otherwise store its own principal in it. 500000 calls, the defect hit within 63000.
/// </summary>
[Test]
public void ARedundantFixDoesNotLetAnotherThreadCacheItsIdentity()
{
LoggingEvent loggingEvent = CreateEvent();
// Partial leaves Identity out, so it stays null unless the cache reopens.
loggingEvent.Fix = FixFlags.Partial;

bool stop = false;
long spins = 0;
TaskCompletionSource<bool> running = new();
Thread reader = new(() =>
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Intruder"), null);
running.TrySetResult(true);
while (!Volatile.Read(ref stop) && loggingEvent.Identity is null)
{
Interlocked.Increment(ref spins);
Comment thread
FreeAndNil marked this conversation as resolved.
Resolved
}
})
{ IsBackground = true };
reader.Start();
Assert.That(running.Task.Wait(TimeSpan.FromSeconds(10)), Is.True);

for (int i = 0; i < 500_000; i++)
{
loggingEvent.Fix = FixFlags.Partial;
}
Volatile.Write(ref stop, true);
Assert.That(reader.Join(TimeSpan.FromSeconds(10)), Is.True);

// A reader that never got scheduled would pass the identity assertion for the wrong reason.
Assert.That(Interlocked.Read(ref spins), Is.GreaterThan(0));
Assert.That(loggingEvent.Identity, Is.Null);
}

/// <summary>
/// Creates an event in the test repository.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions src/log4net/Appender/AspNetTraceAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ namespace log4net.Appender;
/// <see cref="TraceContext.Warn(string)"/> method depending on the level of the logging event.
/// The event's logger name is the default value for the category parameter of the Write/Warn method.
/// </para>
/// <para>
/// Writes to the request current on the appending thread, so it must not be wrapped in a buffering appender.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
Expand Down
10 changes: 4 additions & 6 deletions src/log4net/Core/LoggingEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1137,16 +1137,14 @@ public LoggingEventData GetLoggingEventData(FixFlags fixFlags)
/// </remarks>
protected virtual void FixVolatileData(FixFlags flags)
{
// Unlock the cache so that new values can be stored
// This may not be ideal if we are no longer in the correct context
// and someone calls fix.
_cacheUpdatable = true;

// determine the flags that we are actually fixing
FixFlags updateFlags = (flags ^ _fixFlags) & flags;

if (updateFlags > 0)
{
// Unlocked only while there is something to fix, so a redundant call cannot reopen the cache.
_cacheUpdatable = true;

if ((updateFlags & FixFlags.Message) != 0)
{
// Force the message to be rendered
Expand Down Expand Up @@ -1448,7 +1446,7 @@ public PropertiesDictionary GetProperties()
/// This is a separate flag to fixFlags as it allows incremental fixing and simpler
/// changes in the caching strategy.
/// </remarks>
private bool _cacheUpdatable = true;
private volatile bool _cacheUpdatable = true;

/// <summary>
/// The key into the Properties map for the host name value.
Expand Down
52 changes: 29 additions & 23 deletions src/log4net/Util/LogicalThreadContextStack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
namespace log4net.Util;

/// <summary>
/// Delegate type used for LogicalThreadContextStack's callbacks.
/// Delegate type for an action taking two arguments.
/// </summary>
[Obsolete("No longer used by log4net and removed in version 4.")]
public delegate void TwoArgAction<T1, T2>(T1 t1, T2 t2);

/// <summary>
Expand All @@ -47,10 +48,9 @@ public sealed class LogicalThreadContextStack : IFixingRequired
private readonly string _propertyKey;

/// <summary>
/// The callback used to let the <see cref="LogicalThreadContextStacks"/> register a
/// new instance of a <see cref="LogicalThreadContextStack"/>.
/// The owning stacks.
/// </summary>
private readonly TwoArgAction<string, LogicalThreadContextStack> _registerNew;
private readonly LogicalThreadContextStacks _owner;

/// <summary>
/// Internal constructor
Expand All @@ -60,10 +60,10 @@ public sealed class LogicalThreadContextStack : IFixingRequired
/// Initializes a new instance of the <see cref="LogicalThreadContextStack" /> class.
/// </para>
/// </remarks>
internal LogicalThreadContextStack(string propertyKey, TwoArgAction<string, LogicalThreadContextStack> registerNew)
internal LogicalThreadContextStack(string propertyKey, LogicalThreadContextStacks owner)
{
_propertyKey = propertyKey;
_registerNew = registerNew;
_owner = owner;
}

/// <summary>
Expand Down Expand Up @@ -93,7 +93,7 @@ internal LogicalThreadContextStack(string propertyKey, TwoArgAction<string, Logi
/// syntax.
/// </para>
/// </remarks>
public void Clear() => _registerNew(_propertyKey, new LogicalThreadContextStack(_propertyKey, _registerNew));
public void Clear() => _owner.RegisterNew(_propertyKey, new(_propertyKey, _owner));

/// <summary>
/// Removes the top context from this stack.
Expand All @@ -115,8 +115,8 @@ internal LogicalThreadContextStack(string propertyKey, TwoArgAction<string, Logi
{
result = stack.Pop().Message;
}
LogicalThreadContextStack ltcs = new(_propertyKey, _registerNew) { _stack = stack };
_registerNew(_propertyKey, ltcs);
LogicalThreadContextStack ltcs = new(_propertyKey, _owner) { _stack = stack };
_owner.RegisterNew(_propertyKey, ltcs);
return result;
}

Expand Down Expand Up @@ -147,10 +147,10 @@ public IDisposable Push(string? message)
{
// do modifications on a copy
Stack<StackFrame> stack = new(new Stack<StackFrame>(_stack));
stack.Push(new StackFrame(message, (stack.Count > 0) ? stack.Peek() : null));
stack.Push(new(message, (stack.Count > 0) ? stack.Peek() : null));

LogicalThreadContextStack contextStack = new(_propertyKey, _registerNew) { _stack = stack };
_registerNew(_propertyKey, contextStack);
LogicalThreadContextStack contextStack = new(_propertyKey, _owner) { _stack = stack };
_owner.RegisterNew(_propertyKey, contextStack);
return new AutoPopStackFrame(contextStack, stack.Count - 1);
}

Expand Down Expand Up @@ -313,19 +313,25 @@ internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack,
/// </remarks>
public void Dispose()
{
if (_frameDepth >= 0)
if (_frameDepth < 0)
{
Stack<StackFrame> local = new(new Stack<StackFrame>(_logicalThreadContextStack._stack));
while (local.Count > _frameDepth)
{
local.Pop();
}
LogicalThreadContextStack ltcs = new(_logicalThreadContextStack._propertyKey, _logicalThreadContextStack._registerNew)
{
_stack = local
};
_logicalThreadContextStack._registerNew(_logicalThreadContextStack._propertyKey, ltcs);
return;
}
// Trim the stack registered in this flow, never restore the copy captured by Push.
string propertyKey = _logicalThreadContextStack._propertyKey;
LogicalThreadContextStacks owner = _logicalThreadContextStack._owner;
if (owner.GetCurrent(propertyKey) is not LogicalThreadContextStack current
|| current._stack.Count <= _frameDepth)
{
return;
}

Stack<StackFrame> local = new(new Stack<StackFrame>(current._stack));
while (local.Count > _frameDepth)
{
local.Pop();
}
owner.RegisterNew(propertyKey, new(propertyKey, owner) { _stack = local });
}
}
}
15 changes: 12 additions & 3 deletions src/log4net/Util/LogicalThreadContextStacks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public LogicalThreadContextStack this[string key]
if (propertyValue is null)
{
// Stack does not exist, create
stack = new(key, RegisterNew);
stack = new(key, this);
_properties[key] = stack;
}
else
Expand All @@ -84,17 +84,26 @@ public LogicalThreadContextStack this[string key]

LogLog.Error(_declaringType, $"ThreadContextStacks: Request for stack named [{key}] failed because a property with the same name exists which is a [{propertyValue.GetType().Name}] with value [{propertyValueString}]");

stack = new(key, RegisterNew);
stack = new(key, this);
}
}

return stack;
}
}

private void RegisterNew(string stackName, LogicalThreadContextStack stack)
/// <summary>
/// Registers <paramref name="stack"/> under <paramref name="stackName"/> in the current flow.
/// </summary>
internal void RegisterNew(string stackName, LogicalThreadContextStack stack)
=> _properties[stackName] = stack;

/// <summary>
/// Gets the stack currently registered under <paramref name="stackName"/> in this flow.
/// </summary>
internal LogicalThreadContextStack? GetCurrent(string stackName)
=> _properties[stackName] as LogicalThreadContextStack;

/// <summary>
/// The fully qualified type of the ThreadContextStacks class.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ internal sealed class PropertyPatternConverter : PatternConverter
/// </remarks>
public override void Convert(TextWriter writer, object? state)
{
// Context values may hold user-supplied data, so building a path from %property is the
// operator's choice: https://logging.apache.org/security/faq.html#path-traversal
CompositeProperties compositeProperties = new();

if (LogicalThreadContext.Properties.GetProperties(false) is PropertiesDictionary logicalThreadProperties)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ log4net ships with the following appenders
|AspNetTraceAppender
|Writes logging events to the ASP trace context. These can then be rendered at the end of the ASP page or on the ASP trace page.

Writes to the request current on the appending thread, so it must not be wrapped in a buffering appender.

Comment thread
FreeAndNil marked this conversation as resolved.
Resolved
|xref:manual/configuration/appenders/bufferingforwardingappender.adoc[]
|Buffers events and then forwards them to attached appenders.

Expand Down
2 changes: 2 additions & 0 deletions src/site/antora/modules/ROOT/pages/manual/faq.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ To enable this, set type="log4net.Util.PatternString" on the string property in

For example, to include the current process ID in a FileAppender filename, use the %processid pattern in the File property.

Note that %property expands context values, which may carry user-supplied data, so a path built from one is only as trustworthy as that value, see the https://logging.apache.org/security/faq.html#path-traversal[security FAQ on path traversal].

[source,xml]
----
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
Expand Down
Loading