Esempio n. 1
0
 public void SaveTo(string fileName, MpqArchiveCreateOptions createOptions)
 {
     using (var stream = FileProvider.CreateFileAndFolder(fileName))
     {
         SaveTo(stream, createOptions);
     }
 }
Esempio n. 2
0
        public void SaveTo(Stream stream, bool leaveOpen = false)
        {
            var createOptions = new MpqArchiveCreateOptions
            {
                HashTableSize   = _originalHashTableSize,
                AttributesFlags = AttributesFlags.Crc32,
            };

            SaveTo(stream, createOptions, leaveOpen);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a new <see cref="MpqArchive"/>.
        /// </summary>
        /// <param name="path">The path and name of the <see cref="MpqArchive"/> to create.</param>
        /// <param name="mpqFiles">The <see cref="MpqFile"/>s that should be added to the archive.</param>
        /// <param name="createOptions"></param>
        /// <returns>An <see cref="MpqArchive"/> created as a new file at the specified <paramref name="path"/>.</returns>
        /// <exception cref="IOException">Thrown when unable to create a <see cref="FileStream"/> from the given <paramref name="path"/>.</exception>
        public static MpqArchive Create(string path, IEnumerable <MpqFile> mpqFiles, MpqArchiveCreateOptions createOptions)
        {
            FileStream fileStream;

            try
            {
                fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite);
            }
            catch (Exception exception)
            {
                throw new IOException($"Failed to create a {nameof(FileStream)} at {path}", exception);
            }

            return(Create(fileStream, mpqFiles, createOptions, false));
        }
Esempio n. 4
0
        public void SaveTo(Stream stream, MpqArchiveCreateOptions createOptions, bool leaveOpen = false)
        {
            if (createOptions is null)
            {
                throw new ArgumentNullException(nameof(createOptions));
            }

            if (!createOptions.ListFileCreateMode.HasValue)
            {
                createOptions.ListFileCreateMode = _removedFiles.Contains(ListFile.FileName.GetStringHash()) ? MpqFileCreateMode.Prune : MpqFileCreateMode.Overwrite;
            }

            if (!createOptions.AttributesCreateMode.HasValue)
            {
                createOptions.AttributesCreateMode = _removedFiles.Contains(Attributes.FileName.GetStringHash()) ? MpqFileCreateMode.Prune : MpqFileCreateMode.Overwrite;
            }

            createOptions.HashTableSize ??= _originalHashTableSize;
            MpqArchive.Create(stream, GetMpqFiles().ToArray(), createOptions, leaveOpen).Dispose();
        }
Esempio n. 5
0
 internal Attributes(MpqArchiveCreateOptions mpqArchiveCreateOptions)
 {
     Unk   = 100;
     Flags = mpqArchiveCreateOptions.AttributesFlags;
 }
Esempio n. 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MpqArchive"/> class.
        /// </summary>
        /// <param name="sourceStream">The <see cref="Stream"/> containing pre-archive data. Can be <see langword="null"/>.</param>
        /// <param name="inputFiles">The <see cref="MpqFile"/>s that should be added to the archive.</param>
        /// <param name="createOptions"></param>
        /// <param name="leaveOpen">If <see langword="false"/>, the given <paramref name="sourceStream"/> will be disposed when the <see cref="MpqArchive"/> is disposed.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="mpqFiles"/> collection is <see langword="null"/>.</exception>
        public MpqArchive(Stream?sourceStream, IEnumerable <MpqFile> inputFiles, MpqArchiveCreateOptions createOptions, bool leaveOpen = false)
        {
            if (inputFiles is null)
            {
                throw new ArgumentNullException(nameof(inputFiles));
            }

            if (createOptions is null)
            {
                throw new ArgumentNullException(nameof(createOptions));
            }

            _isStreamOwner = !leaveOpen;
            _baseStream    = AlignStream(sourceStream);

            _headerOffset         = _baseStream.Position;
            _blockSize            = BlockSizeModifier << createOptions.BlockSize;
            _archiveFollowsHeader = createOptions.WriteArchiveFirst;

            var signatureName  = Signature.FileName.GetStringHash();
            var listFileName   = ListFile.FileName.GetStringHash();
            var attributesName = Attributes.FileName.GetStringHash();

            var signatureCreateMode  = createOptions.SignatureCreateMode.GetValueOrDefault(MpqFileCreateMode.Prune);
            var listFileCreateMode   = createOptions.ListFileCreateMode.GetValueOrDefault(MpqFileCreateMode.Overwrite);
            var attributesCreateMode = createOptions.AttributesCreateMode.GetValueOrDefault(MpqFileCreateMode.Overwrite);
            var haveSignature        = false;
            var haveListFile         = false;
            var haveAttributes       = false;
            var mpqFiles             = new HashSet <MpqFile>(MpqFileComparer.Default);

            foreach (var mpqFile in inputFiles)
            {
                if (mpqFile is MpqOrphanedFile)
                {
                    continue;
                }

                if (mpqFile.Name == signatureName)
                {
                    if (signatureCreateMode.HasFlag(MpqFileCreateMode.RemoveFlag))
                    {
                        continue;
                    }
                    else
                    {
                        haveSignature = true;
                    }
                }

                if (mpqFile.Name == listFileName)
                {
                    if (listFileCreateMode.HasFlag(MpqFileCreateMode.RemoveFlag))
                    {
                        continue;
                    }
                    else
                    {
                        haveListFile = true;
                    }
                }

                if (mpqFile.Name == attributesName)
                {
                    if (attributesCreateMode.HasFlag(MpqFileCreateMode.RemoveFlag))
                    {
                        continue;
                    }
                    else
                    {
                        haveAttributes = true;
                    }
                }

                if (!mpqFiles.Add(mpqFile))
                {
                    // todo: logging?
                }
            }

            var fileCount = (uint)mpqFiles.Count;

            var wantGenerateSignature = !haveSignature && signatureCreateMode.HasFlag(MpqFileCreateMode.AddFlag);
            var signature             = wantGenerateSignature ? new Signature() : null;

            if (wantGenerateSignature)
            {
                fileCount++;
            }

            var wantGenerateListFile = !haveListFile && listFileCreateMode.HasFlag(MpqFileCreateMode.AddFlag);
            var listFile             = wantGenerateListFile ? new ListFile() : null;

            if (wantGenerateListFile)
            {
                fileCount++;
            }

            var wantGenerateAttributes = !haveAttributes && attributesCreateMode.HasFlag(MpqFileCreateMode.AddFlag);
            var attributes             = wantGenerateAttributes ? new Attributes(createOptions) : null;

            if (wantGenerateAttributes)
            {
                fileCount++;
            }

            _hashTable  = new HashTable(Math.Max(createOptions.HashTableSize ?? fileCount * 8, fileCount));
            _blockTable = new BlockTable();

            using (var writer = new BinaryWriter(_baseStream, new UTF8Encoding(false, true), true))
            {
                // Skip the MPQ header, since its contents will be calculated afterwards.
                writer.Seek((int)MpqHeader.Size, SeekOrigin.Current);

                // Write Archive
                var fileIndex  = 0U;
                var fileOffset = _archiveFollowsHeader ? MpqHeader.Size : throw new NotImplementedException();

                // var gaps = new List<(long Start, long Length)>();
                var endOfStream = _baseStream.Position;

                void InsertMpqFile(MpqFile mpqFile, bool updateEndOfStream, bool allowMultiple = true)
                {
                    if (listFile is not null && mpqFile is MpqKnownFile knownFile)
                    {
                        listFile.FileNames.Add(knownFile.FileName);
                    }

                    mpqFile.AddToArchive(this, fileIndex, out var mpqEntry, out var mpqHash);
                    var hashTableEntries = _hashTable.Add(mpqHash, mpqFile.HashIndex, mpqFile.HashCollisions);

                    if (!allowMultiple && hashTableEntries > 1)
                    {
                        throw new Exception();
                    }

                    var crc32 = 0;

                    if (attributes is not null && attributes.Flags.HasFlag(AttributesFlags.Crc32) && allowMultiple)
                    {
                        mpqFile.MpqStream.Position = 0;
                        crc32 = new Ionic.Crc.CRC32().GetCrc32(mpqFile.MpqStream);
                    }

                    for (var i = 0; i < hashTableEntries; i++)
                    {
                        _blockTable.Add(mpqEntry);
                        if (attributes is not null)
                        {
                            if (attributes.Flags.HasFlag(AttributesFlags.Crc32))
                            {
                                attributes.Crc32s.Add(crc32);
                            }

                            if (attributes.Flags.HasFlag(AttributesFlags.DateTime))
                            {
                                attributes.DateTimes.Add(DateTime.Now);
                            }

                            if (attributes.Flags.HasFlag(AttributesFlags.Unk0x04))
                            {
                                attributes.Unk0x04s.Add(new byte[16]);
                            }
                        }
                    }

                    mpqFile.Dispose();

                    fileIndex += hashTableEntries;
                    if (updateEndOfStream)
                    {
                        endOfStream = _baseStream.Position;
                    }
                }

                // Find files that cannot be decrypted, and need to have a specific position in the archive, because that position is used to calculate the encryption seed.
                var mpqFixedPositionFiles = mpqFiles.Where(mpqFile => mpqFile.IsFilePositionFixed).OrderBy(mpqFile => mpqFile.MpqStream.FilePosition).ToArray();
                if (mpqFixedPositionFiles.Length > 0)
                {
                    if (mpqFixedPositionFiles.First() !.MpqStream.FilePosition < 0)
                    {
                        throw new NotSupportedException($"Cannot place files in front of the header.");
                    }

                    foreach (var mpqFixedPositionFile in mpqFixedPositionFiles)
                    {
                        var position = mpqFixedPositionFile.MpqStream.FilePosition;
                        if (position < endOfStream)
                        {
                            throw new ArgumentException($"Fixed position files overlap with each other and/or the header. Archive cannot be created.", nameof(inputFiles));
                        }

                        if (position > endOfStream)
                        {
                            var gapSize = position - endOfStream;
                            // gaps.Add((endOfStream, gapSize));
                            writer.Seek((int)gapSize, SeekOrigin.Current);
                        }

                        InsertMpqFile(mpqFixedPositionFile, true);
                    }
                }

                foreach (var mpqFile in mpqFiles.Where(mpqFile => !mpqFile.IsFilePositionFixed))
                {
                    // TODO: insert files into the gaps
                    // need to know compressed size of file first, and if file is also encrypted with blockoffsetadjustedkey, encryption needs to happen after gap selection
                    // therefore, can't use current AddToArchive method, which does both compression and encryption at same time

                    // var availableGaps = gaps.Where(gap => gap.Length >= )
                    var selectedPosition = endOfStream;
                    var selectedGap      = false;
                    _baseStream.Position = selectedPosition;

                    InsertMpqFile(mpqFile, !selectedGap);
                }

                var signaturePosition = endOfStream + 8;
                if (signature is not null)
                {
                    _baseStream.Position = endOfStream;

                    using var signatureStream = new MemoryStream();
                    using var signatureWriter = new BinaryWriter(signatureStream);
                    signatureWriter.Write(signature);
                    signatureWriter.Flush();

                    using var signatureMpqFile   = MpqFile.New(signatureStream, Signature.FileName);
                    signatureMpqFile.TargetFlags = MpqFileFlags.Exists;
                    InsertMpqFile(signatureMpqFile, true);
                }

                if (listFile is not null)
                {
                    _baseStream.Position = endOfStream;

                    using var listFileStream = new MemoryStream();
                    using var listFileWriter = new StreamWriter(listFileStream);
                    listFileWriter.WriteListFile(listFile);
                    listFileWriter.Flush();

                    using var listFileMpqFile   = MpqFile.New(listFileStream, ListFile.FileName);
                    listFileMpqFile.TargetFlags = MpqFileFlags.Exists | MpqFileFlags.CompressedMulti | MpqFileFlags.Encrypted | MpqFileFlags.BlockOffsetAdjustedKey;
                    InsertMpqFile(listFileMpqFile, true);
                }

                if (attributes is not null)
                {
                    _baseStream.Position = endOfStream;

                    if (attributes.Flags.HasFlag(AttributesFlags.Crc32))
                    {
                        attributes.Crc32s.Add(0);
                    }

                    if (attributes.Flags.HasFlag(AttributesFlags.DateTime))
                    {
                        attributes.DateTimes.Add(DateTime.Now);
                    }

                    if (attributes.Flags.HasFlag(AttributesFlags.Unk0x04))
                    {
                        attributes.Unk0x04s.Add(new byte[16]);
                    }

                    using var attributesStream = new MemoryStream();
                    using var attributesWriter = new BinaryWriter(attributesStream);
                    attributesWriter.Write(attributes);
                    attributesWriter.Flush();

                    using var attributesMpqFile   = MpqFile.New(attributesStream, Attributes.FileName);
                    attributesMpqFile.TargetFlags = MpqFileFlags.Exists | MpqFileFlags.CompressedMulti | MpqFileFlags.Encrypted | MpqFileFlags.BlockOffsetAdjustedKey;
                    InsertMpqFile(attributesMpqFile, true, false);
                }

                _baseStream.Position = endOfStream;
                _hashTable.WriteTo(writer);
                _blockTable.WriteTo(writer);

                /*if (!_archiveFollowsHeader)
                 * {
                 *  foreach (var mpqFile in mpqFiles)
                 *  {
                 *      mpqFile.WriteTo(writer, true);
                 *  }
                 * }*/

                writer.Seek((int)_headerOffset, SeekOrigin.Begin);

                _mpqHeader = new MpqHeader((uint)_headerOffset, (uint)(endOfStream - fileOffset), _hashTable.Size, _blockTable.Size, createOptions.BlockSize, _archiveFollowsHeader);
                _mpqHeader.WriteTo(writer);

                if (wantGenerateSignature)
                {
                    var archiveBytes = new byte[_mpqHeader.ArchiveSize];
                    _baseStream.Position = _headerOffset;
                    _baseStream.Read(archiveBytes);

                    using var rsa = RSA.Create();

                    rsa.ImportFromPem(createOptions.SignaturePrivateKey);
                    var signatureBytes = rsa.SignData(archiveBytes, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1);

                    _baseStream.Position = signaturePosition;
                    _baseStream.Write(signatureBytes.Reverse().ToArray());
                }
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Creates a new <see cref="MpqArchive"/>.
 /// </summary>
 /// <param name="sourceStream">The <see cref="Stream"/> containing pre-archive data. Can be <see langword="null"/>.</param>
 /// <param name="mpqFiles">The <see cref="MpqFile"/>s that should be added to the archive.</param>
 /// <param name="createOptions"></param>
 /// <param name="leaveOpen">If <see langword="false"/>, the given <paramref name="sourceStream"/> will be disposed when the <see cref="MpqArchive"/> is disposed.</param>
 /// <returns>An <see cref="MpqArchive"/> that is created.</returns>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="mpqFiles"/> collection is <see langword="null"/>.</exception>
 public static MpqArchive Create(Stream?sourceStream, IEnumerable <MpqFile> mpqFiles, MpqArchiveCreateOptions createOptions, bool leaveOpen = false)
 {
     return(new MpqArchive(sourceStream, mpqFiles, createOptions, leaveOpen));
 }