ZipEntry.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. using System;
  2. using System.IO;
  3. namespace System.Net.ApiService.Compression.Zip {
  4. /// <summary>
  5. /// Defines known values for the <see cref="HostSystemID"/> property.
  6. /// </summary>
  7. public enum HostSystemID
  8. {
  9. /// <summary>
  10. /// Host system = MSDOS
  11. /// </summary>
  12. Msdos = 0,
  13. /// <summary>
  14. /// Host system = Amiga
  15. /// </summary>
  16. Amiga = 1,
  17. /// <summary>
  18. /// Host system = Open VMS
  19. /// </summary>
  20. OpenVms = 2,
  21. /// <summary>
  22. /// Host system = Unix
  23. /// </summary>
  24. Unix = 3,
  25. /// <summary>
  26. /// Host system = VMCms
  27. /// </summary>
  28. VMCms = 4,
  29. /// <summary>
  30. /// Host system = Atari ST
  31. /// </summary>
  32. AtariST = 5,
  33. /// <summary>
  34. /// Host system = OS2
  35. /// </summary>
  36. OS2 = 6,
  37. /// <summary>
  38. /// Host system = Macintosh
  39. /// </summary>
  40. Macintosh = 7,
  41. /// <summary>
  42. /// Host system = ZSystem
  43. /// </summary>
  44. ZSystem = 8,
  45. /// <summary>
  46. /// Host system = Cpm
  47. /// </summary>
  48. Cpm = 9,
  49. /// <summary>
  50. /// Host system = Windows NT
  51. /// </summary>
  52. WindowsNT = 10,
  53. /// <summary>
  54. /// Host system = MVS
  55. /// </summary>
  56. MVS = 11,
  57. /// <summary>
  58. /// Host system = VSE
  59. /// </summary>
  60. Vse = 12,
  61. /// <summary>
  62. /// Host system = Acorn RISC
  63. /// </summary>
  64. AcornRisc = 13,
  65. /// <summary>
  66. /// Host system = VFAT
  67. /// </summary>
  68. Vfat = 14,
  69. /// <summary>
  70. /// Host system = Alternate MVS
  71. /// </summary>
  72. AlternateMvs = 15,
  73. /// <summary>
  74. /// Host system = BEOS
  75. /// </summary>
  76. BeOS = 16,
  77. /// <summary>
  78. /// Host system = Tandem
  79. /// </summary>
  80. Tandem = 17,
  81. /// <summary>
  82. /// Host system = OS400
  83. /// </summary>
  84. OS400 = 18,
  85. /// <summary>
  86. /// Host system = OSX
  87. /// </summary>
  88. OSX = 19,
  89. /// <summary>
  90. /// Host system = WinZIP AES
  91. /// </summary>
  92. WinZipAES = 99,
  93. }
  94. /// <summary>
  95. /// This class represents an entry in a zip archive. This can be a file
  96. /// or a directory
  97. /// ZipFile and ZipInputStream will give you instances of this class as
  98. /// information about the members in an archive. ZipOutputStream
  99. /// uses an instance of this class when creating an entry in a Zip file.
  100. /// <br/>
  101. /// <br/>Author of the original java version : Jochen Hoenicke
  102. /// </summary>
  103. public class ZipEntry
  104. {
  105. [Flags]
  106. private enum Known : byte
  107. {
  108. None = 0,
  109. Size = 0x01,
  110. CompressedSize = 0x02,
  111. Crc = 0x04,
  112. Time = 0x08,
  113. ExternalAttributes = 0x10,
  114. }
  115. #region Constructors
  116. /// <summary>
  117. /// Creates a zip entry with the given name.
  118. /// </summary>
  119. /// <param name="name">
  120. /// The name for this entry. Can include directory components.
  121. /// The convention for names is 'unix' style paths with relative names only.
  122. /// There are with no device names and path elements are separated by '/' characters.
  123. /// </param>
  124. /// <exception cref="ArgumentNullException">
  125. /// The name passed is null
  126. /// </exception>
  127. public ZipEntry(string name)
  128. : this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated)
  129. {
  130. }
  131. /// <summary>
  132. /// Creates a zip entry with the given name and version required to extract
  133. /// </summary>
  134. /// <param name="name">
  135. /// The name for this entry. Can include directory components.
  136. /// The convention for names is 'unix' style paths with no device names and
  137. /// path elements separated by '/' characters. This is not enforced see <see cref="CleanName(string)">CleanName</see>
  138. /// on how to ensure names are valid if this is desired.
  139. /// </param>
  140. /// <param name="versionRequiredToExtract">
  141. /// The minimum 'feature version' required this entry
  142. /// </param>
  143. /// <exception cref="ArgumentNullException">
  144. /// The name passed is null
  145. /// </exception>
  146. internal ZipEntry(string name, int versionRequiredToExtract)
  147. : this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy,
  148. CompressionMethod.Deflated)
  149. {
  150. }
  151. /// <summary>
  152. /// Initializes an entry with the given name and made by information
  153. /// </summary>
  154. /// <param name="name">Name for this entry</param>
  155. /// <param name="madeByInfo">Version and HostSystem Information</param>
  156. /// <param name="versionRequiredToExtract">Minimum required zip feature version required to extract this entry</param>
  157. /// <param name="method">Compression method for this entry.</param>
  158. /// <exception cref="ArgumentNullException">
  159. /// The name passed is null
  160. /// </exception>
  161. /// <exception cref="ArgumentOutOfRangeException">
  162. /// versionRequiredToExtract should be 0 (auto-calculate) or > 10
  163. /// </exception>
  164. /// <remarks>
  165. /// This constructor is used by the ZipFile class when reading from the central header
  166. /// It is not generally useful, use the constructor specifying the name only.
  167. /// </remarks>
  168. internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo,
  169. CompressionMethod method)
  170. {
  171. if (name == null)
  172. {
  173. throw new ArgumentNullException(nameof(name));
  174. }
  175. if (name.Length > 0xffff)
  176. {
  177. throw new ArgumentException("Name is too long", nameof(name));
  178. }
  179. if ((versionRequiredToExtract != 0) && (versionRequiredToExtract < 10))
  180. {
  181. throw new ArgumentOutOfRangeException(nameof(versionRequiredToExtract));
  182. }
  183. this.DateTime = DateTime.Now;
  184. this.name = name;
  185. this.versionMadeBy = (ushort)madeByInfo;
  186. this.versionToExtract = (ushort)versionRequiredToExtract;
  187. this.method = method;
  188. IsUnicodeText = ZipStrings.UseUnicode;
  189. }
  190. /// <summary>
  191. /// Creates a deep copy of the given zip entry.
  192. /// </summary>
  193. /// <param name="entry">
  194. /// The entry to copy.
  195. /// </param>
  196. [Obsolete("Use Clone instead")]
  197. public ZipEntry(ZipEntry entry)
  198. {
  199. if (entry == null)
  200. {
  201. throw new ArgumentNullException(nameof(entry));
  202. }
  203. known = entry.known;
  204. name = entry.name;
  205. size = entry.size;
  206. compressedSize = entry.compressedSize;
  207. crc = entry.crc;
  208. dosTime = entry.dosTime;
  209. method = entry.method;
  210. comment = entry.comment;
  211. versionToExtract = entry.versionToExtract;
  212. versionMadeBy = entry.versionMadeBy;
  213. externalFileAttributes = entry.externalFileAttributes;
  214. flags = entry.flags;
  215. zipFileIndex = entry.zipFileIndex;
  216. offset = entry.offset;
  217. forceZip64_ = entry.forceZip64_;
  218. if (entry.extra != null)
  219. {
  220. extra = new byte[entry.extra.Length];
  221. Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length);
  222. }
  223. }
  224. #endregion Constructors
  225. /// <summary>
  226. /// Get a value indicating wether the entry has a CRC value available.
  227. /// </summary>
  228. public bool HasCrc
  229. {
  230. get
  231. {
  232. return (known & Known.Crc) != 0;
  233. }
  234. }
  235. /// <summary>
  236. /// Get/Set flag indicating if entry is encrypted.
  237. /// A simple helper routine to aid interpretation of <see cref="Flags">flags</see>
  238. /// </summary>
  239. /// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
  240. public bool IsCrypted
  241. {
  242. get
  243. {
  244. return (flags & 1) != 0;
  245. }
  246. set
  247. {
  248. if (value)
  249. {
  250. flags |= 1;
  251. }
  252. else
  253. {
  254. flags &= ~1;
  255. }
  256. }
  257. }
  258. /// <summary>
  259. /// Get / set a flag indicating wether entry name and comment text are
  260. /// encoded in <a href="http://www.unicode.org">unicode UTF8</a>.
  261. /// </summary>
  262. /// <remarks>This is an assistant that interprets the <see cref="Flags">flags</see> property.</remarks>
  263. public bool IsUnicodeText
  264. {
  265. get
  266. {
  267. return (flags & (int)GeneralBitFlags.UnicodeText) != 0;
  268. }
  269. set
  270. {
  271. if (value)
  272. {
  273. flags |= (int)GeneralBitFlags.UnicodeText;
  274. }
  275. else
  276. {
  277. flags &= ~(int)GeneralBitFlags.UnicodeText;
  278. }
  279. }
  280. }
  281. /// <summary>
  282. /// Value used during password checking for PKZIP 2.0 / 'classic' encryption.
  283. /// </summary>
  284. internal byte CryptoCheckValue
  285. {
  286. get
  287. {
  288. return cryptoCheckValue_;
  289. }
  290. set
  291. {
  292. cryptoCheckValue_ = value;
  293. }
  294. }
  295. /// <summary>
  296. /// Get/Set general purpose bit flag for entry
  297. /// </summary>
  298. /// <remarks>
  299. /// General purpose bit flag<br/>
  300. /// <br/>
  301. /// Bit 0: If set, indicates the file is encrypted<br/>
  302. /// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating<br/>
  303. /// Imploding:<br/>
  304. /// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used<br/>
  305. /// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise<br/>
  306. /// <br/>
  307. /// Deflating:<br/>
  308. /// Bit 2 Bit 1<br/>
  309. /// 0 0 Normal compression was used<br/>
  310. /// 0 1 Maximum compression was used<br/>
  311. /// 1 0 Fast compression was used<br/>
  312. /// 1 1 Super fast compression was used<br/>
  313. /// <br/>
  314. /// Bit 3: If set, the fields crc-32, compressed size
  315. /// and uncompressed size are were not able to be written during zip file creation
  316. /// The correct values are held in a data descriptor immediately following the compressed data. <br/>
  317. /// Bit 4: Reserved for use by PKZIP for enhanced deflating<br/>
  318. /// Bit 5: If set indicates the file contains compressed patch data<br/>
  319. /// Bit 6: If set indicates strong encryption was used.<br/>
  320. /// Bit 7-10: Unused or reserved<br/>
  321. /// Bit 11: If set the name and comments for this entry are in <a href="http://www.unicode.org">unicode</a>.<br/>
  322. /// Bit 12-15: Unused or reserved<br/>
  323. /// </remarks>
  324. /// <seealso cref="IsUnicodeText"></seealso>
  325. /// <seealso cref="IsCrypted"></seealso>
  326. public int Flags
  327. {
  328. get
  329. {
  330. return flags;
  331. }
  332. set
  333. {
  334. flags = value;
  335. }
  336. }
  337. /// <summary>
  338. /// Get/Set index of this entry in Zip file
  339. /// </summary>
  340. /// <remarks>This is only valid when the entry is part of a <see cref="ZipFile"></see></remarks>
  341. public long ZipFileIndex
  342. {
  343. get
  344. {
  345. return zipFileIndex;
  346. }
  347. set
  348. {
  349. zipFileIndex = value;
  350. }
  351. }
  352. /// <summary>
  353. /// Get/set offset for use in central header
  354. /// </summary>
  355. public long Offset
  356. {
  357. get
  358. {
  359. return offset;
  360. }
  361. set
  362. {
  363. offset = value;
  364. }
  365. }
  366. /// <summary>
  367. /// Get/Set external file attributes as an integer.
  368. /// The values of this are operating system dependant see
  369. /// <see cref="HostSystem">HostSystem</see> for details
  370. /// </summary>
  371. public int ExternalFileAttributes
  372. {
  373. get
  374. {
  375. if ((known & Known.ExternalAttributes) == 0)
  376. {
  377. return -1;
  378. }
  379. else
  380. {
  381. return externalFileAttributes;
  382. }
  383. }
  384. set
  385. {
  386. externalFileAttributes = value;
  387. known |= Known.ExternalAttributes;
  388. }
  389. }
  390. /// <summary>
  391. /// Get the version made by for this entry or zero if unknown.
  392. /// The value / 10 indicates the major version number, and
  393. /// the value mod 10 is the minor version number
  394. /// </summary>
  395. public int VersionMadeBy
  396. {
  397. get
  398. {
  399. return (versionMadeBy & 0xff);
  400. }
  401. }
  402. /// <summary>
  403. /// Get a value indicating this entry is for a DOS/Windows system.
  404. /// </summary>
  405. public bool IsDOSEntry
  406. {
  407. get
  408. {
  409. return ((HostSystem == (int)HostSystemID.Msdos) ||
  410. (HostSystem == (int)HostSystemID.WindowsNT));
  411. }
  412. }
  413. /// <summary>
  414. /// Test the external attributes for this <see cref="ZipEntry"/> to
  415. /// see if the external attributes are Dos based (including WINNT and variants)
  416. /// and match the values
  417. /// </summary>
  418. /// <param name="attributes">The attributes to test.</param>
  419. /// <returns>Returns true if the external attributes are known to be DOS/Windows
  420. /// based and have the same attributes set as the value passed.</returns>
  421. private bool HasDosAttributes(int attributes)
  422. {
  423. bool result = false;
  424. if ((known & Known.ExternalAttributes) != 0)
  425. {
  426. result |= (((HostSystem == (int)HostSystemID.Msdos) ||
  427. (HostSystem == (int)HostSystemID.WindowsNT)) &&
  428. (ExternalFileAttributes & attributes) == attributes);
  429. }
  430. return result;
  431. }
  432. /// <summary>
  433. /// Gets the compatability information for the <see cref="ExternalFileAttributes">external file attribute</see>
  434. /// If the external file attributes are compatible with MS-DOS and can be read
  435. /// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value
  436. /// will be non-zero and identify the host system on which the attributes are compatible.
  437. /// </summary>
  438. ///
  439. /// <remarks>
  440. /// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat
  441. /// misleading in some cases as they are not all used as shown. You should consult the relevant documentation
  442. /// to obtain up to date and correct information. The modified appnote by the infozip group is
  443. /// particularly helpful as it documents a lot of peculiarities. The document is however a little dated.
  444. /// <list type="table">
  445. /// <item>0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)</item>
  446. /// <item>1 - Amiga</item>
  447. /// <item>2 - OpenVMS</item>
  448. /// <item>3 - Unix</item>
  449. /// <item>4 - VM/CMS</item>
  450. /// <item>5 - Atari ST</item>
  451. /// <item>6 - OS/2 HPFS</item>
  452. /// <item>7 - Macintosh</item>
  453. /// <item>8 - Z-System</item>
  454. /// <item>9 - CP/M</item>
  455. /// <item>10 - Windows NTFS</item>
  456. /// <item>11 - MVS (OS/390 - Z/OS)</item>
  457. /// <item>12 - VSE</item>
  458. /// <item>13 - Acorn Risc</item>
  459. /// <item>14 - VFAT</item>
  460. /// <item>15 - Alternate MVS</item>
  461. /// <item>16 - BeOS</item>
  462. /// <item>17 - Tandem</item>
  463. /// <item>18 - OS/400</item>
  464. /// <item>19 - OS/X (Darwin)</item>
  465. /// <item>99 - WinZip AES</item>
  466. /// <item>remainder - unused</item>
  467. /// </list>
  468. /// </remarks>
  469. public int HostSystem
  470. {
  471. get
  472. {
  473. return (versionMadeBy >> 8) & 0xff;
  474. }
  475. set
  476. {
  477. versionMadeBy &= 0x00ff;
  478. versionMadeBy |= (ushort)((value & 0xff) << 8);
  479. }
  480. }
  481. /// <summary>
  482. /// Get minimum Zip feature version required to extract this entry
  483. /// </summary>
  484. /// <remarks>
  485. /// Minimum features are defined as:<br/>
  486. /// 1.0 - Default value<br/>
  487. /// 1.1 - File is a volume label<br/>
  488. /// 2.0 - File is a folder/directory<br/>
  489. /// 2.0 - File is compressed using Deflate compression<br/>
  490. /// 2.0 - File is encrypted using traditional encryption<br/>
  491. /// 2.1 - File is compressed using Deflate64<br/>
  492. /// 2.5 - File is compressed using PKWARE DCL Implode<br/>
  493. /// 2.7 - File is a patch data set<br/>
  494. /// 4.5 - File uses Zip64 format extensions<br/>
  495. /// 4.6 - File is compressed using BZIP2 compression<br/>
  496. /// 5.0 - File is encrypted using DES<br/>
  497. /// 5.0 - File is encrypted using 3DES<br/>
  498. /// 5.0 - File is encrypted using original RC2 encryption<br/>
  499. /// 5.0 - File is encrypted using RC4 encryption<br/>
  500. /// 5.1 - File is encrypted using AES encryption<br/>
  501. /// 5.1 - File is encrypted using corrected RC2 encryption<br/>
  502. /// 5.1 - File is encrypted using corrected RC2-64 encryption<br/>
  503. /// 6.1 - File is encrypted using non-OAEP key wrapping<br/>
  504. /// 6.2 - Central directory encryption (not confirmed yet)<br/>
  505. /// 6.3 - File is compressed using LZMA<br/>
  506. /// 6.3 - File is compressed using PPMD+<br/>
  507. /// 6.3 - File is encrypted using Blowfish<br/>
  508. /// 6.3 - File is encrypted using Twofish<br/>
  509. /// </remarks>
  510. /// <seealso cref="CanDecompress"></seealso>
  511. public int Version
  512. {
  513. get
  514. {
  515. // Return recorded version if known.
  516. if (versionToExtract != 0)
  517. {
  518. return versionToExtract & 0x00ff; // Only lower order byte. High order is O/S file system.
  519. }
  520. else
  521. {
  522. int result = 10;
  523. if (AESKeySize > 0)
  524. {
  525. result = ZipConstants.VERSION_AES; // Ver 5.1 = AES
  526. }
  527. else if (CentralHeaderRequiresZip64)
  528. {
  529. result = ZipConstants.VersionZip64;
  530. }
  531. else if (CompressionMethod.Deflated == method)
  532. {
  533. result = 20;
  534. }
  535. else if (IsDirectory == true)
  536. {
  537. result = 20;
  538. }
  539. else if (IsCrypted == true)
  540. {
  541. result = 20;
  542. }
  543. else if (HasDosAttributes(0x08))
  544. {
  545. result = 11;
  546. }
  547. return result;
  548. }
  549. }
  550. }
  551. /// <summary>
  552. /// Get a value indicating whether this entry can be decompressed by the library.
  553. /// </summary>
  554. /// <remarks>This is based on the <see cref="Version"></see> and
  555. /// wether the <see cref="IsCompressionMethodSupported()">compression method</see> is supported.</remarks>
  556. public bool CanDecompress
  557. {
  558. get
  559. {
  560. return (Version <= ZipConstants.VersionMadeBy) &&
  561. ((Version == 10) ||
  562. (Version == 11) ||
  563. (Version == 20) ||
  564. (Version == 45) ||
  565. (Version == 51)) &&
  566. IsCompressionMethodSupported();
  567. }
  568. }
  569. /// <summary>
  570. /// Force this entry to be recorded using Zip64 extensions.
  571. /// </summary>
  572. public void ForceZip64()
  573. {
  574. forceZip64_ = true;
  575. }
  576. /// <summary>
  577. /// Get a value indicating wether Zip64 extensions were forced.
  578. /// </summary>
  579. /// <returns>A <see cref="bool"/> value of true if Zip64 extensions have been forced on; false if not.</returns>
  580. public bool IsZip64Forced()
  581. {
  582. return forceZip64_;
  583. }
  584. /// <summary>
  585. /// Gets a value indicating if the entry requires Zip64 extensions
  586. /// to store the full entry values.
  587. /// </summary>
  588. /// <value>A <see cref="bool"/> value of true if a local header requires Zip64 extensions; false if not.</value>
  589. public bool LocalHeaderRequiresZip64
  590. {
  591. get
  592. {
  593. bool result = forceZip64_;
  594. if (!result)
  595. {
  596. ulong trueCompressedSize = compressedSize;
  597. if ((versionToExtract == 0) && IsCrypted)
  598. {
  599. trueCompressedSize += ZipConstants.CryptoHeaderSize;
  600. }
  601. // TODO: A better estimation of the true limit based on compression overhead should be used
  602. // to determine when an entry should use Zip64.
  603. result =
  604. ((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) &&
  605. ((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64));
  606. }
  607. return result;
  608. }
  609. }
  610. /// <summary>
  611. /// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored.
  612. /// </summary>
  613. public bool CentralHeaderRequiresZip64
  614. {
  615. get
  616. {
  617. return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue);
  618. }
  619. }
  620. /// <summary>
  621. /// Get/Set DosTime value.
  622. /// </summary>
  623. /// <remarks>
  624. /// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107.
  625. /// </remarks>
  626. public long DosTime
  627. {
  628. get
  629. {
  630. if ((known & Known.Time) == 0)
  631. {
  632. return 0;
  633. }
  634. else
  635. {
  636. return dosTime;
  637. }
  638. }
  639. set
  640. {
  641. unchecked
  642. {
  643. dosTime = (uint)value;
  644. }
  645. known |= Known.Time;
  646. }
  647. }
  648. /// <summary>
  649. /// Gets/Sets the time of last modification of the entry.
  650. /// </summary>
  651. /// <remarks>
  652. /// The <see cref="DosTime"></see> property is updated to match this as far as possible.
  653. /// </remarks>
  654. public DateTime DateTime
  655. {
  656. get
  657. {
  658. uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
  659. uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
  660. uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
  661. uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
  662. uint year = ((dosTime >> 25) & 0x7f) + 1980;
  663. int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
  664. return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec);
  665. }
  666. set
  667. {
  668. var year = (uint)value.Year;
  669. var month = (uint)value.Month;
  670. var day = (uint)value.Day;
  671. var hour = (uint)value.Hour;
  672. var minute = (uint)value.Minute;
  673. var second = (uint)value.Second;
  674. if (year < 1980)
  675. {
  676. year = 1980;
  677. month = 1;
  678. day = 1;
  679. hour = 0;
  680. minute = 0;
  681. second = 0;
  682. }
  683. else if (year > 2107)
  684. {
  685. year = 2107;
  686. month = 12;
  687. day = 31;
  688. hour = 23;
  689. minute = 59;
  690. second = 59;
  691. }
  692. DosTime = ((year - 1980) & 0x7f) << 25 |
  693. (month << 21) |
  694. (day << 16) |
  695. (hour << 11) |
  696. (minute << 5) |
  697. (second >> 1);
  698. }
  699. }
  700. /// <summary>
  701. /// Returns the entry name.
  702. /// </summary>
  703. /// <remarks>
  704. /// The unix naming convention is followed.
  705. /// Path components in the entry should always separated by forward slashes ('/').
  706. /// Dos device names like C: should also be removed.
  707. /// See the <see cref="ZipNameTransform"/> class, or <see cref="CleanName(string)"/>
  708. ///</remarks>
  709. public string Name
  710. {
  711. get
  712. {
  713. return name;
  714. }
  715. }
  716. /// <summary>
  717. /// Gets/Sets the size of the uncompressed data.
  718. /// </summary>
  719. /// <returns>
  720. /// The size or -1 if unknown.
  721. /// </returns>
  722. /// <remarks>Setting the size before adding an entry to an archive can help
  723. /// avoid compatability problems with some archivers which dont understand Zip64 extensions.</remarks>
  724. public long Size
  725. {
  726. get
  727. {
  728. return (known & Known.Size) != 0 ? (long)size : -1L;
  729. }
  730. set
  731. {
  732. this.size = (ulong)value;
  733. this.known |= Known.Size;
  734. }
  735. }
  736. /// <summary>
  737. /// Gets/Sets the size of the compressed data.
  738. /// </summary>
  739. /// <returns>
  740. /// The compressed entry size or -1 if unknown.
  741. /// </returns>
  742. public long CompressedSize
  743. {
  744. get
  745. {
  746. return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L;
  747. }
  748. set
  749. {
  750. this.compressedSize = (ulong)value;
  751. this.known |= Known.CompressedSize;
  752. }
  753. }
  754. /// <summary>
  755. /// Gets/Sets the crc of the uncompressed data.
  756. /// </summary>
  757. /// <exception cref="System.ArgumentOutOfRangeException">
  758. /// Crc is not in the range 0..0xffffffffL
  759. /// </exception>
  760. /// <returns>
  761. /// The crc value or -1 if unknown.
  762. /// </returns>
  763. public long Crc
  764. {
  765. get
  766. {
  767. return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L;
  768. }
  769. set
  770. {
  771. if (((ulong)crc & 0xffffffff00000000L) != 0)
  772. {
  773. throw new ArgumentOutOfRangeException(nameof(value));
  774. }
  775. this.crc = (uint)value;
  776. this.known |= Known.Crc;
  777. }
  778. }
  779. /// <summary>
  780. /// Gets/Sets the compression method. Only Deflated and Stored are supported.
  781. /// </summary>
  782. /// <returns>
  783. /// The compression method for this entry
  784. /// </returns>
  785. /// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated"/>
  786. /// <see cref="ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored"/>
  787. public CompressionMethod CompressionMethod
  788. {
  789. get
  790. {
  791. return method;
  792. }
  793. set
  794. {
  795. if (!IsCompressionMethodSupported(value))
  796. {
  797. throw new NotSupportedException("Compression method not supported");
  798. }
  799. this.method = value;
  800. }
  801. }
  802. /// <summary>
  803. /// Gets the compression method for outputting to the local or central header.
  804. /// Returns same value as CompressionMethod except when AES encrypting, which
  805. /// places 99 in the method and places the real method in the extra data.
  806. /// </summary>
  807. internal CompressionMethod CompressionMethodForHeader
  808. {
  809. get
  810. {
  811. return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method;
  812. }
  813. }
  814. /// <summary>
  815. /// Gets/Sets the extra data.
  816. /// </summary>
  817. /// <exception cref="System.ArgumentOutOfRangeException">
  818. /// Extra data is longer than 64KB (0xffff) bytes.
  819. /// </exception>
  820. /// <returns>
  821. /// Extra data or null if not set.
  822. /// </returns>
  823. public byte[] ExtraData
  824. {
  825. get
  826. {
  827. // TODO: This is slightly safer but less efficient. Think about wether it should change.
  828. // return (byte[]) extra.Clone();
  829. return extra;
  830. }
  831. set
  832. {
  833. if (value == null)
  834. {
  835. extra = null;
  836. }
  837. else
  838. {
  839. if (value.Length > 0xffff)
  840. {
  841. throw new System.ArgumentOutOfRangeException(nameof(value));
  842. }
  843. extra = new byte[value.Length];
  844. Array.Copy(value, 0, extra, 0, value.Length);
  845. }
  846. }
  847. }
  848. /// <summary>
  849. /// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256).
  850. /// When setting, only 0 (off), 128 or 256 is supported.
  851. /// </summary>
  852. public int AESKeySize
  853. {
  854. get
  855. {
  856. // the strength (1 or 3) is in the entry header
  857. switch (_aesEncryptionStrength)
  858. {
  859. case 0:
  860. return 0; // Not AES
  861. case 1:
  862. return 128;
  863. case 2:
  864. return 192; // Not used by WinZip
  865. case 3:
  866. return 256;
  867. default:
  868. throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength);
  869. }
  870. }
  871. set
  872. {
  873. switch (value)
  874. {
  875. case 0:
  876. _aesEncryptionStrength = 0;
  877. break;
  878. case 128:
  879. _aesEncryptionStrength = 1;
  880. break;
  881. case 256:
  882. _aesEncryptionStrength = 3;
  883. break;
  884. default:
  885. throw new ZipException("AESKeySize must be 0, 128 or 256: " + value);
  886. }
  887. }
  888. }
  889. /// <summary>
  890. /// AES Encryption strength for storage in extra data in entry header.
  891. /// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit.
  892. /// </summary>
  893. internal byte AESEncryptionStrength
  894. {
  895. get
  896. {
  897. return (byte)_aesEncryptionStrength;
  898. }
  899. }
  900. /// <summary>
  901. /// Returns the length of the salt, in bytes
  902. /// </summary>
  903. internal int AESSaltLen
  904. {
  905. get
  906. {
  907. // Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes.
  908. return AESKeySize / 16;
  909. }
  910. }
  911. /// <summary>
  912. /// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode)
  913. /// </summary>
  914. internal int AESOverheadSize
  915. {
  916. get
  917. {
  918. // File format:
  919. // Bytes Content
  920. // Variable Salt value
  921. // 2 Password verification value
  922. // Variable Encrypted file data
  923. // 10 Authentication code
  924. return 12 + AESSaltLen;
  925. }
  926. }
  927. /// <summary>
  928. /// Process extra data fields updating the entry based on the contents.
  929. /// </summary>
  930. /// <param name="localHeader">True if the extra data fields should be handled
  931. /// for a local header, rather than for a central header.
  932. /// </param>
  933. internal void ProcessExtraData(bool localHeader)
  934. {
  935. var extraData = new ZipExtraData(this.extra);
  936. if (extraData.Find(0x0001))
  937. {
  938. // Version required to extract is ignored here as some archivers dont set it correctly
  939. // in theory it should be version 45 or higher
  940. // The recorded size will change but remember that this is zip64.
  941. forceZip64_ = true;
  942. if (extraData.ValueLength < 4)
  943. {
  944. throw new ZipException("Extra data extended Zip64 information length is invalid");
  945. }
  946. // (localHeader ||) was deleted, because actually there is no specific difference with reading sizes between local header & central directory
  947. // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
  948. // ...
  949. // 4.4 Explanation of fields
  950. // ...
  951. // 4.4.8 compressed size: (4 bytes)
  952. // 4.4.9 uncompressed size: (4 bytes)
  953. //
  954. // The size of the file compressed (4.4.8) and uncompressed,
  955. // (4.4.9) respectively. When a decryption header is present it
  956. // will be placed in front of the file data and the value of the
  957. // compressed file size will include the bytes of the decryption
  958. // header. If bit 3 of the general purpose bit flag is set,
  959. // these fields are set to zero in the local header and the
  960. // correct values are put in the data descriptor and
  961. // in the central directory. If an archive is in ZIP64 format
  962. // and the value in this field is 0xFFFFFFFF, the size will be
  963. // in the corresponding 8 byte ZIP64 extended information
  964. // extra field. When encrypting the central directory, if the
  965. // local header is not in ZIP64 format and general purpose bit
  966. // flag 13 is set indicating masking, the value stored for the
  967. // uncompressed size in the Local Header will be zero.
  968. //
  969. // Othewise there is problem with minizip implementation
  970. if (size == uint.MaxValue)
  971. {
  972. size = (ulong)extraData.ReadLong();
  973. }
  974. if (compressedSize == uint.MaxValue)
  975. {
  976. compressedSize = (ulong)extraData.ReadLong();
  977. }
  978. if (!localHeader && (offset == uint.MaxValue))
  979. {
  980. offset = extraData.ReadLong();
  981. }
  982. // Disk number on which file starts is ignored
  983. }
  984. else
  985. {
  986. if (
  987. ((versionToExtract & 0xff) >= ZipConstants.VersionZip64) &&
  988. ((size == uint.MaxValue) || (compressedSize == uint.MaxValue))
  989. )
  990. {
  991. throw new ZipException("Zip64 Extended information required but is missing.");
  992. }
  993. }
  994. DateTime = GetDateTime(extraData);
  995. if (method == CompressionMethod.WinZipAES)
  996. {
  997. ProcessAESExtraData(extraData);
  998. }
  999. }
  1000. private DateTime GetDateTime(ZipExtraData extraData)
  1001. {
  1002. // Check for NT timestamp
  1003. // NOTE: Disable by default to match behavior of InfoZIP
  1004. #if RESPECT_NT_TIMESTAMP
  1005. NTTaggedData ntData = extraData.GetData<NTTaggedData>();
  1006. if (ntData != null)
  1007. return ntData.LastModificationTime;
  1008. #endif
  1009. // Check for Unix timestamp
  1010. ExtendedUnixData unixData = extraData.GetData<ExtendedUnixData>();
  1011. if (unixData != null &&
  1012. // Only apply modification time, but require all other values to be present
  1013. // This is done to match InfoZIP's behaviour
  1014. ((unixData.Include & ExtendedUnixData.Flags.ModificationTime) != 0) &&
  1015. ((unixData.Include & ExtendedUnixData.Flags.AccessTime) != 0) &&
  1016. ((unixData.Include & ExtendedUnixData.Flags.CreateTime) != 0))
  1017. return unixData.ModificationTime;
  1018. // Fall back to DOS time
  1019. uint sec = Math.Min(59, 2 * (dosTime & 0x1f));
  1020. uint min = Math.Min(59, (dosTime >> 5) & 0x3f);
  1021. uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f);
  1022. uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf)));
  1023. uint year = ((dosTime >> 25) & 0x7f) + 1980;
  1024. int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f)));
  1025. return new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc);
  1026. }
  1027. // For AES the method in the entry is 99, and the real compression method is in the extradata
  1028. //
  1029. private void ProcessAESExtraData(ZipExtraData extraData)
  1030. {
  1031. if (extraData.Find(0x9901))
  1032. {
  1033. // Set version for Zipfile.CreateAndInitDecryptionStream
  1034. versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter
  1035. //
  1036. // Unpack AES extra data field see http://www.winzip.com/aes_info.htm
  1037. int length = extraData.ValueLength; // Data size currently 7
  1038. if (length < 7)
  1039. throw new ZipException("AES Extra Data Length " + length + " invalid.");
  1040. int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2)
  1041. int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE"
  1042. int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256
  1043. int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file
  1044. _aesVer = ver;
  1045. _aesEncryptionStrength = encrStrength;
  1046. method = (CompressionMethod)actualCompress;
  1047. }
  1048. else
  1049. throw new ZipException("AES Extra Data missing");
  1050. }
  1051. /// <summary>
  1052. /// Gets/Sets the entry comment.
  1053. /// </summary>
  1054. /// <exception cref="System.ArgumentOutOfRangeException">
  1055. /// If comment is longer than 0xffff.
  1056. /// </exception>
  1057. /// <returns>
  1058. /// The comment or null if not set.
  1059. /// </returns>
  1060. /// <remarks>
  1061. /// A comment is only available for entries when read via the <see cref="ZipFile"/> class.
  1062. /// The <see cref="ZipInputStream"/> class doesnt have the comment data available.
  1063. /// </remarks>
  1064. public string Comment
  1065. {
  1066. get
  1067. {
  1068. return comment;
  1069. }
  1070. set
  1071. {
  1072. // This test is strictly incorrect as the length is in characters
  1073. // while the storage limit is in bytes.
  1074. // While the test is partially correct in that a comment of this length or greater
  1075. // is definitely invalid, shorter comments may also have an invalid length
  1076. // where there are multi-byte characters
  1077. // The full test is not possible here however as the code page to apply conversions with
  1078. // isnt available.
  1079. if ((value != null) && (value.Length > 0xffff))
  1080. {
  1081. throw new ArgumentOutOfRangeException(nameof(value), "cannot exceed 65535");
  1082. }
  1083. comment = value;
  1084. }
  1085. }
  1086. /// <summary>
  1087. /// Gets a value indicating if the entry is a directory.
  1088. /// however.
  1089. /// </summary>
  1090. /// <remarks>
  1091. /// A directory is determined by an entry name with a trailing slash '/'.
  1092. /// The external file attributes can also indicate an entry is for a directory.
  1093. /// Currently only dos/windows attributes are tested in this manner.
  1094. /// The trailing slash convention should always be followed.
  1095. /// </remarks>
  1096. public bool IsDirectory
  1097. {
  1098. get
  1099. {
  1100. int nameLength = name.Length;
  1101. bool result =
  1102. ((nameLength > 0) &&
  1103. ((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) ||
  1104. HasDosAttributes(16)
  1105. ;
  1106. return result;
  1107. }
  1108. }
  1109. /// <summary>
  1110. /// Get a value of true if the entry appears to be a file; false otherwise
  1111. /// </summary>
  1112. /// <remarks>
  1113. /// This only takes account of DOS/Windows attributes. Other operating systems are ignored.
  1114. /// For linux and others the result may be incorrect.
  1115. /// </remarks>
  1116. public bool IsFile
  1117. {
  1118. get
  1119. {
  1120. return !IsDirectory && !HasDosAttributes(8);
  1121. }
  1122. }
  1123. /// <summary>
  1124. /// Test entry to see if data can be extracted.
  1125. /// </summary>
  1126. /// <returns>Returns true if data can be extracted for this entry; false otherwise.</returns>
  1127. public bool IsCompressionMethodSupported()
  1128. {
  1129. return IsCompressionMethodSupported(CompressionMethod);
  1130. }
  1131. #region ICloneable Members
  1132. /// <summary>
  1133. /// Creates a copy of this zip entry.
  1134. /// </summary>
  1135. /// <returns>An <see cref="Object"/> that is a copy of the current instance.</returns>
  1136. public object Clone()
  1137. {
  1138. var result = (ZipEntry)this.MemberwiseClone();
  1139. // Ensure extra data is unique if it exists.
  1140. if (extra != null)
  1141. {
  1142. result.extra = new byte[extra.Length];
  1143. Array.Copy(extra, 0, result.extra, 0, extra.Length);
  1144. }
  1145. return result;
  1146. }
  1147. #endregion ICloneable Members
  1148. /// <summary>
  1149. /// Gets a string representation of this ZipEntry.
  1150. /// </summary>
  1151. /// <returns>A readable textual representation of this <see cref="ZipEntry"/></returns>
  1152. public override string ToString()
  1153. {
  1154. return name;
  1155. }
  1156. /// <summary>
  1157. /// Test a <see cref="CompressionMethod">compression method</see> to see if this library
  1158. /// supports extracting data compressed with that method
  1159. /// </summary>
  1160. /// <param name="method">The compression method to test.</param>
  1161. /// <returns>Returns true if the compression method is supported; false otherwise</returns>
  1162. public static bool IsCompressionMethodSupported(CompressionMethod method)
  1163. {
  1164. return
  1165. (method == CompressionMethod.Deflated) ||
  1166. (method == CompressionMethod.Stored);
  1167. }
  1168. /// <summary>
  1169. /// Cleans a name making it conform to Zip file conventions.
  1170. /// Devices names ('c:\') and UNC share names ('\\server\share') are removed
  1171. /// and forward slashes ('\') are converted to back slashes ('/').
  1172. /// Names are made relative by trimming leading slashes which is compatible
  1173. /// with the ZIP naming convention.
  1174. /// </summary>
  1175. /// <param name="name">The name to clean</param>
  1176. /// <returns>The 'cleaned' name.</returns>
  1177. /// <remarks>
  1178. /// The <seealso cref="ZipNameTransform">Zip name transform</seealso> class is more flexible.
  1179. /// </remarks>
  1180. public static string CleanName(string name)
  1181. {
  1182. if (name == null)
  1183. {
  1184. return string.Empty;
  1185. }
  1186. if (Path.IsPathRooted(name))
  1187. {
  1188. // NOTE:
  1189. // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
  1190. name = name.Substring(Path.GetPathRoot(name).Length);
  1191. }
  1192. name = name.Replace(@"\", "/");
  1193. while ((name.Length > 0) && (name[0] == '/'))
  1194. {
  1195. name = name.Remove(0, 1);
  1196. }
  1197. return name;
  1198. }
  1199. #region Instance Fields
  1200. private Known known;
  1201. private int externalFileAttributes = -1; // contains external attributes (O/S dependant)
  1202. private ushort versionMadeBy; // Contains host system and version information
  1203. // only relevant for central header entries
  1204. private string name;
  1205. private ulong size;
  1206. private ulong compressedSize;
  1207. private ushort versionToExtract; // Version required to extract (library handles <= 2.0)
  1208. private uint crc;
  1209. private uint dosTime;
  1210. private CompressionMethod method = CompressionMethod.Deflated;
  1211. private byte[] extra;
  1212. private string comment;
  1213. private int flags; // general purpose bit flags
  1214. private long zipFileIndex = -1; // used by ZipFile
  1215. private long offset; // used by ZipFile and ZipOutputStream
  1216. private bool forceZip64_;
  1217. private byte cryptoCheckValue_;
  1218. private int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used.
  1219. private int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256
  1220. #endregion Instance Fields
  1221. }
  1222. }