From db00267ef401c5768f3427cc0a993602cb2be6f8 Mon Sep 17 00:00:00 2001 From: Alex Barney Date: Fri, 5 Oct 2018 12:23:18 -0500 Subject: [PATCH] Dispose SharedStreamSource. Temp fix for switchfs reading without title keys --- LibHac/Nca.cs | 11 +++++------ LibHac/Streams/SharedStreamSource.cs | 19 ++++++++++++++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/LibHac/Nca.cs b/LibHac/Nca.cs index a42d8b9f..213c1bc2 100644 --- a/LibHac/Nca.cs +++ b/LibHac/Nca.cs @@ -16,7 +16,6 @@ namespace LibHac public byte[][] DecryptedKeys { get; } = Util.CreateJaggedArray(4, 0x10); public byte[] TitleKey { get; } public byte[] TitleKeyDec { get; } = new byte[0x10]; - private Stream Stream { get; } private SharedStreamSource StreamSource { get; } private bool KeepOpen { get; } private Nca BaseNca { get; set; } @@ -27,8 +26,7 @@ namespace LibHac { stream.Position = 0; KeepOpen = keepOpen; - Stream = stream; - StreamSource = new SharedStreamSource(stream); + StreamSource = new SharedStreamSource(stream, keepOpen); DecryptHeader(keyset, stream); CryptoType = Math.Max(Header.CryptoType, Header.CryptoType2); @@ -50,7 +48,8 @@ namespace LibHac } else { - throw new MissingKeyException("A required key is missing.", $"{Header.RightsId.ToHexString()}", KeyType.Title); + // todo enable key check when opening a section + // throw new MissingKeyException("A required key is missing.", $"{Header.RightsId.ToHexString()}", KeyType.Title); } } @@ -121,7 +120,7 @@ namespace LibHac Stream rawStream = OpenRawSection(index); NcaSection sect = Sections[index]; - if (raw) return rawStream; + if (raw || rawStream == null) return rawStream; switch (sect.Header.Type) { @@ -393,7 +392,7 @@ namespace LibHac { if (!KeepOpen) { - Stream?.Dispose(); + StreamSource?.Dispose(); } } } diff --git a/LibHac/Streams/SharedStreamSource.cs b/LibHac/Streams/SharedStreamSource.cs index 20301524..471669e6 100644 --- a/LibHac/Streams/SharedStreamSource.cs +++ b/LibHac/Streams/SharedStreamSource.cs @@ -1,15 +1,20 @@ -using System.IO; +using System; +using System.IO; namespace LibHac.Streams { - public class SharedStreamSource + public class SharedStreamSource : IDisposable { private Stream BaseStream { get; } private object Locker { get; } = new object(); + private bool KeepOpen { get; } - public SharedStreamSource(Stream baseStream) + public SharedStreamSource(Stream baseStream) : this(baseStream, true) { } + + public SharedStreamSource(Stream baseStream, bool keepOpen) { BaseStream = baseStream; + KeepOpen = keepOpen; } public SharedStream CreateStream() @@ -59,5 +64,13 @@ namespace LibHac.Streams public bool CanSeek => BaseStream.CanSeek; public bool CanWrite => BaseStream.CanWrite; public long Length => BaseStream.Length; + + public void Dispose() + { + if (KeepOpen) + { + BaseStream?.Dispose(); + } + } } }