Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 63 additions & 53 deletions Queueify.Launcher/Bundle.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System.Buffers.Binary;
using System.Formats.Tar;
using System.IO.Compression;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using SevenZip;

namespace Queueify.Launcher;

Expand All @@ -13,16 +14,19 @@ public sealed record BundleInfo(long Offset, long Length, string Id);
public sealed class BundleDamagedException(string message, Exception? inner = null) : Exception(message, inner);

/// <summary>
/// The download is the starter exe followed by the app folder as one Brotli-compressed tar, then a
/// trailer: the archive's length, its id (a hash of it, which names the unpacked folder) and a marker.
/// Windows runs an exe from its headers, so whatever is appended after the starter doesn't disturb it.
/// The download is the starter exe followed by the app folder as one tar, run through the x86 branch filter
/// and compressed with LZMA, then a trailer: the archive's length, its id (a hash of it, which names the
/// unpacked folder) and a marker. Windows runs an exe from its headers, so whatever is appended after the
/// starter doesn't disturb it. The archive is LZMA's 5 property bytes, the tar's length (8 bytes) and the
/// compressed tar.
/// </summary>
public static class Bundle
{
private static readonly byte[] Marker = "QFYAPP01"u8.ToArray();
private static readonly byte[] Marker = "QFYAPP02"u8.ToArray();
private const int IdLength = 32;
private const int TrailerLength = sizeof(long) + IdLength + 8;
private const string Complete = ".complete";
private const uint MaxDictionary = 1u << 26;

// Same bytes for the same files, so an unchanged version keeps its id and its unpacked folder.
private static readonly DateTimeOffset FixedTime = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
Expand All @@ -32,9 +36,8 @@ public static void Write(string starterExe, string appFolder, string outputExe)
var archive = outputExe + ".archive";
try
{
using (var file = File.Create(archive))
using (var brotli = new BrotliCompressingStream(file))
using (var tar = new TarWriter(brotli, TarEntryFormat.Gnu, leaveOpen: true))
var tarData = new MemoryStream();
using (var tar = new TarWriter(tarData, TarEntryFormat.Gnu, leaveOpen: true))
{
var root = Path.GetFullPath(appFolder);
var files = Directory.GetFiles(root, "*", SearchOption.AllDirectories)
Expand All @@ -51,6 +54,7 @@ public static void Write(string starterExe, string appFolder, string outputExe)
});
}
}
using (var file = File.Create(archive)) Compress(tarData.ToArray(), file);

byte[] id;
using (var file = File.OpenRead(archive)) id = Encoding.ASCII.GetBytes(Convert.ToHexStringLower(SHA256.HashData(file))[..IdLength]);
Expand Down Expand Up @@ -112,8 +116,8 @@ public static string Unpack(Stream exe, BundleInfo info, string cacheFolder)

private static void Extract(Stream exe, BundleInfo info, string folder)
{
// Checked before anything is written: Brotli has no checksum of its own, and the id is the
// archive's hash. About 20 MB, read in a moment.
// Checked before anything is written: LZMA has no checksum of its own, and the id is the
// archive's hash. About 17 MB, read in a moment.
using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
{
exe.Seek(info.Offset, SeekOrigin.Begin);
Expand All @@ -123,11 +127,21 @@ private static void Extract(Stream exe, BundleInfo info, string folder)
}

exe.Seek(info.Offset, SeekOrigin.Begin);
var archive = new Slice(exe, info.Length, null);
byte[] tarData;
try
{
using var brotli = new BrotliStream(archive, CompressionMode.Decompress, leaveOpen: true);
using var tar = new TarReader(brotli);
tarData = Decompress(new Slice(exe, info.Length, null));
}
catch (Exception ex) when (ex is ApplicationException or InvalidDataException or EndOfStreamException or IndexOutOfRangeException or NotSupportedException)
{
// The LZMA SDK's own DataErrorException is an ApplicationException; a decoder fed bad data can
// also run off its arrays, or past the size it was told.
throw new BundleDamagedException("The appended app can't be read.", ex);
}

try
{
using var tar = new TarReader(new MemoryStream(tarData, writable: false));
var root = Path.GetFullPath(folder) + Path.DirectorySeparatorChar;
while (tar.GetNextEntry() is { } entry)
{
Expand Down Expand Up @@ -204,50 +218,46 @@ private static void TryDelete(string dir)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
}

/// <summary>Brotli at its strongest, with the largest window: the app folder is one big archive.</summary>
private sealed class BrotliCompressingStream(Stream inner) : Stream
/// <summary>
/// LZMA at its strongest, as 7-Zip's Ultra: a 64 MB dictionary (or less, for less) and the longest matches.
/// About a minute for the app's 70 MB, at build time.
/// </summary>
private static void Compress(byte[] data, Stream output)
{
private BrotliEncoder _encoder = new(quality: 11, window: 24);
private readonly byte[] _buffer = new byte[1 << 16];

public override void Write(ReadOnlySpan<byte> source)
{
while (!source.IsEmpty)
{
_encoder.Compress(source, _buffer, out int read, out int written, isFinalBlock: false);
inner.Write(_buffer, 0, written);
source = source[read..];
}
}

public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
X86Filter.Encode(data);
var encoder = new SevenZip.Compression.LZMA.Encoder();
var dictionary = (int)Math.Min(MaxDictionary, BitOperations.RoundUpToPowerOf2((uint)Math.Max(data.Length, 1 << 12)));
encoder.SetCoderProperties(
[CoderPropID.DictionarySize, CoderPropID.LitContextBits, CoderPropID.LitPosBits, CoderPropID.PosStateBits,
CoderPropID.Algorithm, CoderPropID.NumFastBytes, CoderPropID.MatchFinder, CoderPropID.EndMarker],
[dictionary, 3, 0, 2, 2, 273, "bt4", false]);
encoder.WriteCoderProperties(output);
Span<byte> length = stackalloc byte[sizeof(long)];
BinaryPrimitives.WriteInt64LittleEndian(length, data.Length);
output.Write(length);
encoder.Code(new MemoryStream(data, writable: false), output, -1, -1, null);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
System.Buffers.OperationStatus status;
do
{
status = _encoder.Compress([], _buffer, out _, out int written, isFinalBlock: true);
inner.Write(_buffer, 0, written);
} while (status == System.Buffers.OperationStatus.DestinationTooSmall);
_encoder.Dispose();
}
base.Dispose(disposing);
}
/// <summary>The whole tar, in memory: the branch filter undoes its work over all of it at once.</summary>
private static byte[] Decompress(Stream archive)
{
var properties = new byte[5];
archive.ReadExactly(properties);
Span<byte> lengthBytes = stackalloc byte[sizeof(long)];
archive.ReadExactly(lengthBytes);
var length = BinaryPrimitives.ReadInt64LittleEndian(lengthBytes);
// Never more than Compress writes, so a bad header can't ask for gigabytes of memory.
if (length is < 0 or > 1L << 30 || properties[0] >= 9 * 5 * 5 || BinaryPrimitives.ReadUInt32LittleEndian(properties.AsSpan(1)) > MaxDictionary)
throw new InvalidDataException("Unexpected archive header.");

public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() => inner.Flush();
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
var data = new byte[length];
var decoder = new SevenZip.Compression.LZMA.Decoder();
decoder.SetDecoderProperties(properties);
// The decoder reads a byte at a time.
decoder.Code(new BufferedStream(archive, 1 << 16), new MemoryStream(data), archive.Length - archive.Position, length, null);
X86Filter.Decode(data);
return data;
}

/// <summary>The archive's bytes only, so decompression can't run into the trailer; hashed as they're read.</summary>
private sealed class Slice(Stream inner, long length, IncrementalHash? hash) : Stream
{
Expand Down
4 changes: 4 additions & 0 deletions Queueify.Launcher/Lzma/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# The LZMA SDK's C# code as published, kept as is: no analyzers or nullable warnings.
[*.cs]
generated_code = true

55 changes: 55 additions & 0 deletions Queueify.Launcher/Lzma/CRC.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Common/CRC.cs

namespace SevenZip
{
class CRC
{
public static readonly uint[] Table;

static CRC()
{
Table = new uint[256];
const uint kPoly = 0xEDB88320;
for (uint i = 0; i < 256; i++)
{
uint r = i;
for (int j = 0; j < 8; j++)
if ((r & 1) != 0)
r = (r >> 1) ^ kPoly;
else
r >>= 1;
Table[i] = r;
}
}

uint _value = 0xFFFFFFFF;

public void Init() { _value = 0xFFFFFFFF; }

public void UpdateByte(byte b)
{
_value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8);
}

public void Update(byte[] data, uint offset, uint size)
{
for (uint i = 0; i < size; i++)
_value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8);
}

public uint GetDigest() { return _value ^ 0xFFFFFFFF; }

static uint CalculateDigest(byte[] data, uint offset, uint size)
{
CRC crc = new CRC();
// crc.Init();
crc.Update(data, offset, size);
return crc.GetDigest();
}

static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
{
return (CalculateDigest(data, offset, size) == digest);
}
}
}
157 changes: 157 additions & 0 deletions Queueify.Launcher/Lzma/ICoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// ICoder.h

using System;

namespace SevenZip
{
/// <summary>
/// The exception that is thrown when an error in input stream occurs during decoding.
/// </summary>
class DataErrorException : ApplicationException
{
public DataErrorException(): base("Data Error") { }
}

/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range.
/// </summary>
class InvalidParamException : ApplicationException
{
public InvalidParamException(): base("Invalid Parameter") { }
}

public interface ICodeProgress
{
/// <summary>
/// Callback progress.
/// </summary>
/// <param name="inSize">
/// input size. -1 if unknown.
/// </param>
/// <param name="outSize">
/// output size. -1 if unknown.
/// </param>
void SetProgress(Int64 inSize, Int64 outSize);
};

public interface ICoder
{
/// <summary>
/// Codes streams.
/// </summary>
/// <param name="inStream">
/// input Stream.
/// </param>
/// <param name="outStream">
/// output Stream.
/// </param>
/// <param name="inSize">
/// input Size. -1 if unknown.
/// </param>
/// <param name="outSize">
/// output Size. -1 if unknown.
/// </param>
/// <param name="progress">
/// callback progress reference.
/// </param>
/// <exception cref="SevenZip.DataErrorException">
/// if input stream is not valid
/// </exception>
void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress);
};

/*
public interface ICoder2
{
void Code(ISequentialInStream []inStreams,
const UInt64 []inSizes,
ISequentialOutStream []outStreams,
UInt64 []outSizes,
ICodeProgress progress);
};
*/

/// <summary>
/// Provides the fields that represent properties idenitifiers for compressing.
/// </summary>
public enum CoderPropID
{
/// <summary>
/// Specifies default property.
/// </summary>
DefaultProp = 0,
/// <summary>
/// Specifies size of dictionary.
/// </summary>
DictionarySize,
/// <summary>
/// Specifies size of memory for PPM*.
/// </summary>
UsedMemorySize,
/// <summary>
/// Specifies order for PPM methods.
/// </summary>
Order,
/// <summary>
/// Specifies Block Size.
/// </summary>
BlockSize,
/// <summary>
/// Specifies number of postion state bits for LZMA (0 <= x <= 4).
/// </summary>
PosStateBits,
/// <summary>
/// Specifies number of literal context bits for LZMA (0 <= x <= 8).
/// </summary>
LitContextBits,
/// <summary>
/// Specifies number of literal position bits for LZMA (0 <= x <= 4).
/// </summary>
LitPosBits,
/// <summary>
/// Specifies number of fast bytes for LZ*.
/// </summary>
NumFastBytes,
/// <summary>
/// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B".
/// </summary>
MatchFinder,
/// <summary>
/// Specifies the number of match finder cyckes.
/// </summary>
MatchFinderCycles,
/// <summary>
/// Specifies number of passes.
/// </summary>
NumPasses,
/// <summary>
/// Specifies number of algorithm.
/// </summary>
Algorithm,
/// <summary>
/// Specifies the number of threads.
/// </summary>
NumThreads,
/// <summary>
/// Specifies mode with end marker.
/// </summary>
EndMarker
};


public interface ISetCoderProperties
{
void SetCoderProperties(CoderPropID[] propIDs, object[] properties);
};

public interface IWriteCoderProperties
{
void WriteCoderProperties(System.IO.Stream outStream);
}

public interface ISetDecoderProperties
{
void SetDecoderProperties(byte[] properties);
}
}
Loading
Loading