TarHeader.cs 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. using System;
  2. using System.Text;
  3. namespace ICSharpCode.SharpZipLib.Tar
  4. {
  5. /// <summary>
  6. /// This class encapsulates the Tar Entry Header used in Tar Archives.
  7. /// The class also holds a number of tar constants, used mostly in headers.
  8. /// </summary>
  9. /// <remarks>
  10. /// The tar format and its POSIX successor PAX have a long history which makes for compatability
  11. /// issues when creating and reading files.
  12. ///
  13. /// This is further complicated by a large number of programs with variations on formats
  14. /// One common issue is the handling of names longer than 100 characters.
  15. /// GNU style long names are currently supported.
  16. ///
  17. /// This is the ustar (Posix 1003.1) header.
  18. ///
  19. /// struct header
  20. /// {
  21. /// char t_name[100]; // 0 Filename
  22. /// char t_mode[8]; // 100 Permissions
  23. /// char t_uid[8]; // 108 Numerical User ID
  24. /// char t_gid[8]; // 116 Numerical Group ID
  25. /// char t_size[12]; // 124 Filesize
  26. /// char t_mtime[12]; // 136 st_mtime
  27. /// char t_chksum[8]; // 148 Checksum
  28. /// char t_typeflag; // 156 Type of File
  29. /// char t_linkname[100]; // 157 Target of Links
  30. /// char t_magic[6]; // 257 "ustar" or other...
  31. /// char t_version[2]; // 263 Version fixed to 00
  32. /// char t_uname[32]; // 265 User Name
  33. /// char t_gname[32]; // 297 Group Name
  34. /// char t_devmajor[8]; // 329 Major for devices
  35. /// char t_devminor[8]; // 337 Minor for devices
  36. /// char t_prefix[155]; // 345 Prefix for t_name
  37. /// char t_mfill[12]; // 500 Filler up to 512
  38. /// };
  39. /// </remarks>
  40. public class TarHeader
  41. {
  42. #region Constants
  43. /// <summary>
  44. /// The length of the name field in a header buffer.
  45. /// </summary>
  46. public const int NAMELEN = 100;
  47. /// <summary>
  48. /// The length of the mode field in a header buffer.
  49. /// </summary>
  50. public const int MODELEN = 8;
  51. /// <summary>
  52. /// The length of the user id field in a header buffer.
  53. /// </summary>
  54. public const int UIDLEN = 8;
  55. /// <summary>
  56. /// The length of the group id field in a header buffer.
  57. /// </summary>
  58. public const int GIDLEN = 8;
  59. /// <summary>
  60. /// The length of the checksum field in a header buffer.
  61. /// </summary>
  62. public const int CHKSUMLEN = 8;
  63. /// <summary>
  64. /// Offset of checksum in a header buffer.
  65. /// </summary>
  66. public const int CHKSUMOFS = 148;
  67. /// <summary>
  68. /// The length of the size field in a header buffer.
  69. /// </summary>
  70. public const int SIZELEN = 12;
  71. /// <summary>
  72. /// The length of the magic field in a header buffer.
  73. /// </summary>
  74. public const int MAGICLEN = 6;
  75. /// <summary>
  76. /// The length of the version field in a header buffer.
  77. /// </summary>
  78. public const int VERSIONLEN = 2;
  79. /// <summary>
  80. /// The length of the modification time field in a header buffer.
  81. /// </summary>
  82. public const int MODTIMELEN = 12;
  83. /// <summary>
  84. /// The length of the user name field in a header buffer.
  85. /// </summary>
  86. public const int UNAMELEN = 32;
  87. /// <summary>
  88. /// The length of the group name field in a header buffer.
  89. /// </summary>
  90. public const int GNAMELEN = 32;
  91. /// <summary>
  92. /// The length of the devices field in a header buffer.
  93. /// </summary>
  94. public const int DEVLEN = 8;
  95. /// <summary>
  96. /// The length of the name prefix field in a header buffer.
  97. /// </summary>
  98. public const int PREFIXLEN = 155;
  99. //
  100. // LF_ constants represent the "type" of an entry
  101. //
  102. /// <summary>
  103. /// The "old way" of indicating a normal file.
  104. /// </summary>
  105. public const byte LF_OLDNORM = 0;
  106. /// <summary>
  107. /// Normal file type.
  108. /// </summary>
  109. public const byte LF_NORMAL = (byte)'0';
  110. /// <summary>
  111. /// Link file type.
  112. /// </summary>
  113. public const byte LF_LINK = (byte)'1';
  114. /// <summary>
  115. /// Symbolic link file type.
  116. /// </summary>
  117. public const byte LF_SYMLINK = (byte)'2';
  118. /// <summary>
  119. /// Character device file type.
  120. /// </summary>
  121. public const byte LF_CHR = (byte)'3';
  122. /// <summary>
  123. /// Block device file type.
  124. /// </summary>
  125. public const byte LF_BLK = (byte)'4';
  126. /// <summary>
  127. /// Directory file type.
  128. /// </summary>
  129. public const byte LF_DIR = (byte)'5';
  130. /// <summary>
  131. /// FIFO (pipe) file type.
  132. /// </summary>
  133. public const byte LF_FIFO = (byte)'6';
  134. /// <summary>
  135. /// Contiguous file type.
  136. /// </summary>
  137. public const byte LF_CONTIG = (byte)'7';
  138. /// <summary>
  139. /// Posix.1 2001 global extended header
  140. /// </summary>
  141. public const byte LF_GHDR = (byte)'g';
  142. /// <summary>
  143. /// Posix.1 2001 extended header
  144. /// </summary>
  145. public const byte LF_XHDR = (byte)'x';
  146. // POSIX allows for upper case ascii type as extensions
  147. /// <summary>
  148. /// Solaris access control list file type
  149. /// </summary>
  150. public const byte LF_ACL = (byte)'A';
  151. /// <summary>
  152. /// GNU dir dump file type
  153. /// This is a dir entry that contains the names of files that were in the
  154. /// dir at the time the dump was made
  155. /// </summary>
  156. public const byte LF_GNU_DUMPDIR = (byte)'D';
  157. /// <summary>
  158. /// Solaris Extended Attribute File
  159. /// </summary>
  160. public const byte LF_EXTATTR = (byte)'E';
  161. /// <summary>
  162. /// Inode (metadata only) no file content
  163. /// </summary>
  164. public const byte LF_META = (byte)'I';
  165. /// <summary>
  166. /// Identifies the next file on the tape as having a long link name
  167. /// </summary>
  168. public const byte LF_GNU_LONGLINK = (byte)'K';
  169. /// <summary>
  170. /// Identifies the next file on the tape as having a long name
  171. /// </summary>
  172. public const byte LF_GNU_LONGNAME = (byte)'L';
  173. /// <summary>
  174. /// Continuation of a file that began on another volume
  175. /// </summary>
  176. public const byte LF_GNU_MULTIVOL = (byte)'M';
  177. /// <summary>
  178. /// For storing filenames that dont fit in the main header (old GNU)
  179. /// </summary>
  180. public const byte LF_GNU_NAMES = (byte)'N';
  181. /// <summary>
  182. /// GNU Sparse file
  183. /// </summary>
  184. public const byte LF_GNU_SPARSE = (byte)'S';
  185. /// <summary>
  186. /// GNU Tape/volume header ignore on extraction
  187. /// </summary>
  188. public const byte LF_GNU_VOLHDR = (byte)'V';
  189. /// <summary>
  190. /// The magic tag representing a POSIX tar archive. (would be written with a trailing NULL)
  191. /// </summary>
  192. public const string TMAGIC = "ustar";
  193. /// <summary>
  194. /// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it
  195. /// </summary>
  196. public const string GNU_TMAGIC = "ustar ";
  197. const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds
  198. readonly static DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
  199. #endregion
  200. #region Constructors
  201. /// <summary>
  202. /// Initialise a default TarHeader instance
  203. /// </summary>
  204. public TarHeader()
  205. {
  206. Magic = TMAGIC;
  207. Version = " ";
  208. Name = "";
  209. LinkName = "";
  210. UserId = defaultUserId;
  211. GroupId = defaultGroupId;
  212. UserName = defaultUser;
  213. GroupName = defaultGroupName;
  214. Size = 0;
  215. }
  216. #endregion
  217. #region Properties
  218. /// <summary>
  219. /// Get/set the name for this tar entry.
  220. /// </summary>
  221. /// <exception cref="ArgumentNullException">Thrown when attempting to set the property to null.</exception>
  222. public string Name {
  223. get { return name; }
  224. set {
  225. if (value == null) {
  226. throw new ArgumentNullException("nameof(value)");
  227. }
  228. name = value;
  229. }
  230. }
  231. /// <summary>
  232. /// Get the name of this entry.
  233. /// </summary>
  234. /// <returns>The entry's name.</returns>
  235. [Obsolete("Use the Name property instead", true)]
  236. public string GetName()
  237. {
  238. return name;
  239. }
  240. /// <summary>
  241. /// Get/set the entry's Unix style permission mode.
  242. /// </summary>
  243. public int Mode {
  244. get { return mode; }
  245. set { mode = value; }
  246. }
  247. /// <summary>
  248. /// The entry's user id.
  249. /// </summary>
  250. /// <remarks>
  251. /// This is only directly relevant to unix systems.
  252. /// The default is zero.
  253. /// </remarks>
  254. public int UserId {
  255. get { return userId; }
  256. set { userId = value; }
  257. }
  258. /// <summary>
  259. /// Get/set the entry's group id.
  260. /// </summary>
  261. /// <remarks>
  262. /// This is only directly relevant to linux/unix systems.
  263. /// The default value is zero.
  264. /// </remarks>
  265. public int GroupId {
  266. get { return groupId; }
  267. set { groupId = value; }
  268. }
  269. /// <summary>
  270. /// Get/set the entry's size.
  271. /// </summary>
  272. /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception>
  273. public long Size {
  274. get { return size; }
  275. set {
  276. if (value < 0) {
  277. throw new ArgumentOutOfRangeException("nameof(value)", "Cannot be less than zero");
  278. }
  279. size = value;
  280. }
  281. }
  282. /// <summary>
  283. /// Get/set the entry's modification time.
  284. /// </summary>
  285. /// <remarks>
  286. /// The modification time is only accurate to within a second.
  287. /// </remarks>
  288. /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception>
  289. public DateTime ModTime {
  290. get { return modTime; }
  291. set {
  292. if (value < dateTime1970) {
  293. throw new ArgumentOutOfRangeException("nameof(value)", "ModTime cannot be before Jan 1st 1970");
  294. }
  295. modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
  296. }
  297. }
  298. /// <summary>
  299. /// Get the entry's checksum. This is only valid/updated after writing or reading an entry.
  300. /// </summary>
  301. public int Checksum {
  302. get { return checksum; }
  303. }
  304. /// <summary>
  305. /// Get value of true if the header checksum is valid, false otherwise.
  306. /// </summary>
  307. public bool IsChecksumValid {
  308. get { return isChecksumValid; }
  309. }
  310. /// <summary>
  311. /// Get/set the entry's type flag.
  312. /// </summary>
  313. public byte TypeFlag {
  314. get { return typeFlag; }
  315. set { typeFlag = value; }
  316. }
  317. /// <summary>
  318. /// The entry's link name.
  319. /// </summary>
  320. /// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception>
  321. public string LinkName {
  322. get { return linkName; }
  323. set {
  324. if (value == null) {
  325. throw new ArgumentNullException("nameof(value)");
  326. }
  327. linkName = value;
  328. }
  329. }
  330. /// <summary>
  331. /// Get/set the entry's magic tag.
  332. /// </summary>
  333. /// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception>
  334. public string Magic {
  335. get { return magic; }
  336. set {
  337. if (value == null) {
  338. throw new ArgumentNullException("nameof(value)");
  339. }
  340. magic = value;
  341. }
  342. }
  343. /// <summary>
  344. /// The entry's version.
  345. /// </summary>
  346. /// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception>
  347. public string Version {
  348. get {
  349. return version;
  350. }
  351. set {
  352. if (value == null) {
  353. throw new ArgumentNullException("nameof(value)");
  354. }
  355. version = value;
  356. }
  357. }
  358. /// <summary>
  359. /// The entry's user name.
  360. /// </summary>
  361. public string UserName {
  362. get { return userName; }
  363. set {
  364. if (value != null) {
  365. userName = value.Substring(0, Math.Min(UNAMELEN, value.Length));
  366. } else {
  367. string currentUser = "user";
  368. if (currentUser.Length > UNAMELEN) {
  369. currentUser = currentUser.Substring(0, UNAMELEN);
  370. }
  371. userName = currentUser;
  372. }
  373. }
  374. }
  375. /// <summary>
  376. /// Get/set the entry's group name.
  377. /// </summary>
  378. /// <remarks>
  379. /// This is only directly relevant to unix systems.
  380. /// </remarks>
  381. public string GroupName {
  382. get { return groupName; }
  383. set {
  384. if (value == null) {
  385. groupName = "None";
  386. } else {
  387. groupName = value;
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// Get/set the entry's major device number.
  393. /// </summary>
  394. public int DevMajor {
  395. get { return devMajor; }
  396. set { devMajor = value; }
  397. }
  398. /// <summary>
  399. /// Get/set the entry's minor device number.
  400. /// </summary>
  401. public int DevMinor {
  402. get { return devMinor; }
  403. set { devMinor = value; }
  404. }
  405. #endregion
  406. #region ICloneable Members
  407. /// <summary>
  408. /// Create a new <see cref="TarHeader"/> that is a copy of the current instance.
  409. /// </summary>
  410. /// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns>
  411. public object Clone()
  412. {
  413. return this.MemberwiseClone();
  414. }
  415. #endregion
  416. /// <summary>
  417. /// Parse TarHeader information from a header buffer.
  418. /// </summary>
  419. /// <param name = "header">
  420. /// The tar entry header buffer to get information from.
  421. /// </param>
  422. public void ParseBuffer(byte[] header)
  423. {
  424. if (header == null) {
  425. throw new ArgumentNullException("nameof(header)");
  426. }
  427. int offset = 0;
  428. name = ParseName(header, offset, NAMELEN).ToString();
  429. offset += NAMELEN;
  430. mode = (int)ParseOctal(header, offset, MODELEN);
  431. offset += MODELEN;
  432. UserId = (int)ParseOctal(header, offset, UIDLEN);
  433. offset += UIDLEN;
  434. GroupId = (int)ParseOctal(header, offset, GIDLEN);
  435. offset += GIDLEN;
  436. Size = ParseBinaryOrOctal(header, offset, SIZELEN);
  437. offset += SIZELEN;
  438. ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN));
  439. offset += MODTIMELEN;
  440. checksum = (int)ParseOctal(header, offset, CHKSUMLEN);
  441. offset += CHKSUMLEN;
  442. TypeFlag = header[offset++];
  443. LinkName = ParseName(header, offset, NAMELEN).ToString();
  444. offset += NAMELEN;
  445. Magic = ParseName(header, offset, MAGICLEN).ToString();
  446. offset += MAGICLEN;
  447. if (Magic == "ustar")
  448. {
  449. Version = ParseName(header, offset, VERSIONLEN).ToString();
  450. offset += VERSIONLEN;
  451. UserName = ParseName(header, offset, UNAMELEN).ToString();
  452. offset += UNAMELEN;
  453. GroupName = ParseName(header, offset, GNAMELEN).ToString();
  454. offset += GNAMELEN;
  455. DevMajor = (int) ParseOctal(header, offset, DEVLEN);
  456. offset += DEVLEN;
  457. DevMinor = (int) ParseOctal(header, offset, DEVLEN);
  458. offset += DEVLEN;
  459. string prefix = ParseName(header, offset, PREFIXLEN).ToString();
  460. if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name;
  461. }
  462. isChecksumValid = Checksum == TarHeader.MakeCheckSum(header);
  463. }
  464. /// <summary>
  465. /// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
  466. /// </summary>
  467. /// <param name="outBuffer">output buffer for header information</param>
  468. public void WriteHeader(byte[] outBuffer)
  469. {
  470. if (outBuffer == null) {
  471. throw new ArgumentNullException("nameof(outBuffer)");
  472. }
  473. int offset = 0;
  474. offset = GetNameBytes(Name, outBuffer, offset, NAMELEN);
  475. offset = GetOctalBytes(mode, outBuffer, offset, MODELEN);
  476. offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN);
  477. offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN);
  478. offset = GetBinaryOrOctalBytes(Size, outBuffer, offset, SIZELEN);
  479. offset = GetOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN);
  480. int csOffset = offset;
  481. for (int c = 0; c < CHKSUMLEN; ++c) {
  482. outBuffer[offset++] = (byte)' ';
  483. }
  484. outBuffer[offset++] = TypeFlag;
  485. offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN);
  486. offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN);
  487. offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN);
  488. offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN);
  489. offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN);
  490. if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK)) {
  491. offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN);
  492. offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN);
  493. }
  494. for (; offset < outBuffer.Length;) {
  495. outBuffer[offset++] = 0;
  496. }
  497. checksum = ComputeCheckSum(outBuffer);
  498. GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN);
  499. isChecksumValid = true;
  500. }
  501. /// <summary>
  502. /// Get a hash code for the current object.
  503. /// </summary>
  504. /// <returns>A hash code for the current object.</returns>
  505. public override int GetHashCode()
  506. {
  507. return Name.GetHashCode();
  508. }
  509. /// <summary>
  510. /// Determines if this instance is equal to the specified object.
  511. /// </summary>
  512. /// <param name="obj">The object to compare with.</param>
  513. /// <returns>true if the objects are equal, false otherwise.</returns>
  514. public override bool Equals(object obj)
  515. {
  516. var localHeader = obj as TarHeader;
  517. bool result;
  518. if (localHeader != null) {
  519. result = (name == localHeader.name)
  520. && (mode == localHeader.mode)
  521. && (UserId == localHeader.UserId)
  522. && (GroupId == localHeader.GroupId)
  523. && (Size == localHeader.Size)
  524. && (ModTime == localHeader.ModTime)
  525. && (Checksum == localHeader.Checksum)
  526. && (TypeFlag == localHeader.TypeFlag)
  527. && (LinkName == localHeader.LinkName)
  528. && (Magic == localHeader.Magic)
  529. && (Version == localHeader.Version)
  530. && (UserName == localHeader.UserName)
  531. && (GroupName == localHeader.GroupName)
  532. && (DevMajor == localHeader.DevMajor)
  533. && (DevMinor == localHeader.DevMinor);
  534. } else {
  535. result = false;
  536. }
  537. return result;
  538. }
  539. /// <summary>
  540. /// Set defaults for values used when constructing a TarHeader instance.
  541. /// </summary>
  542. /// <param name="userId">Value to apply as a default for userId.</param>
  543. /// <param name="userName">Value to apply as a default for userName.</param>
  544. /// <param name="groupId">Value to apply as a default for groupId.</param>
  545. /// <param name="groupName">Value to apply as a default for groupName.</param>
  546. static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName)
  547. {
  548. defaultUserId = userIdAsSet = userId;
  549. defaultUser = userNameAsSet = userName;
  550. defaultGroupId = groupIdAsSet = groupId;
  551. defaultGroupName = groupNameAsSet = groupName;
  552. }
  553. static internal void RestoreSetValues()
  554. {
  555. defaultUserId = userIdAsSet;
  556. defaultUser = userNameAsSet;
  557. defaultGroupId = groupIdAsSet;
  558. defaultGroupName = groupNameAsSet;
  559. }
  560. // Return value that may be stored in octal or binary. Length must exceed 8.
  561. //
  562. static private long ParseBinaryOrOctal(byte[] header, int offset, int length)
  563. {
  564. if (header[offset] >= 0x80) {
  565. // File sizes over 8GB are stored in 8 right-justified bytes of binary indicated by setting the high-order bit of the leftmost byte of a numeric field.
  566. long result = 0;
  567. for (int pos = length - 8; pos < length; pos++) {
  568. result = result << 8 | header[offset + pos];
  569. }
  570. return result;
  571. }
  572. return ParseOctal(header, offset, length);
  573. }
  574. /// <summary>
  575. /// Parse an octal string from a header buffer.
  576. /// </summary>
  577. /// <param name = "header">The header buffer from which to parse.</param>
  578. /// <param name = "offset">The offset into the buffer from which to parse.</param>
  579. /// <param name = "length">The number of header bytes to parse.</param>
  580. /// <returns>The long equivalent of the octal string.</returns>
  581. static public long ParseOctal(byte[] header, int offset, int length)
  582. {
  583. if (header == null) {
  584. throw new ArgumentNullException("nameof(header)");
  585. }
  586. long result = 0;
  587. bool stillPadding = true;
  588. int end = offset + length;
  589. for (int i = offset; i < end; ++i) {
  590. if (header[i] == 0) {
  591. break;
  592. }
  593. if (header[i] == (byte)' ' || header[i] == '0') {
  594. if (stillPadding) {
  595. continue;
  596. }
  597. if (header[i] == (byte)' ') {
  598. break;
  599. }
  600. }
  601. stillPadding = false;
  602. result = (result << 3) + (header[i] - '0');
  603. }
  604. return result;
  605. }
  606. /// <summary>
  607. /// Parse a name from a header buffer.
  608. /// </summary>
  609. /// <param name="header">
  610. /// The header buffer from which to parse.
  611. /// </param>
  612. /// <param name="offset">
  613. /// The offset into the buffer from which to parse.
  614. /// </param>
  615. /// <param name="length">
  616. /// The number of header bytes to parse.
  617. /// </param>
  618. /// <returns>
  619. /// The name parsed.
  620. /// </returns>
  621. static public StringBuilder ParseName(byte[] header, int offset, int length)
  622. {
  623. if (header == null) {
  624. throw new ArgumentNullException("nameof(header)");
  625. }
  626. if (offset < 0) {
  627. throw new ArgumentOutOfRangeException("nameof(offset)", "Cannot be less than zero");
  628. }
  629. if (length < 0) {
  630. throw new ArgumentOutOfRangeException("nameof(length)", "Cannot be less than zero");
  631. }
  632. if (offset + length > header.Length) {
  633. throw new ArgumentException("Exceeds header size", "nameof(length)");
  634. }
  635. var result = new StringBuilder(length);
  636. for (int i = offset; i < offset + length; ++i) {
  637. if (header[i] == 0) {
  638. break;
  639. }
  640. result.Append((char)header[i]);
  641. }
  642. return result;
  643. }
  644. /// <summary>
  645. /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
  646. /// </summary>
  647. /// <param name="name">The name to add</param>
  648. /// <param name="nameOffset">The offset of the first character</param>
  649. /// <param name="buffer">The buffer to add to</param>
  650. /// <param name="bufferOffset">The index of the first byte to add</param>
  651. /// <param name="length">The number of characters/bytes to add</param>
  652. /// <returns>The next free index in the <paramref name="buffer"/></returns>
  653. public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length)
  654. {
  655. if (name == null) {
  656. throw new ArgumentNullException("nameof(name)");
  657. }
  658. if (buffer == null) {
  659. throw new ArgumentNullException("nameof(buffer)");
  660. }
  661. return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length);
  662. }
  663. /// <summary>
  664. /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
  665. /// </summary>
  666. /// <param name="name">The name to add</param>
  667. /// <param name="nameOffset">The offset of the first character</param>
  668. /// <param name="buffer">The buffer to add to</param>
  669. /// <param name="bufferOffset">The index of the first byte to add</param>
  670. /// <param name="length">The number of characters/bytes to add</param>
  671. /// <returns>The next free index in the <paramref name="buffer"/></returns>
  672. public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length)
  673. {
  674. if (name == null) {
  675. throw new ArgumentNullException("nameof(name)");
  676. }
  677. if (buffer == null) {
  678. throw new ArgumentNullException("nameof(buffer)");
  679. }
  680. int i;
  681. for (i = 0 ; i < length && nameOffset + i < name.Length; ++i) {
  682. buffer[bufferOffset + i] = (byte)name[nameOffset + i];
  683. }
  684. for (; i < length; ++i) {
  685. buffer[bufferOffset + i] = 0;
  686. }
  687. return bufferOffset + length;
  688. }
  689. /// <summary>
  690. /// Add an entry name to the buffer
  691. /// </summary>
  692. /// <param name="name">
  693. /// The name to add
  694. /// </param>
  695. /// <param name="buffer">
  696. /// The buffer to add to
  697. /// </param>
  698. /// <param name="offset">
  699. /// The offset into the buffer from which to start adding
  700. /// </param>
  701. /// <param name="length">
  702. /// The number of header bytes to add
  703. /// </param>
  704. /// <returns>
  705. /// The index of the next free byte in the buffer
  706. /// </returns>
  707. public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length)
  708. {
  709. if (name == null) {
  710. throw new ArgumentNullException("nameof(name)");
  711. }
  712. if (buffer == null) {
  713. throw new ArgumentNullException("nameof(buffer)");
  714. }
  715. return GetNameBytes(name.ToString(), 0, buffer, offset, length);
  716. }
  717. /// <summary>
  718. /// Add an entry name to the buffer
  719. /// </summary>
  720. /// <param name="name">The name to add</param>
  721. /// <param name="buffer">The buffer to add to</param>
  722. /// <param name="offset">The offset into the buffer from which to start adding</param>
  723. /// <param name="length">The number of header bytes to add</param>
  724. /// <returns>The index of the next free byte in the buffer</returns>
  725. public static int GetNameBytes(string name, byte[] buffer, int offset, int length)
  726. {
  727. if (name == null) {
  728. throw new ArgumentNullException("nameof(name)");
  729. }
  730. if (buffer == null) {
  731. throw new ArgumentNullException("nameof(buffer)");
  732. }
  733. return GetNameBytes(name, 0, buffer, offset, length);
  734. }
  735. /// <summary>
  736. /// Add a string to a buffer as a collection of ascii bytes.
  737. /// </summary>
  738. /// <param name="toAdd">The string to add</param>
  739. /// <param name="nameOffset">The offset of the first character to add.</param>
  740. /// <param name="buffer">The buffer to add to.</param>
  741. /// <param name="bufferOffset">The offset to start adding at.</param>
  742. /// <param name="length">The number of ascii characters to add.</param>
  743. /// <returns>The next free index in the buffer.</returns>
  744. public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length)
  745. {
  746. if (toAdd == null) {
  747. throw new ArgumentNullException("nameof(toAdd)");
  748. }
  749. if (buffer == null) {
  750. throw new ArgumentNullException("nameof(buffer)");
  751. }
  752. int i;
  753. for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i) {
  754. buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i];
  755. }
  756. // If length is beyond the toAdd string length (which is OK by the prev loop condition), eg if a field has fixed length and the string is shorter, make sure all of the extra chars are written as NULLs, so that the reader func would ignore them and get back the original string
  757. for (; i < length; ++i)
  758. buffer[bufferOffset + i] = 0;
  759. return bufferOffset + length;
  760. }
  761. /// <summary>
  762. /// Put an octal representation of a value into a buffer
  763. /// </summary>
  764. /// <param name = "value">
  765. /// the value to be converted to octal
  766. /// </param>
  767. /// <param name = "buffer">
  768. /// buffer to store the octal string
  769. /// </param>
  770. /// <param name = "offset">
  771. /// The offset into the buffer where the value starts
  772. /// </param>
  773. /// <param name = "length">
  774. /// The length of the octal string to create
  775. /// </param>
  776. /// <returns>
  777. /// The offset of the character next byte after the octal string
  778. /// </returns>
  779. public static int GetOctalBytes(long value, byte[] buffer, int offset, int length)
  780. {
  781. if (buffer == null) {
  782. throw new ArgumentNullException("nameof(buffer)");
  783. }
  784. int localIndex = length - 1;
  785. // Either a space or null is valid here. We use NULL as per GNUTar
  786. buffer[offset + localIndex] = 0;
  787. --localIndex;
  788. if (value > 0) {
  789. for (long v = value; (localIndex >= 0) && (v > 0); --localIndex) {
  790. buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7));
  791. v >>= 3;
  792. }
  793. }
  794. for (; localIndex >= 0; --localIndex) {
  795. buffer[offset + localIndex] = (byte)'0';
  796. }
  797. return offset + length;
  798. }
  799. /// <summary>
  800. /// Put an octal or binary representation of a value into a buffer
  801. /// </summary>
  802. /// <param name = "value">Value to be convert to octal</param>
  803. /// <param name = "buffer">The buffer to update</param>
  804. /// <param name = "offset">The offset into the buffer to store the value</param>
  805. /// <param name = "length">The length of the octal string. Must be 12.</param>
  806. /// <returns>Index of next byte</returns>
  807. private static int GetBinaryOrOctalBytes(long value, byte[] buffer, int offset, int length)
  808. {
  809. if (value > 0x1FFFFFFFF) { // Octal 77777777777 (11 digits)
  810. // Put value as binary, right-justified into the buffer. Set high order bit of left-most byte.
  811. for (int pos = length - 1; pos > 0; pos--) {
  812. buffer[offset + pos] = (byte)value;
  813. value = value >> 8;
  814. }
  815. buffer[offset] = 0x80;
  816. return offset + length;
  817. }
  818. return GetOctalBytes(value, buffer, offset, length);
  819. }
  820. /// <summary>
  821. /// Add the checksum integer to header buffer.
  822. /// </summary>
  823. /// <param name = "value"></param>
  824. /// <param name = "buffer">The header buffer to set the checksum for</param>
  825. /// <param name = "offset">The offset into the buffer for the checksum</param>
  826. /// <param name = "length">The number of header bytes to update.
  827. /// It's formatted differently from the other fields: it has 6 digits, a
  828. /// null, then a space -- rather than digits, a space, then a null.
  829. /// The final space is already there, from checksumming
  830. /// </param>
  831. /// <returns>The modified buffer offset</returns>
  832. static void GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length)
  833. {
  834. GetOctalBytes(value, buffer, offset, length - 1);
  835. }
  836. /// <summary>
  837. /// Compute the checksum for a tar entry header.
  838. /// The checksum field must be all spaces prior to this happening
  839. /// </summary>
  840. /// <param name = "buffer">The tar entry's header buffer.</param>
  841. /// <returns>The computed checksum.</returns>
  842. static int ComputeCheckSum(byte[] buffer)
  843. {
  844. int sum = 0;
  845. for (int i = 0; i < buffer.Length; ++i) {
  846. sum += buffer[i];
  847. }
  848. return sum;
  849. }
  850. /// <summary>
  851. /// Make a checksum for a tar entry ignoring the checksum contents.
  852. /// </summary>
  853. /// <param name = "buffer">The tar entry's header buffer.</param>
  854. /// <returns>The checksum for the buffer</returns>
  855. static int MakeCheckSum(byte[] buffer)
  856. {
  857. int sum = 0;
  858. for (int i = 0; i < CHKSUMOFS; ++i) {
  859. sum += buffer[i];
  860. }
  861. for (int i = 0; i < CHKSUMLEN; ++i) {
  862. sum += (byte)' ';
  863. }
  864. for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i) {
  865. sum += buffer[i];
  866. }
  867. return sum;
  868. }
  869. static int GetCTime(DateTime dateTime)
  870. {
  871. return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor));
  872. }
  873. static DateTime GetDateTimeFromCTime(long ticks)
  874. {
  875. DateTime result;
  876. try {
  877. result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor);
  878. } catch (ArgumentOutOfRangeException) {
  879. result = dateTime1970;
  880. }
  881. return result;
  882. }
  883. #region Instance Fields
  884. string name;
  885. int mode;
  886. int userId;
  887. int groupId;
  888. long size;
  889. DateTime modTime;
  890. int checksum;
  891. bool isChecksumValid;
  892. byte typeFlag;
  893. string linkName;
  894. string magic;
  895. string version;
  896. string userName;
  897. string groupName;
  898. int devMajor;
  899. int devMinor;
  900. #endregion
  901. #region Class Fields
  902. // Values used during recursive operations.
  903. static internal int userIdAsSet;
  904. static internal int groupIdAsSet;
  905. static internal string userNameAsSet;
  906. static internal string groupNameAsSet = "None";
  907. static internal int defaultUserId;
  908. static internal int defaultGroupId;
  909. static internal string defaultGroupName = "None";
  910. static internal string defaultUser;
  911. #endregion
  912. }
  913. }