From 12850182ff8a0e6cf26e045057a3d60b3ccd5b0b Mon Sep 17 00:00:00 2001 From: Wizou <11647984+wiz0u@users.noreply.github.com> Date: Wed, 26 Jan 2022 11:08:33 +0100 Subject: [PATCH] fix #25: possible NullReferenceException with Document.LargestThumbSize fix undisposed FileStream on broken session file. --- src/Session.cs | 15 ++++++++------- src/TL.Helpers.cs | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Session.cs b/src/Session.cs index d6736f5..abba80f 100644 --- a/src/Session.cs +++ b/src/Session.cs @@ -47,13 +47,13 @@ namespace WTelegram { var header = new byte[8]; var fileStream = new FileStream(pathname, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1); // no buffering - if (fileStream.Read(header, 0, 8) == 8) + try { - try + if (fileStream.Read(header, 0, 8) == 8) { var position = BinaryPrimitives.ReadInt32LittleEndian(header); var length = BinaryPrimitives.ReadInt32LittleEndian(header.AsSpan(4)); - if (position < 0 || length < 0 || position >= 65536 || length >= 32768){ position = 0; length = (int)fileStream.Length; } + if (position < 0 || length < 0 || position >= 65536 || length >= 32768) { position = 0; length = (int)fileStream.Length; } var input = new byte[length]; fileStream.Position = position; if (fileStream.Read(input, 0, length) != length) @@ -65,10 +65,11 @@ namespace WTelegram Helpers.Log(2, "Loaded previous session"); return session; } - catch (Exception ex) - { - throw new ApplicationException($"Exception while reading session file: {ex.Message}\nDelete the file to start a new session", ex); - } + } + catch (Exception ex) + { + fileStream.Dispose(); + throw new ApplicationException($"Exception while reading session file: {ex.Message}\nDelete the file to start a new session", ex); } return new Session { _fileStream = fileStream, _nextPosition = 8, _rgbKey = rgbKey }; } diff --git a/src/TL.Helpers.cs b/src/TL.Helpers.cs index c74cee4..c890f6c 100644 --- a/src/TL.Helpers.cs +++ b/src/TL.Helpers.cs @@ -357,7 +357,7 @@ namespace TL public override long ID => id; protected override InputDocument ToInputDocument() => new() { id = id, access_hash = access_hash, file_reference = file_reference }; public InputDocumentFileLocation ToFileLocation(PhotoSizeBase thumbSize = null) => new() { id = id, access_hash = access_hash, file_reference = file_reference, thumb_size = thumbSize?.Type }; - public PhotoSizeBase LargestThumbSize => thumbs.Aggregate((agg, next) => (long)next.Width * next.Height > (long)agg.Width * agg.Height ? next : agg); + public PhotoSizeBase LargestThumbSize => thumbs?.Aggregate((agg, next) => (long)next.Width * next.Height > (long)agg.Width * agg.Height ? next : agg); } partial class SendMessageAction