TarBuffer.cs 18 KB

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