Skip to content

Commit 3223c6b

Browse files
committed
Truncate, don't delete files over threshold to keep permissions
1 parent 9c51e1c commit 3223c6b

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

IPBanCore/Core/Utility/LogFileScanner.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -259,17 +259,17 @@ public void Update()
259259
Logger.Trace("Watched file {0} length has not changed", file.FileName);
260260
}
261261

262-
// if a max file size is specified and the file is over the max size, delete the file
262+
// if a max file size is specified and the file is over the max size, truncate the file
263263
if (maxFileSize > 0 && len > maxFileSize)
264264
{
265265
try
266266
{
267-
Logger.Warn("Deleting log file over max size: {0}", file.FileName);
268-
File.Delete(file.FileName);
267+
Logger.Warn("Truncating log file over max size: {0}", file.FileName);
268+
using var _ = new FileStream(file.FileName, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
269269
}
270270
catch
271271
{
272-
// someone else might have it open, in which case we have no chance to delete
272+
// someone else might have it open, in which case we can try again later
273273
}
274274
}
275275
}

IPBanTests/IPBanLogFileParserTests.cs

+22
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,28 @@ public void TestNormalizeGlob()
284284
ClassicAssert.Throws<ArgumentException>(() => LogFileScanner.NormalizeGlob("\\", out _, out _));
285285
}
286286

287+
/// <summary>
288+
/// Ensure files are truncated to 0 bytes instead of deleted
289+
/// </summary>
290+
[Test]
291+
public void TestTruncateFile()
292+
{
293+
var tempFile = Path.GetTempFileName();
294+
try
295+
{
296+
using LogFileScanner scanner = new(tempFile, 4, 0);
297+
scanner.Update();
298+
File.AppendAllText(tempFile, "12345");
299+
scanner.Update();
300+
var bytes = File.ReadAllBytes(tempFile);
301+
ClassicAssert.AreEqual(0, bytes.Length);
302+
}
303+
finally
304+
{
305+
File.Delete(tempFile);
306+
}
307+
}
308+
287309
private LogFileScanner SetupLogFileScanner(string failureRegex = "",
288310
string failureRegexTimestampFormat = null,
289311
string successRegex = null,

0 commit comments

Comments
 (0)