Unzip.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Linq;
  7. using System.Text;
  8. namespace SongCore.Utilities
  9. {
  10. // Unzip class for .NET 3.5 Client Profile or Mono 2.10
  11. // Written by Alexey Yakovlev <yallie@yandex.ru>
  12. // https://github.com/yallie/unzip
  13. class Unzip
  14. {
  15. /// <summary>
  16. /// Zip archive entry.
  17. /// </summary>
  18. public class Entry
  19. {
  20. /// <summary>
  21. /// Gets or sets the name of a file or a directory.
  22. /// </summary>
  23. public string Name { get; set; }
  24. /// <summary>
  25. /// Gets or sets the comment.
  26. /// </summary>
  27. public string Comment { get; set; }
  28. /// <summary>
  29. /// Gets or sets the CRC32.
  30. /// </summary>
  31. public uint Crc32 { get; set; }
  32. /// <summary>
  33. /// Gets or sets the compressed size of the file.
  34. /// </summary>
  35. public int CompressedSize { get; set; }
  36. /// <summary>
  37. /// Gets or sets the original size of the file.
  38. /// </summary>
  39. public int OriginalSize { get; set; }
  40. /// <summary>
  41. /// Gets or sets a value indicating whether this <see cref="Entry" /> is deflated.
  42. /// </summary>
  43. public bool Deflated { get; set; }
  44. /// <summary>
  45. /// Gets a value indicating whether this <see cref="Entry" /> is a directory.
  46. /// </summary>
  47. public bool IsDirectory { get { return Name.EndsWith("/"); } }
  48. /// <summary>
  49. /// Gets or sets the timestamp.
  50. /// </summary>
  51. public DateTime Timestamp { get; set; }
  52. /// <summary>
  53. /// Gets a value indicating whether this <see cref="Entry" /> is a file.
  54. /// </summary>
  55. public bool IsFile { get { return !IsDirectory; } }
  56. [EditorBrowsable(EditorBrowsableState.Never)]
  57. public int HeaderOffset { get; set; }
  58. [EditorBrowsable(EditorBrowsableState.Never)]
  59. public int DataOffset { get; set; }
  60. }
  61. /// <summary>
  62. /// CRC32 calculation helper.
  63. /// </summary>
  64. public class Crc32Calculator
  65. {
  66. private static readonly uint[] Crc32Table =
  67. {
  68. 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
  69. 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
  70. 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
  71. 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
  72. 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
  73. 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
  74. 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
  75. 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
  76. 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
  77. 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
  78. 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
  79. 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
  80. 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
  81. 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
  82. 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
  83. 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
  84. 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
  85. 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
  86. 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
  87. 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
  88. 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
  89. 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
  90. 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
  91. 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
  92. 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
  93. 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
  94. 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
  95. 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
  96. 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
  97. 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
  98. 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
  99. 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
  100. };
  101. private uint crcValue = 0xffffffff;
  102. public uint Crc32 { get { return crcValue ^ 0xffffffff; } }
  103. public void UpdateWithBlock(byte[] buffer, int numberOfBytes)
  104. {
  105. for (var i = 0; i < numberOfBytes; i++)
  106. {
  107. crcValue = (crcValue >> 8) ^ Crc32Table[buffer[i] ^ crcValue & 0xff];
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// Provides data for the ExtractProgress event.
  113. /// </summary>
  114. public class FileProgressEventArgs : ProgressChangedEventArgs
  115. {
  116. /// <summary>
  117. /// Initializes a new instance of the <see cref="FileProgressEventArgs"/> class.
  118. /// </summary>
  119. /// <param name="currentFile">The current file.</param>
  120. /// <param name="totalFiles">The total files.</param>
  121. /// <param name="fileName">Name of the file.</param>
  122. public FileProgressEventArgs(int currentFile, int totalFiles, string fileName)
  123. : base(totalFiles != 0 ? currentFile * 100 / totalFiles : 100, fileName)
  124. {
  125. CurrentFile = currentFile;
  126. TotalFiles = totalFiles;
  127. FileName = fileName;
  128. }
  129. /// <summary>
  130. /// Gets the current file.
  131. /// </summary>
  132. public int CurrentFile { get; private set; }
  133. /// <summary>
  134. /// Gets the total files.
  135. /// </summary>
  136. public int TotalFiles { get; private set; }
  137. /// <summary>
  138. /// Gets the name of the file.
  139. /// </summary>
  140. public string FileName { get; private set; }
  141. }
  142. private const int EntrySignature = 0x02014B50;
  143. private const int FileSignature = 0x04034b50;
  144. private const int DirectorySignature = 0x06054B50;
  145. private const int BufferSize = 16 * 1024;
  146. /// <summary>
  147. /// Occurs when a file or a directory is extracted from an archive.
  148. /// </summary>
  149. public event EventHandler<FileProgressEventArgs> ExtractProgress;
  150. /// <summary>
  151. /// Initializes a new instance of the <see cref="Unzip" /> class.
  152. /// </summary>
  153. /// <param name="fileName">Name of the file.</param>
  154. public Unzip(string fileName)
  155. : this(File.OpenRead(fileName))
  156. {
  157. }
  158. /// <summary>
  159. /// Initializes a new instance of the <see cref="Unzip" /> class.
  160. /// </summary>
  161. /// <param name="stream">The stream.</param>
  162. public Unzip(Stream stream)
  163. {
  164. Stream = stream;
  165. Reader = new BinaryReader(Stream);
  166. }
  167. private Stream Stream { get; set; }
  168. private BinaryReader Reader { get; set; }
  169. /// <summary>
  170. /// Performs application-defined tasks associated with
  171. /// freeing, releasing, or resetting unmanaged resources.
  172. /// </summary>
  173. public void Dispose()
  174. {
  175. if (Stream != null)
  176. {
  177. Stream.Dispose();
  178. Stream = null;
  179. }
  180. if (Reader != null)
  181. {
  182. Reader.Close();
  183. Reader = null;
  184. }
  185. }
  186. /// <summary>
  187. /// Extracts the contents of the zip file to the given directory.
  188. /// </summary>
  189. /// <param name="directoryName">Name of the directory.</param>
  190. public void ExtractToDirectory(string directoryName)
  191. {
  192. for (int index = 0; index < Entries.Length; index++)
  193. {
  194. var entry = Entries[index];
  195. // create target directory for the file
  196. var fileName = Path.Combine(directoryName, entry.Name);
  197. var dirName = Path.GetDirectoryName(fileName);
  198. Directory.CreateDirectory(dirName);
  199. // save file if it is not only a directory
  200. if (!entry.IsDirectory)
  201. {
  202. Extract(entry.Name, fileName);
  203. }
  204. var extractProgress = ExtractProgress;
  205. if (extractProgress != null)
  206. {
  207. extractProgress(this, new FileProgressEventArgs(index + 1, Entries.Length, entry.Name));
  208. }
  209. }
  210. }
  211. /// <summary>
  212. /// Extracts the specified file to the specified name.
  213. /// </summary>
  214. /// <param name="fileName">Name of the file in zip archive.</param>
  215. /// <param name="outputFileName">Name of the output file.</param>
  216. public void Extract(string fileName, string outputFileName)
  217. {
  218. var entry = GetEntry(fileName);
  219. using (var outStream = File.Create(outputFileName))
  220. {
  221. Extract(entry, outStream);
  222. }
  223. var fileInfo = new FileInfo(outputFileName);
  224. if (fileInfo.Length != entry.OriginalSize)
  225. {
  226. throw new InvalidDataException(string.Format(
  227. "Corrupted archive: {0} has an uncompressed size {1} which does not match its expected size {2}",
  228. outputFileName, fileInfo.Length, entry.OriginalSize));
  229. }
  230. File.SetLastWriteTime(outputFileName, entry.Timestamp);
  231. }
  232. private Entry GetEntry(string fileName)
  233. {
  234. fileName = fileName.Replace("\\", "/").Trim().TrimStart('/');
  235. var entry = Entries.FirstOrDefault(e => e.Name == fileName);
  236. if (entry == null)
  237. {
  238. throw new FileNotFoundException("File not found in the archive: " + fileName);
  239. }
  240. return entry;
  241. }
  242. /// <summary>
  243. /// Extracts the specified file to the output <see cref="Stream"/>.
  244. /// </summary>
  245. /// <param name="fileName">Name of the file in zip archive.</param>
  246. /// <param name="outputStream">The output stream.</param>
  247. public void Extract(string fileName, Stream outputStream)
  248. {
  249. Extract(GetEntry(fileName), outputStream);
  250. }
  251. /// <summary>
  252. /// Extracts the specified entry.
  253. /// </summary>
  254. /// <param name="entry">Zip file entry to extract.</param>
  255. /// <param name="outputStream">The stream to write the data to.</param>
  256. /// <exception cref="System.InvalidOperationException"> is thrown when the file header signature doesn't match.</exception>
  257. public void Extract(Entry entry, Stream outputStream)
  258. {
  259. // check file signature
  260. Stream.Seek(entry.HeaderOffset, SeekOrigin.Begin);
  261. if (Reader.ReadInt32() != FileSignature)
  262. {
  263. throw new InvalidDataException("File signature doesn't match.");
  264. }
  265. // move to file data
  266. Stream.Seek(entry.DataOffset, SeekOrigin.Begin);
  267. var inputStream = Stream;
  268. if (entry.Deflated)
  269. {
  270. inputStream = new DeflateStream(Stream, CompressionMode.Decompress, true);
  271. }
  272. // allocate buffer, prepare for CRC32 calculation
  273. var count = entry.OriginalSize;
  274. var bufferSize = Math.Min(BufferSize, entry.OriginalSize);
  275. var buffer = new byte[bufferSize];
  276. var crc32Calculator = new Crc32Calculator();
  277. while (count > 0)
  278. {
  279. // decompress data
  280. var read = inputStream.Read(buffer, 0, bufferSize);
  281. if (read == 0)
  282. {
  283. break;
  284. }
  285. crc32Calculator.UpdateWithBlock(buffer, read);
  286. // copy to the output stream
  287. outputStream.Write(buffer, 0, read);
  288. count -= read;
  289. }
  290. if (crc32Calculator.Crc32 != entry.Crc32)
  291. {
  292. throw new InvalidDataException(string.Format(
  293. "Corrupted archive: CRC32 doesn't match on file {0}: expected {1:x8}, got {2:x8}.",
  294. entry.Name, entry.Crc32, crc32Calculator.Crc32));
  295. }
  296. }
  297. /// <summary>
  298. /// Gets the file names.
  299. /// </summary>
  300. public IEnumerable<string> FileNames
  301. {
  302. get
  303. {
  304. return Entries.Select(e => e.Name).Where(f => !f.EndsWith("/")).OrderBy(f => f);
  305. }
  306. }
  307. private Entry[] entries;
  308. /// <summary>
  309. /// Gets zip file entries.
  310. /// </summary>
  311. public Entry[] Entries
  312. {
  313. get
  314. {
  315. if (entries == null)
  316. {
  317. entries = ReadZipEntries().ToArray();
  318. }
  319. return entries;
  320. }
  321. }
  322. private IEnumerable<Entry> ReadZipEntries()
  323. {
  324. if (Stream.Length < 22)
  325. {
  326. yield break;
  327. }
  328. Stream.Seek(-22, SeekOrigin.End);
  329. // find directory signature
  330. while (Reader.ReadInt32() != DirectorySignature)
  331. {
  332. if (Stream.Position <= 5)
  333. {
  334. yield break;
  335. }
  336. // move 1 byte back
  337. Stream.Seek(-5, SeekOrigin.Current);
  338. }
  339. // read directory properties
  340. Stream.Seek(6, SeekOrigin.Current);
  341. var entries = Reader.ReadUInt16();
  342. var difSize = Reader.ReadInt32();
  343. var dirOffset = Reader.ReadUInt32();
  344. Stream.Seek(dirOffset, SeekOrigin.Begin);
  345. // read directory entries
  346. for (int i = 0; i < entries; i++)
  347. {
  348. if (Reader.ReadInt32() != EntrySignature)
  349. {
  350. continue;
  351. }
  352. // read file properties
  353. // TODO: Replace with a proper class to make this method a lot shorter.
  354. Reader.ReadInt32();
  355. bool utf8 = (Reader.ReadInt16() & 0x0800) != 0;
  356. short method = Reader.ReadInt16();
  357. int timestamp = Reader.ReadInt32();
  358. uint crc32 = Reader.ReadUInt32();
  359. int compressedSize = Reader.ReadInt32();
  360. int fileSize = Reader.ReadInt32();
  361. short fileNameSize = Reader.ReadInt16();
  362. short extraSize = Reader.ReadInt16();
  363. short commentSize = Reader.ReadInt16();
  364. int headerOffset = Reader.ReadInt32();
  365. Reader.ReadInt32();
  366. int fileHeaderOffset = Reader.ReadInt32();
  367. var fileNameBytes = Reader.ReadBytes(fileNameSize);
  368. Stream.Seek(extraSize, SeekOrigin.Current);
  369. var fileCommentBytes = Reader.ReadBytes(commentSize);
  370. var fileDataOffset = CalculateFileDataOffset(fileHeaderOffset);
  371. // decode zip file entry
  372. var encoder = utf8 ? Encoding.UTF8 : Encoding.Default;
  373. yield return new Entry
  374. {
  375. Name = encoder.GetString(fileNameBytes),
  376. Comment = encoder.GetString(fileCommentBytes),
  377. Crc32 = crc32,
  378. CompressedSize = compressedSize,
  379. OriginalSize = fileSize,
  380. HeaderOffset = fileHeaderOffset,
  381. DataOffset = fileDataOffset,
  382. Deflated = method == 8,
  383. Timestamp = ConvertToDateTime(timestamp)
  384. };
  385. }
  386. }
  387. private int CalculateFileDataOffset(int fileHeaderOffset)
  388. {
  389. var position = Stream.Position;
  390. Stream.Seek(fileHeaderOffset + 26, SeekOrigin.Begin);
  391. var fileNameSize = Reader.ReadInt16();
  392. var extraSize = Reader.ReadInt16();
  393. var fileOffset = (int)Stream.Position + fileNameSize + extraSize;
  394. Stream.Seek(position, SeekOrigin.Begin);
  395. return fileOffset;
  396. }
  397. /// <summary>
  398. /// Converts DOS timestamp to a <see cref="DateTime"/> instance.
  399. /// </summary>
  400. /// <param name="dosTimestamp">The dos timestamp.</param>
  401. /// <returns>The <see cref="DateTime"/> instance.</returns>
  402. public static DateTime ConvertToDateTime(int dosTimestamp)
  403. {
  404. return new DateTime((dosTimestamp >> 25) + 1980, (dosTimestamp >> 21) & 15, (dosTimestamp >> 16) & 31,
  405. (dosTimestamp >> 11) & 31, (dosTimestamp >> 5) & 63, (dosTimestamp & 31) * 2);
  406. }
  407. }
  408. }