You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

538 lines
18 KiB

  1. // TarOutputStream.cs
  2. //
  3. // Copyright (C) 2001 Mike Krueger
  4. // Copyright 2005 John Reilly
  5. //
  6. // This program is free software; you can redistribute it and/or
  7. // modify it under the terms of the GNU General Public License
  8. // as published by the Free Software Foundation; either version 2
  9. // of the License, or (at your option) any later version.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with this program; if not, write to the Free Software
  18. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. //
  20. // Linking this library statically or dynamically with other modules is
  21. // making a combined work based on this library. Thus, the terms and
  22. // conditions of the GNU General Public License cover the whole
  23. // combination.
  24. //
  25. // As a special exception, the copyright holders of this library give you
  26. // permission to link this library with independent modules to produce an
  27. // executable, regardless of the license terms of these independent
  28. // modules, and to copy and distribute the resulting executable under
  29. // terms of your choice, provided that you also meet, for each linked
  30. // independent module, the terms and conditions of the license of that
  31. // module. An independent module is a module which is not derived from
  32. // or based on this library. If you modify this library, you may extend
  33. // this exception to your version of the library, but you are not
  34. // obligated to do so. If you do not wish to do so, delete this
  35. // exception statement from your version.
  36. using System;
  37. using System.IO;
  38. namespace Externals.Compression.Tar
  39. {
  40. /// <summary>
  41. /// The TarOutputStream writes a UNIX tar archive as an OutputStream.
  42. /// Methods are provided to put entries, and then write their contents
  43. /// by writing to this stream using write().
  44. /// </summary>
  45. /// public
  46. internal class TarOutputStream : Stream
  47. {
  48. #region Constructors
  49. /// <summary>
  50. /// Construct TarOutputStream using default block factor
  51. /// </summary>
  52. /// <param name="outputStream">stream to write to</param>
  53. public TarOutputStream(Stream outputStream)
  54. : this(outputStream, TarBuffer.DefaultBlockFactor)
  55. {
  56. }
  57. /// <summary>
  58. /// Construct TarOutputStream with user specified block factor
  59. /// </summary>
  60. /// <param name="outputStream">stream to write to</param>
  61. /// <param name="blockFactor">blocking factor</param>
  62. public TarOutputStream(Stream outputStream, int blockFactor)
  63. {
  64. if (outputStream == null)
  65. {
  66. throw new ArgumentNullException("outputStream");
  67. }
  68. this.outputStream = outputStream;
  69. buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor);
  70. assemblyBuffer = new byte[TarBuffer.BlockSize];
  71. blockBuffer = new byte[TarBuffer.BlockSize];
  72. }
  73. #endregion
  74. /// <summary>
  75. /// Get/set flag indicating ownership of the underlying stream.
  76. /// When the flag is true <see cref="Close"></see> will close the underlying stream also.
  77. /// </summary>
  78. public bool IsStreamOwner
  79. {
  80. get { return buffer.IsStreamOwner; }
  81. set { buffer.IsStreamOwner = value; }
  82. }
  83. /// <summary>
  84. /// true if the stream supports reading; otherwise, false.
  85. /// </summary>
  86. public override bool CanRead
  87. {
  88. get
  89. {
  90. return outputStream.CanRead;
  91. }
  92. }
  93. /// <summary>
  94. /// true if the stream supports seeking; otherwise, false.
  95. /// </summary>
  96. public override bool CanSeek
  97. {
  98. get
  99. {
  100. return outputStream.CanSeek;
  101. }
  102. }
  103. /// <summary>
  104. /// true if stream supports writing; otherwise, false.
  105. /// </summary>
  106. public override bool CanWrite
  107. {
  108. get
  109. {
  110. return outputStream.CanWrite;
  111. }
  112. }
  113. /// <summary>
  114. /// length of stream in bytes
  115. /// </summary>
  116. public override long Length
  117. {
  118. get
  119. {
  120. return outputStream.Length;
  121. }
  122. }
  123. /// <summary>
  124. /// gets or sets the position within the current stream.
  125. /// </summary>
  126. public override long Position
  127. {
  128. get
  129. {
  130. return outputStream.Position;
  131. }
  132. set
  133. {
  134. outputStream.Position = value;
  135. }
  136. }
  137. /// <summary>
  138. /// set the position within the current stream
  139. /// </summary>
  140. /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param>
  141. /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param>
  142. /// <returns>The new position in the stream.</returns>
  143. public override long Seek(long offset, SeekOrigin origin)
  144. {
  145. return outputStream.Seek(offset, origin);
  146. }
  147. /// <summary>
  148. /// Set the length of the current stream
  149. /// </summary>
  150. /// <param name="value">The new stream length.</param>
  151. public override void SetLength(long value)
  152. {
  153. outputStream.SetLength(value);
  154. }
  155. /// <summary>
  156. /// Read a byte from the stream and advance the position within the stream
  157. /// by one byte or returns -1 if at the end of the stream.
  158. /// </summary>
  159. /// <returns>The byte value or -1 if at end of stream</returns>
  160. public override int ReadByte()
  161. {
  162. return outputStream.ReadByte();
  163. }
  164. /// <summary>
  165. /// read bytes from the current stream and advance the position within the
  166. /// stream by the number of bytes read.
  167. /// </summary>
  168. /// <param name="buffer">The buffer to store read bytes in.</param>
  169. /// <param name="offset">The index into the buffer to being storing bytes at.</param>
  170. /// <param name="count">The desired number of bytes to read.</param>
  171. /// <returns>The total number of bytes read, or zero if at the end of the stream.
  172. /// The number of bytes may be less than the <paramref name="count">count</paramref>
  173. /// requested if data is not avialable.</returns>
  174. public override int Read(byte[] buffer, int offset, int count)
  175. {
  176. return outputStream.Read(buffer, offset, count);
  177. }
  178. /// <summary>
  179. /// All buffered data is written to destination
  180. /// </summary>
  181. public override void Flush()
  182. {
  183. outputStream.Flush();
  184. }
  185. /// <summary>
  186. /// Ends the TAR archive without closing the underlying OutputStream.
  187. /// The result is that the EOF block of nulls is written.
  188. /// </summary>
  189. public void Finish()
  190. {
  191. if (IsEntryOpen)
  192. {
  193. CloseEntry();
  194. }
  195. WriteEofBlock();
  196. }
  197. /// <summary>
  198. /// Ends the TAR archive and closes the underlying OutputStream.
  199. /// </summary>
  200. /// <remarks>This means that Finish() is called followed by calling the
  201. /// TarBuffer's Close().</remarks>
  202. public override void Close()
  203. {
  204. if (!isClosed)
  205. {
  206. isClosed = true;
  207. Finish();
  208. buffer.Close();
  209. }
  210. }
  211. /// <summary>
  212. /// Get the record size being used by this stream's TarBuffer.
  213. /// </summary>
  214. public int RecordSize
  215. {
  216. get { return buffer.RecordSize; }
  217. }
  218. /// <summary>
  219. /// Get the record size being used by this stream's TarBuffer.
  220. /// </summary>
  221. /// <returns>
  222. /// The TarBuffer record size.
  223. /// </returns>
  224. [Obsolete("Use RecordSize property instead")]
  225. public int GetRecordSize()
  226. {
  227. return buffer.RecordSize;
  228. }
  229. /// <summary>
  230. /// Get a value indicating wether an entry is open, requiring more data to be written.
  231. /// </summary>
  232. bool IsEntryOpen
  233. {
  234. get { return (currBytes < currSize); }
  235. }
  236. /// <summary>
  237. /// Put an entry on the output stream. This writes the entry's
  238. /// header and positions the output stream for writing
  239. /// the contents of the entry. Once this method is called, the
  240. /// stream is ready for calls to write() to write the entry's
  241. /// contents. Once the contents are written, closeEntry()
  242. /// <B>MUST</B> be called to ensure that all buffered data
  243. /// is completely written to the output stream.
  244. /// </summary>
  245. /// <param name="entry">
  246. /// The TarEntry to be written to the archive.
  247. /// </param>
  248. public void PutNextEntry(TarEntry entry)
  249. {
  250. if (entry == null)
  251. {
  252. throw new ArgumentNullException("entry");
  253. }
  254. if (entry.TarHeader.Name.Length >= TarHeader.NAMELEN)
  255. {
  256. TarHeader longHeader = new TarHeader();
  257. longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME;
  258. longHeader.Name = longHeader.Name + "././@LongLink";
  259. longHeader.UserId = 0;
  260. longHeader.GroupId = 0;
  261. longHeader.GroupName = "";
  262. longHeader.UserName = "";
  263. longHeader.LinkName = "";
  264. longHeader.Size = entry.TarHeader.Name.Length;
  265. longHeader.WriteHeader(blockBuffer);
  266. buffer.WriteBlock(blockBuffer); // Add special long filename header block
  267. int nameCharIndex = 0;
  268. while (nameCharIndex < entry.TarHeader.Name.Length)
  269. {
  270. Array.Clear(blockBuffer, 0, blockBuffer.Length);
  271. TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize);
  272. nameCharIndex += TarBuffer.BlockSize;
  273. buffer.WriteBlock(blockBuffer);
  274. }
  275. }
  276. entry.WriteEntryHeader(blockBuffer);
  277. buffer.WriteBlock(blockBuffer);
  278. currBytes = 0;
  279. currSize = entry.IsDirectory ? 0 : entry.Size;
  280. }
  281. /// <summary>
  282. /// Close an entry. This method MUST be called for all file
  283. /// entries that contain data. The reason is that we must
  284. /// buffer data written to the stream in order to satisfy
  285. /// the buffer's block based writes. Thus, there may be
  286. /// data fragments still being assembled that must be written
  287. /// to the output stream before this entry is closed and the
  288. /// next entry written.
  289. /// </summary>
  290. public void CloseEntry()
  291. {
  292. if (assemblyBufferLength > 0)
  293. {
  294. Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength);
  295. buffer.WriteBlock(assemblyBuffer);
  296. currBytes += assemblyBufferLength;
  297. assemblyBufferLength = 0;
  298. }
  299. if (currBytes < currSize)
  300. {
  301. string errorText = string.Format(
  302. "Entry closed at '{0}' before the '{1}' bytes specified in the header were written",
  303. currBytes, currSize);
  304. throw new TarException(errorText);
  305. }
  306. }
  307. /// <summary>
  308. /// Writes a byte to the current tar archive entry.
  309. /// This method simply calls Write(byte[], int, int).
  310. /// </summary>
  311. /// <param name="value">
  312. /// The byte to be written.
  313. /// </param>
  314. public override void WriteByte(byte value)
  315. {
  316. Write(new byte[] { value }, 0, 1);
  317. }
  318. /// <summary>
  319. /// Writes bytes to the current tar archive entry. This method
  320. /// is aware of the current entry and will throw an exception if
  321. /// you attempt to write bytes past the length specified for the
  322. /// current entry. The method is also (painfully) aware of the
  323. /// record buffering required by TarBuffer, and manages buffers
  324. /// that are not a multiple of recordsize in length, including
  325. /// assembling records from small buffers.
  326. /// </summary>
  327. /// <param name = "buffer">
  328. /// The buffer to write to the archive.
  329. /// </param>
  330. /// <param name = "offset">
  331. /// The offset in the buffer from which to get bytes.
  332. /// </param>
  333. /// <param name = "count">
  334. /// The number of bytes to write.
  335. /// </param>
  336. public override void Write(byte[] buffer, int offset, int count)
  337. {
  338. if (buffer == null)
  339. {
  340. throw new ArgumentNullException("buffer");
  341. }
  342. if (offset < 0)
  343. {
  344. #if NETCF_1_0
  345. throw new ArgumentOutOfRangeException("offset");
  346. #else
  347. throw new ArgumentOutOfRangeException("offset", "Cannot be negative");
  348. #endif
  349. }
  350. if (buffer.Length - offset < count)
  351. {
  352. throw new ArgumentException("offset and count combination is invalid");
  353. }
  354. if (count < 0)
  355. {
  356. #if NETCF_1_0
  357. throw new ArgumentOutOfRangeException("count");
  358. #else
  359. throw new ArgumentOutOfRangeException("count", "Cannot be negative");
  360. #endif
  361. }
  362. if ((currBytes + count) > currSize)
  363. {
  364. string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes",
  365. count, this.currSize);
  366. #if NETCF_1_0
  367. throw new ArgumentOutOfRangeException("count");
  368. #else
  369. throw new ArgumentOutOfRangeException("count", errorText);
  370. #endif
  371. }
  372. //
  373. // We have to deal with assembly!!!
  374. // The programmer can be writing little 32 byte chunks for all
  375. // we know, and we must assemble complete blocks for writing.
  376. // TODO REVIEW Maybe this should be in TarBuffer? Could that help to
  377. // eliminate some of the buffer copying.
  378. //
  379. if (assemblyBufferLength > 0)
  380. {
  381. if ((assemblyBufferLength + count) >= blockBuffer.Length)
  382. {
  383. int aLen = blockBuffer.Length - assemblyBufferLength;
  384. Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength);
  385. Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen);
  386. this.buffer.WriteBlock(blockBuffer);
  387. currBytes += blockBuffer.Length;
  388. offset += aLen;
  389. count -= aLen;
  390. assemblyBufferLength = 0;
  391. }
  392. else
  393. {
  394. Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
  395. offset += count;
  396. assemblyBufferLength += count;
  397. count -= count;
  398. }
  399. }
  400. //
  401. // When we get here we have EITHER:
  402. // o An empty "assembly" buffer.
  403. // o No bytes to write (count == 0)
  404. //
  405. while (count > 0)
  406. {
  407. if (count < blockBuffer.Length)
  408. {
  409. Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
  410. assemblyBufferLength += count;
  411. break;
  412. }
  413. this.buffer.WriteBlock(buffer, offset);
  414. int bufferLength = blockBuffer.Length;
  415. currBytes += bufferLength;
  416. count -= bufferLength;
  417. offset += bufferLength;
  418. }
  419. }
  420. /// <summary>
  421. /// Write an EOF (end of archive) block to the tar archive.
  422. /// An EOF block consists of all zeros.
  423. /// </summary>
  424. void WriteEofBlock()
  425. {
  426. Array.Clear(blockBuffer, 0, blockBuffer.Length);
  427. buffer.WriteBlock(blockBuffer);
  428. }
  429. #region Instance Fields
  430. /// <summary>
  431. /// bytes written for this entry so far
  432. /// </summary>
  433. long currBytes;
  434. /// <summary>
  435. /// current 'Assembly' buffer length
  436. /// </summary>
  437. int assemblyBufferLength;
  438. /// <summary>
  439. /// Flag indicating wether this instance has been closed or not.
  440. /// </summary>
  441. bool isClosed;
  442. /// <summary>
  443. /// Size for the current entry
  444. /// </summary>
  445. protected long currSize;
  446. /// <summary>
  447. /// single block working buffer
  448. /// </summary>
  449. protected byte[] blockBuffer;
  450. /// <summary>
  451. /// 'Assembly' buffer used to assemble data before writing
  452. /// </summary>
  453. protected byte[] assemblyBuffer;
  454. /// <summary>
  455. /// TarBuffer used to provide correct blocking factor
  456. /// </summary>
  457. protected TarBuffer buffer;
  458. /// <summary>
  459. /// the destination stream for the archive contents
  460. /// </summary>
  461. protected Stream outputStream;
  462. #endregion
  463. }
  464. }
  465. /* The original Java file had this header:
  466. ** Authored by Timothy Gerard Endres
  467. ** <mailto:time@gjt.org> <http://www.trustice.com>
  468. **
  469. ** This work has been placed into the public domain.
  470. ** You may use this work in any way and for any purpose you wish.
  471. **
  472. ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
  473. ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
  474. ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
  475. ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
  476. ** REDISTRIBUTION OF THIS SOFTWARE.
  477. **
  478. */