Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Fixed Content-Length bug with password-protected nzbs (#123)
nzbdav-devd8b9b00ea10e
diff --git a/backend/Streams/AesDecoderStream.cs b/backend/Streams/AesDecoderStream.csindex dbac1981..75063f29 100644--- a/backend/Streams/AesDecoderStream.cs+++ b/backend/Streams/AesDecoderStream.cs@@ -6,54 +6,68 @@ namespace NzbWebDAV.Streamsinternal sealed class AesDecoderStream : Stream{private readonly Stream _mStream;+ private Aes _aes; // keep Aes alive for transform lifetimeprivate ICryptoTransform _mDecoder;- private readonly byte[] _mBuffer;- private long _mWritten;+ private readonly byte[] _plainBuffer; // decrypted bytes cache+ private int _plainStart;+ private int _plainEnd;+ private readonly byte[] _cipherBuffer; // buffer to read ciphertext blocks in chunks++ private long _mWritten; // number of decoded bytes returned alreadyprivate readonly long _mLimit;- private int _mOffset;- private int _mEnding;- private int _mUnderflow;private bool _isDisposed;- private long? pendingSeekPosition = null;+ private long? _pendingSeekPosition = null;// store for reinitializing on Seekprivate readonly byte[] _mKey;private readonly byte[] _mBaseIv;+ private const int BlockSize = 16;+ private const int DefaultPlainBufferSize = 4 << 10; // 4096+ private const int DefaultCipherBufferBlocks = 8; // read up to 8 blocks at once+public AesDecoderStream(Stream input, AesParams aesParams){- _mStream = input;+ _mStream = input ?? throw new ArgumentNullException(nameof(input));_mLimit = aesParams.DecodedSize;- _mKey = aesParams.Key;- _mBaseIv = aesParams.Iv;+ _mKey = aesParams.Key ?? throw new ArgumentNullException(nameof(aesParams.Key));+ _mBaseIv = aesParams.Iv ?? throw new ArgumentNullException(nameof(aesParams.Iv));- if (((uint)input.Length & 15) != 0)+ if (((uint)input.Length & (BlockSize - 1)) != 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);- }+ // Create and hold Aes instance for the lifetime of this stream (safer)+ _aes = Aes.Create();+ _aes.Mode = CipherMode.CBC;+ _aes.Padding = PaddingMode.None;++ _mDecoder = _aes.CreateDecryptor(_mKey, _mBaseIv);- _mBuffer = new byte[4 << 10];+ // plain buffer - capacity should be multiple of block size and >= one block+ var psize = DefaultPlainBufferSize;+ if ((psize & (BlockSize - 1)) != 0) psize += BlockSize - (psize & (BlockSize - 1));+ if (psize < BlockSize) psize = BlockSize;+ _plainBuffer = new byte[psize];++ _cipherBuffer = new byte[BlockSize * DefaultCipherBufferBlocks];++ _plainStart = _plainEnd = 0;+ _mWritten = 0;}protected override void Dispose(bool disposing){try{- if (_isDisposed)- return;-+ if (_isDisposed) return;_isDisposed = true;if (disposing){_mStream.Dispose();- _mDecoder.Dispose();+ _mDecoder?.Dispose();+ _aes?.Dispose();}}finally@@ -66,7 +80,7 @@ namespace NzbWebDAV.Streamspublic override long Position{- get => pendingSeekPosition ?? _mWritten;+ get => _pendingSeekPosition ?? _mWritten;set => Seek(value, SeekOrigin.Begin);}@@ -82,49 +96,127 @@ namespace NzbWebDAV.Streamspublic override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken ct){- // perform any pending seeks- if (pendingSeekPosition != null)+ if (buffer == null) throw new ArgumentNullException(nameof(buffer));+ if (offset < 0 || count < 0 || offset + count > buffer.Length) throw new ArgumentOutOfRangeException();++ // Perform pending seek (deferred heavy work)+ if (_pendingSeekPosition != null){- if (!await SeekAsync(pendingSeekPosition.Value, ct)) return 0;- pendingSeekPosition = null;+ var pos = _pendingSeekPosition.Value;+ _pendingSeekPosition = null;+ await SeekInternalAsync(pos, ct).ConfigureAwait(false);}if (count == 0 || _mWritten == _mLimit)return 0;- if (_mUnderflow > 0)- return HandleUnderflow(buffer, offset, count);+ // Cap to remaining logical decoded bytes+ int toReturnAllowed = (int)Math.Min(count, _mLimit - _mWritten);+ int totalCopied = 0;- // Need at least 16 bytes- if (_mEnding - _mOffset < 16)+ // First, deliver any already-decrypted bytes in the plain buffer+ if (_plainEnd > _plainStart){- Buffer.BlockCopy(_mBuffer, _mOffset, _mBuffer, 0, _mEnding - _mOffset);- _mEnding -= _mOffset;- _mOffset = 0;-- do+ int have = _plainEnd - _plainStart;+ int take = Math.Min(have, toReturnAllowed);+ Buffer.BlockCopy(_plainBuffer, _plainStart, buffer, offset, take);+ _plainStart += take;+ _mWritten += take;+ totalCopied += take;+ toReturnAllowed -= take;+ offset += take;++ if (_plainStart == _plainEnd){- var read = await _mStream- .ReadAsync(_mBuffer.AsMemory(_mEnding, _mBuffer.Length - _mEnding), ct)- .ConfigureAwait(false);- if (read == 0) return 0;- _mEnding += read;- } while (_mEnding - _mOffset < 16);+ _plainStart = _plainEnd = 0;+ }++ if (toReturnAllowed == 0 || _mWritten == _mLimit)+ return totalCopied;}- if (count > _mLimit - _mWritten)- count = (int)(_mLimit - _mWritten);+ // Now read ciphertext and decrypt as many blocks as needed/fit+ while (toReturnAllowed > 0 && _mWritten < _mLimit)+ {+ // Read up to cipherBuffer.Length bytes from underlying stream in one ReadAsync+ int cipherRead = 0;+ int firstRead = await _mStream.ReadAsync(_cipherBuffer, 0, _cipherBuffer.Length, ct)+ .ConfigureAwait(false);+ if (firstRead == 0)+ {+ // underlying stream EOF+ return totalCopied;+ }++ cipherRead = firstRead;- if (count < 16)- return HandleUnderflow(buffer, offset, count);+ // If we didn't read an integral number of blocks, try to read more until we either have whole blocks+ // or underlying stream returns 0. Given the constructor check, partial final block is considered error.+ while ((cipherRead & (BlockSize - 1)) != 0)+ {+ int need = BlockSize - (cipherRead & (BlockSize - 1));+ int r = await _mStream.ReadAsync(_cipherBuffer, cipherRead, need, ct).ConfigureAwait(false);+ if (r == 0)+ {+ // corrupt ciphertext (not multiple of blocksize)+ throw new EndOfStreamException(+ "Unexpected end of ciphertext stream (not a multiple of block size).");+ }++ cipherRead += r;+ }- if (count > _mEnding - _mOffset)- count = _mEnding - _mOffset;+ // Decrypt as many whole blocks as will fit into the plainBuffer+ int decryptOffset = 0;+ while (decryptOffset < cipherRead)+ {+ int cipherRemaining = cipherRead - decryptOffset;+ int plainSpace = _plainBuffer.Length - _plainEnd;+ // If there is no plain space, compact the buffer if possible+ if (plainSpace < BlockSize && _plainStart > 0)+ {+ int existing = _plainEnd - _plainStart;+ if (existing > 0)+ Buffer.BlockCopy(_plainBuffer, _plainStart, _plainBuffer, 0, existing);+ _plainStart = 0;+ _plainEnd = existing;+ plainSpace = _plainBuffer.Length - _plainEnd;+ }++ // How many cipher bytes (multiple of blocksize) can we process now?+ int processBytes = Math.Min(cipherRemaining, plainSpace & ~(BlockSize - 1));+ if (processBytes == 0)+ {+ // plain buffer cannot accept even one block; we must stop decrypting and allow copying out+ break;+ }++ int processed = _mDecoder.TransformBlock(_cipherBuffer, decryptOffset, processBytes, _plainBuffer,+ _plainEnd);+ decryptOffset += processBytes;+ _plainEnd += processed;+ }- var processed = _mDecoder.TransformBlock(_mBuffer, _mOffset, count & ~15, buffer, offset);- _mOffset += processed;- _mWritten += processed;- return processed;+ // Copy decrypted bytes to destination+ if (_plainEnd > _plainStart)+ {+ int have = _plainEnd - _plainStart;+ int take = Math.Min(have, toReturnAllowed);+ Buffer.BlockCopy(_plainBuffer, _plainStart, buffer, offset, take);+ _plainStart += take;+ _mWritten += take;+ totalCopied += take;+ toReturnAllowed -= take;+ offset += take;++ if (_plainStart == _plainEnd)+ {+ _plainStart = _plainEnd = 0;+ }+ }+ }++ return totalCopied;}public override void SetLength(long value) => throw new NotImplementedException();@@ -151,91 +243,92 @@ namespace NzbWebDAV.Streamsif (target < 0 || target > _mLimit)throw new ArgumentOutOfRangeException(nameof(offset), "Seek position outside stream limits");- pendingSeekPosition = target;+ // Defer heavy work to next ReadAsync (seek is "instant")+ _pendingSeekPosition = target;+ // clear decrypted buffer so it doesn't leak across seeks+ _plainStart = _plainEnd = 0;return target;}- private async Task<bool> SeekAsync(long offset, CancellationToken ct)+ /// <summary>+ /// Perform the real seek work: set underlying stream position to correct ciphertext block,+ /// create a decryptor with appropriate IV (previous ciphertext block or base IV),+ /// and populate the plain buffer if seeking into the middle of a block.+ /// </summary>+ private async Task SeekInternalAsync(long offset, CancellationToken ct){- // Align to AES block size (16)- var blockSize = 16;- var blockIndex = offset / blockSize;- var blockOffset = offset % blockSize;+ if (offset < 0 || offset > _mLimit) throw new ArgumentOutOfRangeException(nameof(offset));- // We need previous block to get proper IV- var cipherPos = blockIndex > 0 ? (blockIndex - 1) * blockSize : 0;+ long blockIndex = offset / BlockSize;+ int blockOffset = (int)(offset % BlockSize);- // Seek underlying stream- _mStream.Seek(cipherPos, SeekOrigin.Begin);+ long cipherPosForRead = (blockIndex > 0) ? (blockIndex - 1) * BlockSize : 0L;+ _mStream.Seek(cipherPosForRead, SeekOrigin.Begin);- // Read previous block as IV (or original IV for block 0)- var iv = new byte[16];+ // determine IV: previous ciphertext block (if blockIndex>0) or base IV+ var iv = new byte[BlockSize];if (blockIndex > 0){- try- {- await _mStream.ReadExactlyAsync(iv.AsMemory(0, 16), ct);- }- catch (Exception e)+ int read = 0;+ while (read < BlockSize){- throw new EndOfStreamException("Unable to read previous block for IV", e);+ int r = await _mStream.ReadAsync(iv, read, BlockSize - read, ct).ConfigureAwait(false);+ if (r == 0) throw new EndOfStreamException("Unable to read previous block for IV during seek.");+ read += r;}+ // after this read, stream at start of target block}else{- Buffer.BlockCopy(_mBaseIv, 0, iv, 0, 16);+ Buffer.BlockCopy(_mBaseIv, 0, iv, 0, BlockSize);+ // stream already at start (0)}- // 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);- }+ // recreate decryptor using existing Aes instance+ _mDecoder?.Dispose();+ _mDecoder = _aes.CreateDecryptor(_mKey, iv);- // Reset internal buffers- _mOffset = 0;- _mEnding = 0;- _mUnderflow = 0;- _mWritten = offset - blockOffset; // position of start of current block+ // reset plain buffer+ _plainStart = _plainEnd = 0;- // Preload and decrypt up to the block containing target+ // logical written position is start of block+ _mWritten = offset - blockOffset;++ // If seeking into middle of block, decrypt that block and store remainderif (blockOffset > 0){- var tempCipher = new byte[blockSize];- await _mStream.ReadExactlyAsync(tempCipher.AsMemory(0, blockSize), ct);+ var block = new byte[BlockSize];+ int read = 0;+ while (read < BlockSize)+ {+ int r = await _mStream.ReadAsync(block, read, BlockSize - read, ct).ConfigureAwait(false);+ if (r == 0) throw new EndOfStreamException("Unable to read target block during seek.");+ read += r;+ }- var tempPlain = new byte[blockSize];- var decrypted = _mDecoder.TransformBlock(tempCipher, 0, blockSize, tempPlain, 0);+ var tempPlain = new byte[BlockSize];+ int dec = _mDecoder.TransformBlock(block, 0, BlockSize, tempPlain, 0);+ if (dec != BlockSize) throw new CryptographicException("Unexpected decrypted block size during seek.");- // 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;- }+ int remainder = BlockSize - blockOffset;+ if (remainder > 0)+ {+ if (remainder > _plainBuffer.Length)+ throw new InvalidOperationException("Plain buffer too small for remainder.");+ Buffer.BlockCopy(tempPlain, blockOffset, _plainBuffer, 0, remainder);+ _plainStart = 0;+ _plainEnd = remainder;+ }- return true;+ // set written to match requested offset+ _mWritten = offset; // offset - blockOffset + blockOffset+ }}- private int HandleUnderflow(byte[] buffer, int offset, int count)+ public override void Close(){- 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;+ Dispose(true);+ base.Close();}}}\ No newline at end of file