TarBuffer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. using System;
  2. using System.IO;
  3. namespace ICSharpCode.SharpZipLib.Tar
  4. {
  5. /// <summary>
  6. /// The TarBuffer class implements the tar archive concept
  7. /// of a buffered input stream. This concept goes back to the
  8. /// days of blocked tape drives and special io devices. In the
  9. /// C# universe, the only real function that this class
  10. /// performs is to ensure that files have the correct "record"
  11. /// size, or other tars will complain.
  12. /// <p>
  13. /// You should never have a need to access this class directly.
  14. /// TarBuffers are created by Tar IO Streams.
  15. /// </p>
  16. /// </summary>
  17. public class TarBuffer
  18. {
  19. /* A quote from GNU tar man file on blocking and records
  20. A `tar' archive file contains a series of blocks. Each block
  21. contains `BLOCKSIZE' bytes. Although this format may be thought of as
  22. being on magnetic tape, other media are often used.
  23. Each file archived is represented by a header block which describes
  24. the file, followed by zero or more blocks which give the contents of
  25. the file. At the end of the archive file there may be a block filled
  26. with binary zeros as an end-of-file marker. A reasonable system should
  27. write a block of zeros at the end, but must not assume that such a
  28. block exists when reading an archive.
  29. The blocks may be "blocked" for physical I/O operations. Each
  30. record of N blocks is written with a single 'write ()'
  31. operation. On magnetic tapes, the result of such a write is a single
  32. record. When writing an archive, the last record of blocks should be
  33. written at the full size, with blocks after the zero block containing
  34. all zeros. When reading an archive, a reasonable system should
  35. properly handle an archive whose last record is shorter than the rest,
  36. or which contains garbage records after a zero block.
  37. */
  38. #region Constants
  39. /// <summary>
  40. /// The size of a block in a tar archive in bytes.
  41. /// </summary>
  42. /// <remarks>This is 512 bytes.</remarks>
  43. public const int BlockSize = 512;
  44. /// <summary>
  45. /// The number of blocks in a default record.
  46. /// </summary>
  47. /// <remarks>
  48. /// The default value is 20 blocks per record.
  49. /// </remarks>
  50. public const int DefaultBlockFactor = 20;
  51. /// <summary>
  52. /// The size in bytes of a default record.
  53. /// </summary>
  54. /// <remarks>
  55. /// The default size is 10KB.
  56. /// </remarks>
  57. public const int DefaultRecordSize = BlockSize * DefaultBlockFactor;
  58. #endregion Constants
  59. /// <summary>
  60. /// Get the record size for this buffer
  61. /// </summary>
  62. /// <value>The record size in bytes.
  63. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></value>
  64. public int RecordSize
  65. {
  66. get
  67. {
  68. return recordSize;
  69. }
  70. }
  71. /// <summary>
  72. /// Get the TAR Buffer's record size.
  73. /// </summary>
  74. /// <returns>The record size in bytes.
  75. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></returns>
  76. [Obsolete("Use RecordSize property instead")]
  77. public int GetRecordSize()
  78. {
  79. return recordSize;
  80. }
  81. /// <summary>
  82. /// Get the Blocking factor for the buffer
  83. /// </summary>
  84. /// <value>This is the number of blocks in each record.</value>
  85. public int BlockFactor
  86. {
  87. get
  88. {
  89. return blockFactor;
  90. }
  91. }
  92. /// <summary>
  93. /// Get the TAR Buffer's block factor
  94. /// </summary>
  95. /// <returns>The block factor; the number of blocks per record.</returns>
  96. [Obsolete("Use BlockFactor property instead")]
  97. public int GetBlockFactor()
  98. {
  99. return blockFactor;
  100. }
  101. /// <summary>
  102. /// Construct a default TarBuffer
  103. /// </summary>
  104. protected TarBuffer()
  105. {
  106. }
  107. /// <summary>
  108. /// Create TarBuffer for reading with default BlockFactor
  109. /// </summary>
  110. /// <param name="inputStream">Stream to buffer</param>
  111. /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns>
  112. public static TarBuffer CreateInputTarBuffer(Stream inputStream)
  113. {
  114. if (inputStream == null)
  115. {
  116. throw new ArgumentNullException(nameof(inputStream));
  117. }
  118. return CreateInputTarBuffer(inputStream, DefaultBlockFactor);
  119. }
  120. /// <summary>
  121. /// Construct TarBuffer for reading inputStream setting BlockFactor
  122. /// </summary>
  123. /// <param name="inputStream">Stream to buffer</param>
  124. /// <param name="blockFactor">Blocking factor to apply</param>
  125. /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns>
  126. public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor)
  127. {
  128. if (inputStream == null)
  129. {
  130. throw new ArgumentNullException(nameof(inputStream));
  131. }
  132. if (blockFactor <= 0)
  133. {
  134. throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative");
  135. }
  136. var tarBuffer = new TarBuffer();
  137. tarBuffer.inputStream = inputStream;
  138. tarBuffer.outputStream = null;
  139. tarBuffer.Initialize(blockFactor);
  140. return tarBuffer;
  141. }
  142. /// <summary>
  143. /// Construct TarBuffer for writing with default BlockFactor
  144. /// </summary>
  145. /// <param name="outputStream">output stream for buffer</param>
  146. /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns>
  147. public static TarBuffer CreateOutputTarBuffer(Stream outputStream)
  148. {
  149. if (outputStream == null)
  150. {
  151. throw new ArgumentNullException(nameof(outputStream));
  152. }
  153. return CreateOutputTarBuffer(outputStream, DefaultBlockFactor);
  154. }
  155. /// <summary>
  156. /// Construct TarBuffer for writing Tar output to streams.
  157. /// </summary>
  158. /// <param name="outputStream">Output stream to write to.</param>
  159. /// <param name="blockFactor">Blocking factor to apply</param>
  160. /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns>
  161. public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor)
  162. {
  163. if (outputStream == null)
  164. {
  165. throw new ArgumentNullException(nameof(outputStream));
  166. }
  167. if (blockFactor <= 0)
  168. {
  169. throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative");
  170. }
  171. var tarBuffer = new TarBuffer();
  172. tarBuffer.inputStream = null;
  173. tarBuffer.outputStream = outputStream;
  174. tarBuffer.Initialize(blockFactor);
  175. return tarBuffer;
  176. }
  177. /// <summary>
  178. /// Initialization common to all constructors.
  179. /// </summary>
  180. private void Initialize(int archiveBlockFactor)
  181. {
  182. blockFactor = archiveBlockFactor;
  183. recordSize = archiveBlockFactor * BlockSize;
  184. recordBuffer = new byte[RecordSize];
  185. if (inputStream != null)
  186. {
  187. currentRecordIndex = -1;
  188. currentBlockIndex = BlockFactor;
  189. }
  190. else
  191. {
  192. currentRecordIndex = 0;
  193. currentBlockIndex = 0;
  194. }
  195. }
  196. /// <summary>
  197. /// Determine if an archive block indicates End of Archive. End of
  198. /// archive is indicated by a block that consists entirely of null bytes.
  199. /// All remaining blocks for the record should also be null's
  200. /// However some older tars only do a couple of null blocks (Old GNU tar for one)
  201. /// and also partial records
  202. /// </summary>
  203. /// <param name = "block">The data block to check.</param>
  204. /// <returns>Returns true if the block is an EOF block; false otherwise.</returns>
  205. [Obsolete("Use IsEndOfArchiveBlock instead")]
  206. public bool IsEOFBlock(byte[] block)
  207. {
  208. if (block == null)
  209. {
  210. throw new ArgumentNullException(nameof(block));
  211. }
  212. if (block.Length != BlockSize)
  213. {
  214. throw new ArgumentException("block length is invalid");
  215. }
  216. for (int i = 0; i < BlockSize; ++i)
  217. {
  218. if (block[i] != 0)
  219. {
  220. return false;
  221. }
  222. }
  223. return true;
  224. }
  225. /// <summary>
  226. /// Determine if an archive block indicates the End of an Archive has been reached.
  227. /// End of archive is indicated by a block that consists entirely of null bytes.
  228. /// All remaining blocks for the record should also be null's
  229. /// However some older tars only do a couple of null blocks (Old GNU tar for one)
  230. /// and also partial records
  231. /// </summary>
  232. /// <param name = "block">The data block to check.</param>
  233. /// <returns>Returns true if the block is an EOF block; false otherwise.</returns>
  234. public static bool IsEndOfArchiveBlock(byte[] block)
  235. {
  236. if (block == null)
  237. {
  238. throw new ArgumentNullException(nameof(block));
  239. }
  240. if (block.Length != BlockSize)
  241. {
  242. throw new ArgumentException("block length is invalid");
  243. }
  244. for (int i = 0; i < BlockSize; ++i)
  245. {
  246. if (block[i] != 0)
  247. {
  248. return false;
  249. }
  250. }
  251. return true;
  252. }
  253. /// <summary>
  254. /// Skip over a block on the input stream.
  255. /// </summary>
  256. public void SkipBlock()
  257. {
  258. if (inputStream == null)
  259. {
  260. throw new TarException("no input stream defined");
  261. }
  262. if (currentBlockIndex >= BlockFactor)
  263. {
  264. if (!ReadRecord())
  265. {
  266. throw new TarException("Failed to read a record");
  267. }
  268. }
  269. currentBlockIndex++;
  270. }
  271. /// <summary>
  272. /// Read a block from the input stream.
  273. /// </summary>
  274. /// <returns>
  275. /// The block of data read.
  276. /// </returns>
  277. public byte[] ReadBlock()
  278. {
  279. if (inputStream == null)
  280. {
  281. throw new TarException("TarBuffer.ReadBlock - no input stream defined");
  282. }
  283. if (currentBlockIndex >= BlockFactor)
  284. {
  285. if (!ReadRecord())
  286. {
  287. throw new TarException("Failed to read a record");
  288. }
  289. }
  290. byte[] result = new byte[BlockSize];
  291. Array.Copy(recordBuffer, (currentBlockIndex * BlockSize), result, 0, BlockSize);
  292. currentBlockIndex++;
  293. return result;
  294. }
  295. /// <summary>
  296. /// Read a record from data stream.
  297. /// </summary>
  298. /// <returns>
  299. /// false if End-Of-File, else true.
  300. /// </returns>
  301. private bool ReadRecord()
  302. {
  303. if (inputStream == null)
  304. {
  305. throw new TarException("no input stream stream defined");
  306. }
  307. currentBlockIndex = 0;
  308. int offset = 0;
  309. int bytesNeeded = RecordSize;
  310. while (bytesNeeded > 0)
  311. {
  312. long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded);
  313. //
  314. // NOTE
  315. // We have found EOF, and the record is not full!
  316. //
  317. // This is a broken archive. It does not follow the standard
  318. // blocking algorithm. However, because we are generous, and
  319. // it requires little effort, we will simply ignore the error
  320. // and continue as if the entire record were read. This does
  321. // not appear to break anything upstream. We used to return
  322. // false in this case.
  323. //
  324. // Thanks to 'Yohann.Roussel@alcatel.fr' for this fix.
  325. //
  326. if (numBytes <= 0)
  327. {
  328. break;
  329. }
  330. offset += (int)numBytes;
  331. bytesNeeded -= (int)numBytes;
  332. }
  333. currentRecordIndex++;
  334. return true;
  335. }
  336. /// <summary>
  337. /// Get the current block number, within the current record, zero based.
  338. /// </summary>
  339. /// <remarks>Block numbers are zero based values</remarks>
  340. /// <seealso cref="RecordSize"/>
  341. public int CurrentBlock
  342. {
  343. get { return currentBlockIndex; }
  344. }
  345. /// <summary>
  346. /// Gets or sets a flag indicating ownership of underlying stream.
  347. /// When the flag is true <see cref="Close" /> will close the underlying stream also.
  348. /// </summary>
  349. /// <remarks>The default value is true.</remarks>
  350. public bool IsStreamOwner { get; set; } = true;
  351. /// <summary>
  352. /// Get the current block number, within the current record, zero based.
  353. /// </summary>
  354. /// <returns>
  355. /// The current zero based block number.
  356. /// </returns>
  357. /// <remarks>
  358. /// The absolute block number = (<see cref="GetCurrentRecordNum">record number</see> * <see cref="BlockFactor">block factor</see>) + <see cref="GetCurrentBlockNum">block number</see>.
  359. /// </remarks>
  360. [Obsolete("Use CurrentBlock property instead")]
  361. public int GetCurrentBlockNum()
  362. {
  363. return currentBlockIndex;
  364. }
  365. /// <summary>
  366. /// Get the current record number.
  367. /// </summary>
  368. /// <returns>
  369. /// The current zero based record number.
  370. /// </returns>
  371. public int CurrentRecord
  372. {
  373. get { return currentRecordIndex; }
  374. }
  375. /// <summary>
  376. /// Get the current record number.
  377. /// </summary>
  378. /// <returns>
  379. /// The current zero based record number.
  380. /// </returns>
  381. [Obsolete("Use CurrentRecord property instead")]
  382. public int GetCurrentRecordNum()
  383. {
  384. return currentRecordIndex;
  385. }
  386. /// <summary>
  387. /// Write a block of data to the archive.
  388. /// </summary>
  389. /// <param name="block">
  390. /// The data to write to the archive.
  391. /// </param>
  392. public void WriteBlock(byte[] block)
  393. {
  394. if (block == null)
  395. {
  396. throw new ArgumentNullException(nameof(block));
  397. }
  398. if (outputStream == null)
  399. {
  400. throw new TarException("TarBuffer.WriteBlock - no output stream defined");
  401. }
  402. if (block.Length != BlockSize)
  403. {
  404. string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'",
  405. block.Length, BlockSize);
  406. throw new TarException(errorText);
  407. }
  408. if (currentBlockIndex >= BlockFactor)
  409. {
  410. WriteRecord();
  411. }
  412. Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize);
  413. currentBlockIndex++;
  414. }
  415. /// <summary>
  416. /// Write an archive record to the archive, where the record may be
  417. /// inside of a larger array buffer. The buffer must be "offset plus
  418. /// record size" long.
  419. /// </summary>
  420. /// <param name="buffer">
  421. /// The buffer containing the record data to write.
  422. /// </param>
  423. /// <param name="offset">
  424. /// The offset of the record data within buffer.
  425. /// </param>
  426. public void WriteBlock(byte[] buffer, int offset)
  427. {
  428. if (buffer == null)
  429. {
  430. throw new ArgumentNullException(nameof(buffer));
  431. }
  432. if (outputStream == null)
  433. {
  434. throw new TarException("TarBuffer.WriteBlock - no output stream stream defined");
  435. }
  436. if ((offset < 0) || (offset >= buffer.Length))
  437. {
  438. throw new ArgumentOutOfRangeException(nameof(offset));
  439. }
  440. if ((offset + BlockSize) > buffer.Length)
  441. {
  442. string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'",
  443. buffer.Length, offset, recordSize);
  444. throw new TarException(errorText);
  445. }
  446. if (currentBlockIndex >= BlockFactor)
  447. {
  448. WriteRecord();
  449. }
  450. Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize);
  451. currentBlockIndex++;
  452. }
  453. /// <summary>
  454. /// Write a TarBuffer record to the archive.
  455. /// </summary>
  456. private void WriteRecord()
  457. {
  458. if (outputStream == null)
  459. {
  460. throw new TarException("TarBuffer.WriteRecord no output stream defined");
  461. }
  462. outputStream.Write(recordBuffer, 0, RecordSize);
  463. outputStream.Flush();
  464. currentBlockIndex = 0;
  465. currentRecordIndex++;
  466. }
  467. /// <summary>
  468. /// WriteFinalRecord writes the current record buffer to output any unwritten data is present.
  469. /// </summary>
  470. /// <remarks>Any trailing bytes are set to zero which is by definition correct behaviour
  471. /// for the end of a tar stream.</remarks>
  472. private void WriteFinalRecord()
  473. {
  474. if (outputStream == null)
  475. {
  476. throw new TarException("TarBuffer.WriteFinalRecord no output stream defined");
  477. }
  478. if (currentBlockIndex > 0)
  479. {
  480. int dataBytes = currentBlockIndex * BlockSize;
  481. Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes);
  482. WriteRecord();
  483. }
  484. outputStream.Flush();
  485. }
  486. /// <summary>
  487. /// Close the TarBuffer. If this is an output buffer, also flush the
  488. /// current block before closing.
  489. /// </summary>
  490. public void Close()
  491. {
  492. if (outputStream != null)
  493. {
  494. WriteFinalRecord();
  495. if (IsStreamOwner)
  496. {
  497. outputStream.Dispose();
  498. }
  499. outputStream = null;
  500. }
  501. else if (inputStream != null)
  502. {
  503. if (IsStreamOwner)
  504. {
  505. inputStream.Dispose();
  506. }
  507. inputStream = null;
  508. }
  509. }
  510. #region Instance Fields
  511. private Stream inputStream;
  512. private Stream outputStream;
  513. private byte[] recordBuffer;
  514. private int currentBlockIndex;
  515. private int currentRecordIndex;
  516. private int recordSize = DefaultRecordSize;
  517. private int blockFactor = DefaultBlockFactor;
  518. #endregion Instance Fields
  519. }
  520. }