Files
ucvl-zonghengjia-open-source/windows/BoundedLogSelfTest.cs
T

74 lines
3.4 KiB
C#
Raw Normal View History

using System.Text;
namespace UCVL.VPNPlus;
internal static class BoundedLogSelfTest
{
internal static bool Run()
{
var directory = Path.Combine(Path.GetTempPath(), "ucvl-bounded-log-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
const long limit = 192;
var logPath = Path.Combine(directory, "rotation.log");
var original = new string('a', 180) + "\n";
File.WriteAllText(logPath, original, new UTF8Encoding(false));
var originalLength = new FileInfo(logPath).Length;
// Reading and loading the helper must not delete or truncate an existing log.
_ = BoundedLog.ReadTail(logPath, 1, 64);
if (!File.Exists(logPath) || new FileInfo(logPath).Length != originalLength
|| File.Exists(logPath + ".1")) return false;
BoundedLog.Append(logPath, "rotation-entry\n", limit);
var backupPath = logPath + ".1";
if (!File.Exists(backupPath)
|| File.ReadAllText(backupPath, Encoding.UTF8) != original
|| new FileInfo(logPath).Length > limit) return false;
for (var i = 0; i < 40; i++)
BoundedLog.Append(logPath, $"line-{i:D2}-xxxxxxxx\n", limit);
if (new FileInfo(logPath).Length > limit
|| !File.Exists(backupPath)
|| new FileInfo(backupPath).Length > limit
|| File.Exists(logPath + ".2")) return false;
var legacyPath = Path.Combine(directory, "legacy-unbounded.log");
File.WriteAllText(legacyPath, new string('l', 2048), new UTF8Encoding(false));
if (new FileInfo(legacyPath).Length != 2048 || File.Exists(legacyPath + ".1")) return false;
BoundedLog.Append(legacyPath, "new\n", limit);
if (new FileInfo(legacyPath).Length > limit
|| new FileInfo(legacyPath + ".1").Length > limit) return false;
var tailPath = Path.Combine(directory, "damaged-tail.log");
var prefix = Encoding.UTF8.GetBytes("PREFIX-MUST-NOT-BE-READ\n" + new string('p', 4096) + "\n");
var damagedTail = new List<byte>(prefix);
damagedTail.AddRange([0x00, 0xC3, 0x28, (byte)'\n']);
damagedTail.AddRange(Encoding.UTF8.GetBytes("tail-one\ntail-two\ntail-three\n"));
File.WriteAllBytes(tailPath, damagedTail.ToArray());
var result = BoundedLog.ReadTail(tailPath, 3, 128);
if (result.BytesRead > 128
|| result.Text.Contains("PREFIX-MUST-NOT-BE-READ", StringComparison.Ordinal)
|| result.Text.Contains('\0')
|| !result.Text.Contains("tail-one", StringComparison.Ordinal)
|| !result.Text.Contains("tail-two", StringComparison.Ordinal)
|| !result.Text.Contains("tail-three", StringComparison.Ordinal)) return false;
var message = ProxyProbe.BuildFailureLog(new IOException("secret-target.example:443"));
return message.Contains(nameof(IOException), StringComparison.Ordinal)
&& !message.Contains("secret-target", StringComparison.OrdinalIgnoreCase)
&& !message.Contains(":443", StringComparison.Ordinal);
}
catch
{
return false;
}
finally
{
try { Directory.Delete(directory, recursive: true); } catch { }
}
}
}