Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Added support for password-protected 7z archives.
nzbdav-dev4e5ba9e7af58
diff --git a/backend/Database/Models/DavMultipartFile.cs b/backend/Database/Models/DavMultipartFile.csindex ee90ad31..07d9ec0a 100644--- a/backend/Database/Models/DavMultipartFile.cs+++ b/backend/Database/Models/DavMultipartFile.cs@@ -12,6 +12,7 @@ public class DavMultipartFilepublic class Meta{+ public AesParams? AesParams { get; set; }public FilePart[] FileParts { get; set; } = [];}diff --git a/backend/Extensions/SevenZipArchiveEntryExtensions.cs b/backend/Extensions/SevenZipArchiveEntryExtensions.csindex ca343758..2f41e2bc 100644--- a/backend/Extensions/SevenZipArchiveEntryExtensions.cs+++ b/backend/Extensions/SevenZipArchiveEntryExtensions.cs@@ -14,21 +14,58 @@ public static class SevenZipArchiveEntryExtensions}catch (NotImplementedException){- var coders = (IEnumerable?)entry- ?.GetReflectionProperty("FilePart")- ?.GetReflectionProperty("Folder")- ?.GetReflectionField("_coders");- var compressionMethodId = (ulong?)FirstOrDefault(coders)- ?.GetReflectionField("_methodId")- ?.GetReflectionField("_id");- return compressionMethodId == 0- ? CompressionType.None+ var coders = entry?.GetCoders();+ var compressionMethodId = GetCoderMethodId(coders?.FirstOrDefault());+ return compressionMethodId == 0 ? CompressionType.None+ : compressionMethodId == 116459265 ? CompressionType.None: CompressionType.Unknown;}}- private static object? FirstOrDefault(IEnumerable? enumerable)+ public static byte[]? GetAesCoderInfoProps(this SevenZipArchiveEntry entry){- return enumerable?.Cast<object?>().FirstOrDefault();+ const ulong aesMethodId = 0x06F10701;+ return (byte[]?)entry+ ?.GetCoders()+ ?.FirstOrDefault(x => GetCoderMethodId(x) == aesMethodId)+ ?.GetReflectionField("_props");+ }++ public static long GetFolderStartByteOffset(this SevenZipArchiveEntry entry)+ {+ var filePart = entry?.GetReflectionProperty("FilePart");+ var folder = filePart?.GetReflectionProperty("Folder");+ var database = filePart?.GetReflectionField("_database");+ var folderFirstPackStreamId = (int)folder?.GetReflectionField("_firstPackStreamId")!;+ var databaseDataStartPosition = (long)database?.GetReflectionField("_dataStartPosition")!;+ var databasePackStreamStartPositions = (List<long>)database?.GetReflectionField("_packStreamStartPositions")!;+ return databaseDataStartPosition + databasePackStreamStartPositions[folderFirstPackStreamId];+ }++ public static long? GetPackedSize(this SevenZipArchiveEntry entry)+ {+ throw new NotImplementedException();+ }++ private static IEnumerable<object?>? GetCoders(this SevenZipArchiveEntry entry)+ {+ var coders = (IEnumerable?)entry+ ?.GetFolder()+ ?.GetReflectionField("_coders");+ return coders?.Cast<object?>();+ }++ private static object? GetFolder(this SevenZipArchiveEntry entry)+ {+ return entry+ ?.GetReflectionProperty("FilePart")+ ?.GetReflectionProperty("Folder");+ }++ private static ulong? GetCoderMethodId(object? coder)+ {+ return (ulong?)coder+ ?.GetReflectionField("_methodId")+ ?.GetReflectionField("_id");}}\ No newline at end of filediff --git a/backend/Extensions/SevenZipArchiveExtensions.cs b/backend/Extensions/SevenZipArchiveExtensions.csindex 44cd7bca..6ed25d8d 100644--- a/backend/Extensions/SevenZipArchiveExtensions.cs+++ b/backend/Extensions/SevenZipArchiveExtensions.cs@@ -11,4 +11,11 @@ public static class SevenZipArchiveExtensionsvar packStreamStartPositions = (List<long>?)database?.GetReflectionField("_packStreamStartPositions");return dataStartPosition!.Value + packStreamStartPositions![index];}++ public static long GetPackSize(this SevenZipArchive archive, int index)+ {+ var database = archive?.GetReflectionField("_database");+ var packSizes = (List<long>?)database?.GetReflectionField("_packSizes");+ return packSizes![index];+ }}\ No newline at end of filediff --git a/backend/Models/AesParams.cs b/backend/Models/AesParams.csnew file mode 100644index 00000000..289fb203--- /dev/null+++ b/backend/Models/AesParams.cs@@ -0,0 +1,97 @@+using System.Security.Cryptography;+using System.Text;++namespace NzbWebDAV.Models;++public class AesParams()+{+ public long DecodedSize { get; set; } = 0;+ public byte[] Iv { get; set; } = [];+ public byte[] Key { get; set; } = [];++ public static AesParams? FromCoderInfo(byte[]? coderInfo, string? password, long decodedSize)+ {+ if (coderInfo == null || password == null) return null;+ return new AesParams(coderInfo, password, decodedSize);+ }++ private AesParams(byte[] info, string password, long decodedSize) : this()+ {+ Init(info, out var numCyclesPower, out var salt, out var iv);+ Key = InitKey(numCyclesPower, salt, Encoding.Unicode.GetBytes(password));+ DecodedSize = decodedSize;+ Iv = iv;+ }++ private static void Init(byte[] info, out int numCyclesPower, out byte[] salt, out byte[] iv)+ {+ var bt = info[0];+ numCyclesPower = bt & 0x3F;++ if ((bt & 0xC0) == 0)+ {+ salt = [];+ iv = [];+ return;+ }++ var saltSize = (bt >> 7) & 1;+ var ivSize = (bt >> 6) & 1;+ if (info.Length == 1)+ throw new InvalidOperationException();++ var bt2 = info[1];+ saltSize += (bt2 >> 4);+ ivSize += (bt2 & 15);+ if (info.Length < 2 + saltSize + ivSize)+ throw new InvalidOperationException();++ salt = new byte[saltSize];+ for (var i = 0; i < saltSize; i++)+ salt[i] = info[i + 2];++ iv = new byte[16];+ for (var i = 0; i < ivSize; i++)+ iv[i] = info[i + saltSize + 2];++ if (numCyclesPower > 24)+ throw new NotSupportedException();+ }++ private byte[] InitKey(int mNumCyclesPower, byte[] salt, byte[] pass)+ {+ if (mNumCyclesPower == 0x3F)+ {+ var key = new byte[32];+ int pos;+ for (pos = 0; pos < salt.Length; pos++)+ key[pos] = salt[pos];++ for (var i = 0; i < pass.Length && pos < 32; i++)+ key[pos++] = pass[i];++ return key;+ }++ using var sha = SHA256.Create();+ var counter = new byte[8];+ var numRounds = 1L << mNumCyclesPower;+ for (long round = 0; round < numRounds; round++)+ {+ sha.TransformBlock(salt, 0, salt.Length, null, 0);+ sha.TransformBlock(pass, 0, pass.Length, null, 0);+ sha.TransformBlock(counter, 0, 8, null, 0);++ for (var i = 0; i < 8; i++)+ {+ if (++counter[i] != 0)+ break;+ }+ }++ sha.TransformFinalBlock(counter, 0, 0);+ var shaKey = sha.Hash;+ if (shaKey == null) throw new InvalidOperationException("Initialized AES with null key");+ return shaKey;+ }+}\ No newline at end of filediff --git a/backend/Queue/FileAggregators/SevenZipAggregator.cs b/backend/Queue/FileAggregators/SevenZipAggregator.csindex 35c02b9e..38623a78 100644--- a/backend/Queue/FileAggregators/SevenZipAggregator.cs+++ b/backend/Queue/FileAggregators/SevenZipAggregator.cs@@ -29,7 +29,7 @@ public class SevenZipAggregator(foreach (var sevenZipFile in sevenZipFiles){var pathWithinArchive = sevenZipFile.PathWithinArchive;- var sevenZipParts = sevenZipFile.Parts;+ var davMultipartFileMeta = sevenZipFile.DavMultipartFileMeta;var parentDirectory = EnsureExtractPath(pathWithinArchive);var name = Path.GetFileName(pathWithinArchive);@@ -42,7 +42,8 @@ public class SevenZipAggregator(id: Guid.NewGuid(),parent: parentDirectory,name: name,- fileSize: sevenZipParts.Sum(x => x.FilePartByteRange.Count),+ fileSize: davMultipartFileMeta.AesParams?.DecodedSize+ ?? davMultipartFileMeta.FileParts.Sum(x => x.FilePartByteRange.Count),type: DavItem.ItemType.MultipartFile,releaseDate: sevenZipFile.ReleaseDate,lastHealthCheck: checkedFullHealth ? DateTimeOffset.UtcNow : null@@ -51,10 +52,7 @@ public class SevenZipAggregator(var davMultipartFile = new DavMultipartFile(){Id = davItem.Id,- Metadata = new DavMultipartFile.Meta()- {- FileParts = sevenZipParts.ToArray()- }+ Metadata = davMultipartFileMeta};dbClient.Ctx.Items.Add(davItem);diff --git a/backend/Queue/FileProcessors/SevenZipProcessor.cs b/backend/Queue/FileProcessors/SevenZipProcessor.csindex 8ec5ec09..2c762667 100644--- a/backend/Queue/FileProcessors/SevenZipProcessor.cs+++ b/backend/Queue/FileProcessors/SevenZipProcessor.cs@@ -15,17 +15,20 @@ public class SevenZipProcessor : BaseProcessor{private readonly List<GetFileInfosStep.FileInfo> _fileInfos;private readonly UsenetStreamingClient _client;+ private readonly string? _archivePassword;private readonly CancellationToken _ct;public SevenZipProcessor(List<GetFileInfosStep.FileInfo> fileInfos,UsenetStreamingClient client,+ string? archivePassword,CancellationToken ct){_fileInfos = fileInfos;_client = client;+ _archivePassword = archivePassword;_ct = ct;}@@ -33,19 +36,26 @@ public class SevenZipProcessor : BaseProcessor{var multipartFile = await GetMultipartFile();await using var stream = new MultipartFileStream(multipartFile, _client);- var sevenZipEntries = await SevenZipUtil.GetSevenZipEntriesAsync(stream, _ct);+ var sevenZipEntries = await SevenZipUtil.GetSevenZipEntriesAsync(stream, _archivePassword, _ct);if (sevenZipEntries.Any(x => x.CompressionType != CompressionType.None)){const string message = "Only uncompressed 7z files are supported.";throw new Unsupported7zCompressionMethodException(message);}+ if (sevenZipEntries.Any(x => x.IsEncrypted && x.IsSolid))+ {+ // TODO: Add support for solid 7z archives+ const string message = "Password-protected 7z archives cannot be solid.";+ throw new NonRetryableDownloadException(message);+ }+return new Result(){SevenZipFiles = sevenZipEntries.Select(x => new SevenZipFile(){PathWithinArchive = x.PathWithinArchive,- Parts = GetSevenZipParts(x, multipartFile),+ DavMultipartFileMeta = GetDavMultipartFileMeta(x, multipartFile),ReleaseDate = _fileInfos.First().ReleaseDate,}).ToList(),};@@ -78,7 +88,7 @@ public class SevenZipProcessor : BaseProcessorreturn string.IsNullOrEmpty(match.Groups[2].Value) ? -1 : int.Parse(match.Groups[2].Value);}- private List<DavMultipartFile.FilePart> GetSevenZipParts+ private DavMultipartFile.Meta GetDavMultipartFileMeta(SevenZipUtil.SevenZipEntry sevenZipEntry,MultipartFile multipartFile@@ -100,7 +110,7 @@ public class SevenZipProcessor : BaseProcessorvar endIndexExclusive = endIndexInclusive + 1;var indexCount = endIndexExclusive - startIndexInclusive;- return Enumerable+ var fileParts = Enumerable.Range(startIndexInclusive, indexCount).Select(index =>{@@ -119,7 +129,13 @@ public class SevenZipProcessor : BaseProcessorFilePartByteRange = LongRange.FromStartAndSize(partStartInclusive, partByteCount),};})- .ToList();+ .ToArray();++ return new DavMultipartFile.Meta()+ {+ AesParams = sevenZipEntry.AesParams,+ FileParts = fileParts,+ };}public new class Result : BaseProcessor.Result@@ -130,7 +146,7 @@ public class SevenZipProcessor : BaseProcessorpublic class SevenZipFile{public required string PathWithinArchive { get; init; }- public required List<DavMultipartFile.FilePart> Parts { get; init; }+ public required DavMultipartFile.Meta DavMultipartFileMeta { get; init; }public required DateTimeOffset ReleaseDate { get; init; }}}\ No newline at end of filediff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.csindex 966bfa49..783addb7 100644--- a/backend/Queue/QueueItemProcessor.cs+++ b/backend/Queue/QueueItemProcessor.cs@@ -109,6 +109,7 @@ public class QueueItemProcessor(var documentBytes = Encoding.UTF8.GetBytes(queueItem.NzbContents);using var stream = new MemoryStream(documentBytes);var nzb = await NzbDocument.LoadAsync(stream);+ var archivePassword = nzb.MetaData.GetValueOrDefault("password")?.FirstOrDefault();var nzbFiles = nzb.Files.Where(x => x.Segments.Count > 0).ToList();// part 1 -- get name and size of each nzb file@@ -123,7 +124,7 @@ public class QueueItemProcessor(segments, par2FileDescriptors);// part 2 -- perform file processing- var fileProcessors = GetFileProcessors(fileInfos).ToList();+ var fileProcessors = GetFileProcessors(fileInfos, archivePassword).ToList();var part2Progress = progress.Offset(50).Scale(50, 100)@@ -171,7 +172,11 @@ public class QueueItemProcessor(});}- private IEnumerable<BaseProcessor> GetFileProcessors(List<GetFileInfosStep.FileInfo> fileInfos)+ private IEnumerable<BaseProcessor> GetFileProcessors+ (+ List<GetFileInfosStep.FileInfo> fileInfos,+ string? archivePassword+ ){var groups = fileInfos.DistinctBy(x => x.FileName)@@ -180,7 +185,7 @@ public class QueueItemProcessor(foreach (var group in groups){if (group.Key == "7z")- yield return new SevenZipProcessor(group.ToList(), usenetClient, ct);+ yield return new SevenZipProcessor(group.ToList(), usenetClient, archivePassword, ct);else if (group.Key == "rar")foreach (var fileInfo in group)diff --git a/backend/Streams/AesDecoderStream.cs b/backend/Streams/AesDecoderStream.csnew file mode 100644index 00000000..405e840e--- /dev/null+++ b/backend/Streams/AesDecoderStream.cs@@ -0,0 +1,229 @@+using System.Security.Cryptography;+using NzbWebDAV.Models;++namespace NzbWebDAV.Streams+{+ internal sealed class AesDecoderStream : Stream+ {+ private readonly Stream _mStream;+ private ICryptoTransform _mDecoder;+ private readonly byte[] _mBuffer;+ private long _mWritten;+ private readonly long _mLimit;+ private int _mOffset;+ private int _mEnding;+ private int _mUnderflow;+ private bool _isDisposed;++ // store for reinitializing on Seek+ private readonly byte[] _mKey;+ private readonly byte[] _mBaseIv;++ public AesDecoderStream(Stream input, AesParams aesParams)+ {+ _mStream = input;+ _mLimit = aesParams.DecodedSize;+ _mKey = aesParams.Key;+ _mBaseIv = aesParams.Iv;++ if (((uint)input.Length & 15) != 0)+ {+ throw new NotSupportedException("AES decoder does not support padding.");+ }++ using (var aes = Aes.Create())+ {+ aes.Mode = CipherMode.CBC;+ aes.Padding = PaddingMode.None;+ _mDecoder = aes.CreateDecryptor(_mKey, _mBaseIv);+ }++ _mBuffer = new byte[4 << 10];+ }++ protected override void Dispose(bool disposing)+ {+ try+ {+ if (_isDisposed)+ return;++ _isDisposed = true;+ if (disposing)+ {+ _mStream.Dispose();+ _mDecoder.Dispose();+ }+ }+ finally+ {+ base.Dispose(disposing);+ }+ }++ public override void Flush() => throw new NotImplementedException();++ public override long Position+ {+ get => _mWritten;+ set => Seek(value, SeekOrigin.Begin);+ }++ public override bool CanWrite => false;+ public override long Length => _mLimit;+ public override bool CanRead => true;+ public override bool CanSeek => true;++ public override int Read(byte[] buffer, int offset, int count)+ {+ return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();+ }++ public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct)+ {+ if (count == 0 || _mWritten == _mLimit)+ return 0;++ if (_mUnderflow > 0)+ return HandleUnderflow(buffer, offset, count);++ // Need at least 16 bytes+ if (_mEnding - _mOffset < 16)+ {+ Buffer.BlockCopy(_mBuffer, _mOffset, _mBuffer, 0, _mEnding - _mOffset);+ _mEnding -= _mOffset;+ _mOffset = 0;++ do+ {+ var read = await _mStream+ .ReadAsync(_mBuffer.AsMemory(_mEnding, _mBuffer.Length - _mEnding), ct)+ .ConfigureAwait(false);+ if (read == 0)+ throw new EndOfStreamException();+ _mEnding += read;+ } while (_mEnding - _mOffset < 16);+ }++ if (count > _mLimit - _mWritten)+ count = (int)(_mLimit - _mWritten);++ if (count < 16)+ return HandleUnderflow(buffer, offset, count);++ if (count > _mEnding - _mOffset)+ count = _mEnding - _mOffset;++ var processed = _mDecoder.TransformBlock(_mBuffer, _mOffset, count & ~15, buffer, offset);+ _mOffset += processed;+ _mWritten += processed;+ return processed;+ }++ public override void SetLength(long value) => throw new NotImplementedException();+ public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();++ public override long Seek(long offset, SeekOrigin origin)+ {+ if (!CanSeek)+ throw new NotSupportedException();++ long target;+ switch (origin)+ {+ case SeekOrigin.Begin:+ target = offset;+ break;+ case SeekOrigin.Current:+ target = _mWritten + offset;+ break;+ case SeekOrigin.End:+ target = _mLimit + offset;+ break;+ default:+ throw new ArgumentOutOfRangeException(nameof(origin), origin, null);+ }++ if (target < 0 || target > _mLimit)+ throw new ArgumentOutOfRangeException(nameof(offset), "Seek position outside stream limits");++ // Align to AES block size (16)+ var blockSize = 16;+ var blockIndex = target / blockSize;+ var blockOffset = target % blockSize;++ // We need previous block to get proper IV+ long cipherPos = blockIndex > 0 ? (blockIndex - 1) * blockSize : 0;++ // Seek underlying stream+ _mStream.Seek(cipherPos, SeekOrigin.Begin);++ // Read previous block as IV (or original IV for block 0)+ byte[] iv = new byte[16];+ if (blockIndex > 0)+ {+ int bytesRead = _mStream.Read(iv, 0, 16);+ if (bytesRead != 16)+ throw new EndOfStreamException("Unable to read previous block for IV");+ }+ else+ {+ Buffer.BlockCopy(_mBaseIv, 0, iv, 0, 16);+ }++ // Create a new decryptor starting at that IV+ _mDecoder.Dispose();+ using (var aes = Aes.Create())+ {+ aes.Mode = CipherMode.CBC;+ aes.Padding = PaddingMode.None;+ _mDecoder = aes.CreateDecryptor(_mKey, iv);+ }++ // Reset internal buffers+ _mOffset = 0;+ _mEnding = 0;+ _mUnderflow = 0;+ _mWritten = target - blockOffset; // position of start of current block++ // Preload and decrypt up to the block containing target+ int decrypted = 0;+ if (blockOffset > 0)+ {+ var tempCipher = new byte[blockSize];+ int bytes = _mStream.Read(tempCipher, 0, blockSize);+ if (bytes != blockSize)+ throw new EndOfStreamException();++ var tempPlain = new byte[blockSize];+ decrypted = _mDecoder.TransformBlock(tempCipher, 0, blockSize, tempPlain, 0);++ // cache the remainder into mBuffer for next reads+ Buffer.BlockCopy(tempPlain, (int)blockOffset, _mBuffer, 0, decrypted - (int)blockOffset);+ _mOffset = 0;+ _mEnding = decrypted - (int)blockOffset;+ _mWritten += blockOffset;+ }++ return target;+ }++ private int HandleUnderflow(byte[] buffer, int offset, int count)+ {+ if (_mUnderflow == 0)+ {+ var blockSize = (_mEnding - _mOffset) & ~15;+ _mUnderflow = _mDecoder.TransformBlock(_mBuffer, _mOffset, blockSize, _mBuffer, _mOffset);+ }++ if (count > _mUnderflow)+ count = _mUnderflow;++ Buffer.BlockCopy(_mBuffer, _mOffset, buffer, offset, count);+ _mWritten += count;+ _mOffset += count;+ _mUnderflow -= count;+ return count;+ }+ }+}\ No newline at end of filediff --git a/backend/Streams/SubStream.cs b/backend/Streams/SubStream.csnew file mode 100644index 00000000..4ef7daaa--- /dev/null+++ b/backend/Streams/SubStream.cs@@ -0,0 +1,124 @@+namespace NzbWebDAV.Streams;++using System;+using System.IO;++public sealed class SubStream : Stream+{+ private readonly Stream _innerStream;+ private readonly long _start;+ private readonly long _length;+ private long _position;+ private bool _disposed;++ public SubStream(Stream innerStream, long offset, long count)+ {+ if (innerStream == null)+ throw new ArgumentNullException(nameof(innerStream));+ if (!innerStream.CanSeek)+ throw new ArgumentException("Inner stream must support seeking.", nameof(innerStream));+ if (offset < 0 || count < 0)+ throw new ArgumentOutOfRangeException("Offset and count must be non-negative.");+ if (offset + count > innerStream.Length)+ throw new ArgumentException("The specified range exceeds the length of the inner stream.");++ _innerStream = innerStream;+ _start = offset;+ _length = count;+ _position = 0;+ }++ public override bool CanRead => !_disposed && _innerStream.CanRead;+ public override bool CanSeek => !_disposed && _innerStream.CanSeek;+ public override bool CanWrite => false;++ public override long Length+ {+ get+ {+ ThrowIfDisposed();+ return _length;+ }+ }++ public override long Position+ {+ get+ {+ ThrowIfDisposed();+ return _position;+ }+ set+ {+ ThrowIfDisposed();+ if (value < 0 || value > _length)+ throw new ArgumentOutOfRangeException(nameof(value));+ _position = value;+ }+ }++ public override int Read(byte[] buffer, int offset, int count)+ {+ ThrowIfDisposed();++ if (buffer == null)+ throw new ArgumentNullException(nameof(buffer));+ if (offset < 0 || count < 0 || offset + count > buffer.Length)+ throw new ArgumentOutOfRangeException();++ if (_position >= _length)+ return 0;++ long remaining = _length - _position;+ if (count > remaining)+ count = (int)remaining;++ _innerStream.Seek(_start + _position, SeekOrigin.Begin);+ int read = _innerStream.Read(buffer, offset, count);+ _position += read;+ return read;+ }++ public override long Seek(long offset, SeekOrigin origin)+ {+ ThrowIfDisposed();++ long newPos = origin switch+ {+ SeekOrigin.Begin => offset,+ SeekOrigin.Current => _position + offset,+ SeekOrigin.End => _length + offset,+ _ => throw new ArgumentException("Invalid seek origin.", nameof(origin))+ };++ if (newPos < 0 || newPos > _length)+ throw new IOException("Attempted to seek outside the bounds of the substream.");++ _position = newPos;+ return _position;+ }++ public override void Flush()+ {+ /* read-only, nothing to flush */+ }++ public override void SetLength(long value) =>+ throw new NotSupportedException("SubStream is read-only.");++ public override void Write(byte[] buffer, int offset, int count) =>+ throw new NotSupportedException("SubStream is read-only.");++ protected override void Dispose(bool disposing)+ {+ _disposed = true;+ // We do not dispose the inner stream — caller owns it.+ base.Dispose(disposing);+ }++ private void ThrowIfDisposed()+ {+ if (_disposed)+ throw new ObjectDisposedException(nameof(SubStream));+ }+}\ No newline at end of filediff --git a/backend/Utils/SevenZipUtil.cs b/backend/Utils/SevenZipUtil.csindex cd170d67..e95e7f9c 100644--- a/backend/Utils/SevenZipUtil.cs+++ b/backend/Utils/SevenZipUtil.cs@@ -4,39 +4,46 @@ using NzbWebDAV.Models;using NzbWebDAV.Streams;using SharpCompress.Archives.SevenZip;using SharpCompress.Common;+using SharpCompress.Readers;namespace NzbWebDAV.Utils;public static class SevenZipUtil{- public static async Task<List<SevenZipEntry>> GetSevenZipEntriesAsync(Stream stream, CancellationToken ct)+ public static async Task<List<SevenZipEntry>> GetSevenZipEntriesAsync+ (+ Stream stream,+ string? password,+ CancellationToken ct+ ){await using var cancellableStream = new CancellableStream(stream, ct);- return await Task.Run(() => GetSevenZipEntries(cancellableStream), ct);+ return await Task.Run(() => GetSevenZipEntries(cancellableStream, password), ct);}- public static List<SevenZipEntry> GetSevenZipEntries(Stream stream)+ public static List<SevenZipEntry> GetSevenZipEntries(Stream stream, string? password = null){- try- {- using var archive = SevenZipArchive.Open(stream);- return archive.Entries- .Where(x => !x.IsDirectory)- .Select((entry, index) => new SevenZipEntry(entry, archive, index))- .ToList();- }- catch (CryptographicException e)- {- throw new PasswordProtected7zException("Password-protected 7z archives are not supported");- }+ using var archive = SevenZipArchive.Open(stream, new ReaderOptions() { Password = password });+ return archive.Entries+ .Where(x => !x.IsDirectory)+ .Select((entry, index) => new SevenZipEntry(entry, archive, index, password))+ .ToList();}- public class SevenZipEntry(SevenZipArchiveEntry entry, SevenZipArchive archive, int index)+ public class SevenZipEntry(SevenZipArchiveEntry entry, SevenZipArchive archive, int index, string? password){+ public SevenZipArchiveEntry Entry => entry;public string PathWithinArchive { get; } = entry.Key!;public CompressionType CompressionType { get; } = entry.GetCompressionType();+ public bool IsEncrypted { get; } = entry.IsEncrypted;+ public bool IsSolid { get; } = entry.IsSolid;++ public AesParams? AesParams { get; } =+ AesParams.FromCoderInfo(entry.GetAesCoderInfoProps(), password, entry.Size);++ public long FolderStartByteOffset { get; } = entry.GetFolderStartByteOffset();public LongRange ByteRangeWithinArchive { get; } =- LongRange.FromStartAndSize(archive.GetEntryStartByteOffset(index), entry.Size);+ LongRange.FromStartAndSize(archive.GetEntryStartByteOffset(index), archive.GetPackSize(index));}}\ No newline at end of filediff --git a/backend/WebDav/DatabaseStoreMultipartFile.cs b/backend/WebDav/DatabaseStoreMultipartFile.csindex 26e05503..9bd24f7d 100644--- a/backend/WebDav/DatabaseStoreMultipartFile.cs+++ b/backend/WebDav/DatabaseStoreMultipartFile.cs@@ -32,10 +32,13 @@ public class DatabaseStoreMultipartFile(var id = davMultipartFile.Id;var multipartFile = await dbClient.Ctx.MultipartFiles.Where(x => x.Id == id).FirstOrDefaultAsync(ct);if (multipartFile is null) throw new FileNotFoundException($"Could not find nzb file with id: {id}");- return new DavMultipartFileStream(+ var packedStream = new DavMultipartFileStream(multipartFile.Metadata.FileParts,usenetClient,configManager.GetConnectionsPerStream());+ return multipartFile.Metadata.AesParams != null+ ? new AesDecoderStream(packedStream, multipartFile.Metadata.AesParams)+ : packedStream;}}\ No newline at end of file