TarHeader.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. private const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds
  198. private static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
  199. #endregion Constants
  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 Constructors
  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. {
  224. get { return name; }
  225. set
  226. {
  227. if (value == null)
  228. {
  229. throw new ArgumentNullException(nameof(value));
  230. }
  231. name = value;
  232. }
  233. }
  234. /// <summary>
  235. /// Get the name of this entry.
  236. /// </summary>
  237. /// <returns>The entry's name.</returns>
  238. [Obsolete("Use the Name property instead", true)]
  239. public string GetName()
  240. {
  241. return name;
  242. }
  243. /// <summary>
  244. /// Get/set the entry's Unix style permission mode.
  245. /// </summary>
  246. public int Mode
  247. {
  248. get { return mode; }
  249. set { mode = value; }
  250. }
  251. /// <summary>
  252. /// The entry's user id.
  253. /// </summary>
  254. /// <remarks>
  255. /// This is only directly relevant to unix systems.
  256. /// The default is zero.
  257. /// </remarks>
  258. public int UserId
  259. {
  260. get { return userId; }
  261. set { userId = value; }
  262. }
  263. /// <summary>
  264. /// Get/set the entry's group id.
  265. /// </summary>
  266. /// <remarks>
  267. /// This is only directly relevant to linux/unix systems.
  268. /// The default value is zero.
  269. /// </remarks>
  270. public int GroupId
  271. {
  272. get { return groupId; }
  273. set { groupId = value; }
  274. }
  275. /// <summary>
  276. /// Get/set the entry's size.
  277. /// </summary>
  278. /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception>
  279. public long Size
  280. {
  281. get { return size; }
  282. set
  283. {
  284. if (value < 0)
  285. {
  286. throw new ArgumentOutOfRangeException(nameof(value), "Cannot be less than zero");
  287. }
  288. size = value;
  289. }
  290. }
  291. /// <summary>
  292. /// Get/set the entry's modification time.
  293. /// </summary>
  294. /// <remarks>
  295. /// The modification time is only accurate to within a second.
  296. /// </remarks>
  297. /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception>
  298. public DateTime ModTime
  299. {
  300. get { return modTime; }
  301. set
  302. {
  303. if (value < dateTime1970)
  304. {
  305. throw new ArgumentOutOfRangeException(nameof(value), "ModTime cannot be before Jan 1st 1970");
  306. }
  307. modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
  308. }
  309. }
  310. /// <summary>
  311. /// Get the entry's checksum. This is only valid/updated after writing or reading an entry.
  312. /// </summary>
  313. public int Checksum
  314. {
  315. get { return checksum; }
  316. }
  317. /// <summary>
  318. /// Get value of true if the header checksum is valid, false otherwise.
  319. /// </summary>
  320. public bool IsChecksumValid
  321. {
  322. get { return isChecksumValid; }
  323. }
  324. /// <summary>
  325. /// Get/set the entry's type flag.
  326. /// </summary>
  327. public byte TypeFlag
  328. {
  329. get { return typeFlag; }
  330. set { typeFlag = value; }
  331. }
  332. /// <summary>
  333. /// The entry's link name.
  334. /// </summary>
  335. /// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception>
  336. public string LinkName
  337. {
  338. get { return linkName; }
  339. set
  340. {
  341. if (value == null)
  342. {
  343. throw new ArgumentNullException(nameof(value));
  344. }
  345. linkName = value;
  346. }
  347. }
  348. /// <summary>
  349. /// Get/set the entry's magic tag.
  350. /// </summary>
  351. /// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception>
  352. public string Magic
  353. {
  354. get { return magic; }
  355. set
  356. {
  357. if (value == null)
  358. {
  359. throw new ArgumentNullException(nameof(value));
  360. }
  361. magic = value;
  362. }
  363. }
  364. /// <summary>
  365. /// The entry's version.
  366. /// </summary>
  367. /// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception>
  368. public string Version
  369. {
  370. get
  371. {
  372. return version;
  373. }
  374. set
  375. {
  376. if (value == null)
  377. {
  378. throw new ArgumentNullException(nameof(value));
  379. }
  380. version = value;
  381. }
  382. }
  383. /// <summary>
  384. /// The entry's user name.
  385. /// </summary>
  386. public string UserName
  387. {
  388. get { return userName; }
  389. set
  390. {
  391. if (value != null)
  392. {
  393. userName = value.Substring(0, Math.Min(UNAMELEN, value.Length));
  394. }
  395. else
  396. {
  397. string currentUser = "user";
  398. if (currentUser.Length > UNAMELEN)
  399. {
  400. currentUser = currentUser.Substring(0, UNAMELEN);
  401. }
  402. userName = currentUser;
  403. }
  404. }
  405. }
  406. /// <summary>
  407. /// Get/set the entry's group name.
  408. /// </summary>
  409. /// <remarks>
  410. /// This is only directly relevant to unix systems.
  411. /// </remarks>
  412. public string GroupName
  413. {
  414. get { return groupName; }
  415. set
  416. {
  417. if (value == null)
  418. {
  419. groupName = "None";
  420. }
  421. else
  422. {
  423. groupName = value;
  424. }
  425. }
  426. }
  427. /// <summary>
  428. /// Get/set the entry's major device number.
  429. /// </summary>
  430. public int DevMajor
  431. {
  432. get { return devMajor; }
  433. set { devMajor = value; }
  434. }
  435. /// <summary>
  436. /// Get/set the entry's minor device number.
  437. /// </summary>
  438. public int DevMinor
  439. {
  440. get { return devMinor; }
  441. set { devMinor = value; }
  442. }
  443. #endregion Properties
  444. #region ICloneable Members
  445. /// <summary>
  446. /// Create a new <see cref="TarHeader"/> that is a copy of the current instance.
  447. /// </summary>
  448. /// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns>
  449. public object Clone()
  450. {
  451. return this.MemberwiseClone();
  452. }
  453. #endregion ICloneable Members
  454. /// <summary>
  455. /// Parse TarHeader information from a header buffer.
  456. /// </summary>
  457. /// <param name = "header">
  458. /// The tar entry header buffer to get information from.
  459. /// </param>
  460. public void ParseBuffer(byte[] header)
  461. {
  462. if (header == null)
  463. {
  464. throw new ArgumentNullException(nameof(header));
  465. }
  466. int offset = 0;
  467. name = ParseName(header, offset, NAMELEN).ToString();
  468. offset += NAMELEN;
  469. mode = (int)ParseOctal(header, offset, MODELEN);
  470. offset += MODELEN;
  471. UserId = (int)ParseOctal(header, offset, UIDLEN);
  472. offset += UIDLEN;
  473. GroupId = (int)ParseOctal(header, offset, GIDLEN);
  474. offset += GIDLEN;
  475. Size = ParseBinaryOrOctal(header, offset, SIZELEN);
  476. offset += SIZELEN;
  477. ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN));
  478. offset += MODTIMELEN;
  479. checksum = (int)ParseOctal(header, offset, CHKSUMLEN);
  480. offset += CHKSUMLEN;
  481. TypeFlag = header[offset++];
  482. LinkName = ParseName(header, offset, NAMELEN).ToString();
  483. offset += NAMELEN;
  484. Magic = ParseName(header, offset, MAGICLEN).ToString();
  485. offset += MAGICLEN;
  486. if (Magic == "ustar")
  487. {
  488. Version = ParseName(header, offset, VERSIONLEN).ToString();
  489. offset += VERSIONLEN;
  490. UserName = ParseName(header, offset, UNAMELEN).ToString();
  491. offset += UNAMELEN;
  492. GroupName = ParseName(header, offset, GNAMELEN).ToString();
  493. offset += GNAMELEN;
  494. DevMajor = (int)ParseOctal(header, offset, DEVLEN);
  495. offset += DEVLEN;
  496. DevMinor = (int)ParseOctal(header, offset, DEVLEN);
  497. offset += DEVLEN;
  498. string prefix = ParseName(header, offset, PREFIXLEN).ToString();
  499. if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name;
  500. }
  501. isChecksumValid = Checksum == TarHeader.MakeCheckSum(header);
  502. }
  503. /// <summary>
  504. /// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
  505. /// </summary>
  506. /// <param name="outBuffer">output buffer for header information</param>
  507. public void WriteHeader(byte[] outBuffer)
  508. {
  509. if (outBuffer == null)
  510. {
  511. throw new ArgumentNullException(nameof(outBuffer));
  512. }
  513. int offset = 0;
  514. offset = GetNameBytes(Name, outBuffer, offset, NAMELEN);
  515. offset = GetOctalBytes(mode, outBuffer, offset, MODELEN);
  516. offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN);
  517. offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN);
  518. offset = GetBinaryOrOctalBytes(Size, outBuffer, offset, SIZELEN);
  519. offset = GetOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN);
  520. int csOffset = offset;
  521. for (int c = 0; c < CHKSUMLEN; ++c)
  522. {
  523. outBuffer[offset++] = (byte)' ';
  524. }
  525. outBuffer[offset++] = TypeFlag;
  526. offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN);
  527. offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN);
  528. offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN);
  529. offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN);
  530. offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN);
  531. if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK))
  532. {
  533. offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN);
  534. offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN);
  535. }
  536. for (; offset < outBuffer.Length;)
  537. {
  538. outBuffer[offset++] = 0;
  539. }
  540. checksum = ComputeCheckSum(outBuffer);
  541. GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN);
  542. isChecksumValid = true;
  543. }
  544. /// <summary>
  545. /// Get a hash code for the current object.
  546. /// </summary>
  547. /// <returns>A hash code for the current object.</returns>
  548. public override int GetHashCode()
  549. {
  550. return Name.GetHashCode();
  551. }
  552. /// <summary>
  553. /// Determines if this instance is equal to the specified object.
  554. /// </summary>
  555. /// <param name="obj">The object to compare with.</param>
  556. /// <returns>true if the objects are equal, false otherwise.</returns>
  557. public override bool Equals(object obj)
  558. {
  559. var localHeader = obj as TarHeader;
  560. bool result;
  561. if (localHeader != null)
  562. {
  563. result = (name == localHeader.name)
  564. && (mode == localHeader.mode)
  565. && (UserId == localHeader.UserId)
  566. && (GroupId == localHeader.GroupId)
  567. && (Size == localHeader.Size)
  568. && (ModTime == localHeader.ModTime)
  569. && (Checksum == localHeader.Checksum)
  570. && (TypeFlag == localHeader.TypeFlag)
  571. && (LinkName == localHeader.LinkName)
  572. && (Magic == localHeader.Magic)
  573. && (Version == localHeader.Version)
  574. && (UserName == localHeader.UserName)
  575. && (GroupName == localHeader.GroupName)
  576. && (DevMajor == localHeader.DevMajor)
  577. && (DevMinor == localHeader.DevMinor);
  578. }
  579. else
  580. {
  581. result = false;
  582. }
  583. return result;
  584. }
  585. /// <summary>
  586. /// Set defaults for values used when constructing a TarHeader instance.
  587. /// </summary>
  588. /// <param name="userId">Value to apply as a default for userId.</param>
  589. /// <param name="userName">Value to apply as a default for userName.</param>
  590. /// <param name="groupId">Value to apply as a default for groupId.</param>
  591. /// <param name="groupName">Value to apply as a default for groupName.</param>
  592. static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName)
  593. {
  594. defaultUserId = userIdAsSet = userId;
  595. defaultUser = userNameAsSet = userName;
  596. defaultGroupId = groupIdAsSet = groupId;
  597. defaultGroupName = groupNameAsSet = groupName;
  598. }
  599. static internal void RestoreSetValues()
  600. {
  601. defaultUserId = userIdAsSet;
  602. defaultUser = userNameAsSet;
  603. defaultGroupId = groupIdAsSet;
  604. defaultGroupName = groupNameAsSet;
  605. }
  606. // Return value that may be stored in octal or binary. Length must exceed 8.
  607. //
  608. static private long ParseBinaryOrOctal(byte[] header, int offset, int length)
  609. {
  610. if (header[offset] >= 0x80)
  611. {
  612. // 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.
  613. long result = 0;
  614. for (int pos = length - 8; pos < length; pos++)
  615. {
  616. result = result << 8 | header[offset + pos];
  617. }
  618. return result;
  619. }
  620. return ParseOctal(header, offset, length);
  621. }
  622. /// <summary>
  623. /// Parse an octal string from a header buffer.
  624. /// </summary>
  625. /// <param name = "header">The header buffer from which to parse.</param>
  626. /// <param name = "offset">The offset into the buffer from which to parse.</param>
  627. /// <param name = "length">The number of header bytes to parse.</param>
  628. /// <returns>The long equivalent of the octal string.</returns>
  629. static public long ParseOctal(byte[] header, int offset, int length)
  630. {
  631. if (header == null)
  632. {
  633. throw new ArgumentNullException(nameof(header));
  634. }
  635. long result = 0;
  636. bool stillPadding = true;
  637. int end = offset + length;
  638. for (int i = offset; i < end; ++i)
  639. {
  640. if (header[i] == 0)
  641. {
  642. break;
  643. }
  644. if (header[i] == (byte)' ' || header[i] == '0')
  645. {
  646. if (stillPadding)
  647. {
  648. continue;
  649. }
  650. if (header[i] == (byte)' ')
  651. {
  652. break;
  653. }
  654. }
  655. stillPadding = false;
  656. result = (result << 3) + (header[i] - '0');
  657. }
  658. return result;
  659. }
  660. /// <summary>
  661. /// Parse a name from a header buffer.
  662. /// </summary>
  663. /// <param name="header">
  664. /// The header buffer from which to parse.
  665. /// </param>
  666. /// <param name="offset">
  667. /// The offset into the buffer from which to parse.
  668. /// </param>
  669. /// <param name="length">
  670. /// The number of header bytes to parse.
  671. /// </param>
  672. /// <returns>
  673. /// The name parsed.
  674. /// </returns>
  675. static public StringBuilder ParseName(byte[] header, int offset, int length)
  676. {
  677. if (header == null)
  678. {
  679. throw new ArgumentNullException(nameof(header));
  680. }
  681. if (offset < 0)
  682. {
  683. throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be less than zero");
  684. }
  685. if (length < 0)
  686. {
  687. throw new ArgumentOutOfRangeException(nameof(length), "Cannot be less than zero");
  688. }
  689. if (offset + length > header.Length)
  690. {
  691. throw new ArgumentException("Exceeds header size", nameof(length));
  692. }
  693. var result = new StringBuilder(length);
  694. for (int i = offset; i < offset + length; ++i)
  695. {
  696. if (header[i] == 0)
  697. {
  698. break;
  699. }
  700. result.Append((char)header[i]);
  701. }
  702. return result;
  703. }
  704. /// <summary>
  705. /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
  706. /// </summary>
  707. /// <param name="name">The name to add</param>
  708. /// <param name="nameOffset">The offset of the first character</param>
  709. /// <param name="buffer">The buffer to add to</param>
  710. /// <param name="bufferOffset">The index of the first byte to add</param>
  711. /// <param name="length">The number of characters/bytes to add</param>
  712. /// <returns>The next free index in the <paramref name="buffer"/></returns>
  713. public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length)
  714. {
  715. if (name == null)
  716. {
  717. throw new ArgumentNullException(nameof(name));
  718. }
  719. if (buffer == null)
  720. {
  721. throw new ArgumentNullException(nameof(buffer));
  722. }
  723. return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length);
  724. }
  725. /// <summary>
  726. /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
  727. /// </summary>
  728. /// <param name="name">The name to add</param>
  729. /// <param name="nameOffset">The offset of the first character</param>
  730. /// <param name="buffer">The buffer to add to</param>
  731. /// <param name="bufferOffset">The index of the first byte to add</param>
  732. /// <param name="length">The number of characters/bytes to add</param>
  733. /// <returns>The next free index in the <paramref name="buffer"/></returns>
  734. public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length)
  735. {
  736. if (name == null)
  737. {
  738. throw new ArgumentNullException(nameof(name));
  739. }
  740. if (buffer == null)
  741. {
  742. throw new ArgumentNullException(nameof(buffer));
  743. }
  744. int i;
  745. for (i = 0; i < length && nameOffset + i < name.Length; ++i)
  746. {
  747. buffer[bufferOffset + i] = (byte)name[nameOffset + i];
  748. }
  749. for (; i < length; ++i)
  750. {
  751. buffer[bufferOffset + i] = 0;
  752. }
  753. return bufferOffset + length;
  754. }
  755. /// <summary>
  756. /// Add an entry name to the buffer
  757. /// </summary>
  758. /// <param name="name">
  759. /// The name to add
  760. /// </param>
  761. /// <param name="buffer">
  762. /// The buffer to add to
  763. /// </param>
  764. /// <param name="offset">
  765. /// The offset into the buffer from which to start adding
  766. /// </param>
  767. /// <param name="length">
  768. /// The number of header bytes to add
  769. /// </param>
  770. /// <returns>
  771. /// The index of the next free byte in the buffer
  772. /// </returns>
  773. public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length)
  774. {
  775. if (name == null)
  776. {
  777. throw new ArgumentNullException(nameof(name));
  778. }
  779. if (buffer == null)
  780. {
  781. throw new ArgumentNullException(nameof(buffer));
  782. }
  783. return GetNameBytes(name.ToString(), 0, buffer, offset, length);
  784. }
  785. /// <summary>
  786. /// Add an entry name to the buffer
  787. /// </summary>
  788. /// <param name="name">The name to add</param>
  789. /// <param name="buffer">The buffer to add to</param>
  790. /// <param name="offset">The offset into the buffer from which to start adding</param>
  791. /// <param name="length">The number of header bytes to add</param>
  792. /// <returns>The index of the next free byte in the buffer</returns>
  793. public static int GetNameBytes(string name, byte[] buffer, int offset, int length)
  794. {
  795. if (name == null)
  796. {
  797. throw new ArgumentNullException(nameof(name));
  798. }
  799. if (buffer == null)
  800. {
  801. throw new ArgumentNullException(nameof(buffer));
  802. }
  803. return GetNameBytes(name, 0, buffer, offset, length);
  804. }
  805. /// <summary>
  806. /// Add a string to a buffer as a collection of ascii bytes.
  807. /// </summary>
  808. /// <param name="toAdd">The string to add</param>
  809. /// <param name="nameOffset">The offset of the first character to add.</param>
  810. /// <param name="buffer">The buffer to add to.</param>
  811. /// <param name="bufferOffset">The offset to start adding at.</param>
  812. /// <param name="length">The number of ascii characters to add.</param>
  813. /// <returns>The next free index in the buffer.</returns>
  814. public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length)
  815. {
  816. if (toAdd == null)
  817. {
  818. throw new ArgumentNullException(nameof(toAdd));
  819. }
  820. if (buffer == null)
  821. {
  822. throw new ArgumentNullException(nameof(buffer));
  823. }
  824. int i;
  825. for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i)
  826. {
  827. buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i];
  828. }
  829. // 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
  830. for (; i < length; ++i)
  831. buffer[bufferOffset + i] = 0;
  832. return bufferOffset + length;
  833. }
  834. /// <summary>
  835. /// Put an octal representation of a value into a buffer
  836. /// </summary>
  837. /// <param name = "value">
  838. /// the value to be converted to octal
  839. /// </param>
  840. /// <param name = "buffer">
  841. /// buffer to store the octal string
  842. /// </param>
  843. /// <param name = "offset">
  844. /// The offset into the buffer where the value starts
  845. /// </param>
  846. /// <param name = "length">
  847. /// The length of the octal string to create
  848. /// </param>
  849. /// <returns>
  850. /// The offset of the character next byte after the octal string
  851. /// </returns>
  852. public static int GetOctalBytes(long value, byte[] buffer, int offset, int length)
  853. {
  854. if (buffer == null)
  855. {
  856. throw new ArgumentNullException(nameof(buffer));
  857. }
  858. int localIndex = length - 1;
  859. // Either a space or null is valid here. We use NULL as per GNUTar
  860. buffer[offset + localIndex] = 0;
  861. --localIndex;
  862. if (value > 0)
  863. {
  864. for (long v = value; (localIndex >= 0) && (v > 0); --localIndex)
  865. {
  866. buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7));
  867. v >>= 3;
  868. }
  869. }
  870. for (; localIndex >= 0; --localIndex)
  871. {
  872. buffer[offset + localIndex] = (byte)'0';
  873. }
  874. return offset + length;
  875. }
  876. /// <summary>
  877. /// Put an octal or binary representation of a value into a buffer
  878. /// </summary>
  879. /// <param name = "value">Value to be convert to octal</param>
  880. /// <param name = "buffer">The buffer to update</param>
  881. /// <param name = "offset">The offset into the buffer to store the value</param>
  882. /// <param name = "length">The length of the octal string. Must be 12.</param>
  883. /// <returns>Index of next byte</returns>
  884. private static int GetBinaryOrOctalBytes(long value, byte[] buffer, int offset, int length)
  885. {
  886. if (value > 0x1FFFFFFFF)
  887. { // Octal 77777777777 (11 digits)
  888. // Put value as binary, right-justified into the buffer. Set high order bit of left-most byte.
  889. for (int pos = length - 1; pos > 0; pos--)
  890. {
  891. buffer[offset + pos] = (byte)value;
  892. value = value >> 8;
  893. }
  894. buffer[offset] = 0x80;
  895. return offset + length;
  896. }
  897. return GetOctalBytes(value, buffer, offset, length);
  898. }
  899. /// <summary>
  900. /// Add the checksum integer to header buffer.
  901. /// </summary>
  902. /// <param name = "value"></param>
  903. /// <param name = "buffer">The header buffer to set the checksum for</param>
  904. /// <param name = "offset">The offset into the buffer for the checksum</param>
  905. /// <param name = "length">The number of header bytes to update.
  906. /// It's formatted differently from the other fields: it has 6 digits, a
  907. /// null, then a space -- rather than digits, a space, then a null.
  908. /// The final space is already there, from checksumming
  909. /// </param>
  910. /// <returns>The modified buffer offset</returns>
  911. private static void GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length)
  912. {
  913. GetOctalBytes(value, buffer, offset, length - 1);
  914. }
  915. /// <summary>
  916. /// Compute the checksum for a tar entry header.
  917. /// The checksum field must be all spaces prior to this happening
  918. /// </summary>
  919. /// <param name = "buffer">The tar entry's header buffer.</param>
  920. /// <returns>The computed checksum.</returns>
  921. private static int ComputeCheckSum(byte[] buffer)
  922. {
  923. int sum = 0;
  924. for (int i = 0; i < buffer.Length; ++i)
  925. {
  926. sum += buffer[i];
  927. }
  928. return sum;
  929. }
  930. /// <summary>
  931. /// Make a checksum for a tar entry ignoring the checksum contents.
  932. /// </summary>
  933. /// <param name = "buffer">The tar entry's header buffer.</param>
  934. /// <returns>The checksum for the buffer</returns>
  935. private static int MakeCheckSum(byte[] buffer)
  936. {
  937. int sum = 0;
  938. for (int i = 0; i < CHKSUMOFS; ++i)
  939. {
  940. sum += buffer[i];
  941. }
  942. for (int i = 0; i < CHKSUMLEN; ++i)
  943. {
  944. sum += (byte)' ';
  945. }
  946. for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i)
  947. {
  948. sum += buffer[i];
  949. }
  950. return sum;
  951. }
  952. private static int GetCTime(DateTime dateTime)
  953. {
  954. return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor));
  955. }
  956. private static DateTime GetDateTimeFromCTime(long ticks)
  957. {
  958. DateTime result;
  959. try
  960. {
  961. result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor);
  962. }
  963. catch (ArgumentOutOfRangeException)
  964. {
  965. result = dateTime1970;
  966. }
  967. return result;
  968. }
  969. #region Instance Fields
  970. private string name;
  971. private int mode;
  972. private int userId;
  973. private int groupId;
  974. private long size;
  975. private DateTime modTime;
  976. private int checksum;
  977. private bool isChecksumValid;
  978. private byte typeFlag;
  979. private string linkName;
  980. private string magic;
  981. private string version;
  982. private string userName;
  983. private string groupName;
  984. private int devMajor;
  985. private int devMinor;
  986. #endregion Instance Fields
  987. #region Class Fields
  988. // Values used during recursive operations.
  989. static internal int userIdAsSet;
  990. static internal int groupIdAsSet;
  991. static internal string userNameAsSet;
  992. static internal string groupNameAsSet = "None";
  993. static internal int defaultUserId;
  994. static internal int defaultGroupId;
  995. static internal string defaultGroupName = "None";
  996. static internal string defaultUser;
  997. #endregion Class Fields
  998. }
  999. }