TarOutputStream.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using System;
  2. using System.IO;
  3. namespace ICSharpCode.SharpZipLib.Tar
  4. {
  5. /// <summary>
  6. /// The TarOutputStream writes a UNIX tar archive as an OutputStream.
  7. /// Methods are provided to put entries, and then write their contents
  8. /// by writing to this stream using write().
  9. /// </summary>
  10. /// public
  11. public class TarOutputStream : Stream
  12. {
  13. #region Constructors
  14. /// <summary>
  15. /// Construct TarOutputStream using default block factor
  16. /// </summary>
  17. /// <param name="outputStream">stream to write to</param>
  18. public TarOutputStream(Stream outputStream)
  19. : this(outputStream, TarBuffer.DefaultBlockFactor)
  20. {
  21. }
  22. /// <summary>
  23. /// Construct TarOutputStream with user specified block factor
  24. /// </summary>
  25. /// <param name="outputStream">stream to write to</param>
  26. /// <param name="blockFactor">blocking factor</param>
  27. public TarOutputStream(Stream outputStream, int blockFactor)
  28. {
  29. if (outputStream == null) {
  30. throw new ArgumentNullException("nameof(outputStream)");
  31. }
  32. this.outputStream = outputStream;
  33. buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor);
  34. assemblyBuffer = new byte[TarBuffer.BlockSize];
  35. blockBuffer = new byte[TarBuffer.BlockSize];
  36. }
  37. #endregion
  38. /// <summary>
  39. /// Gets or sets a flag indicating ownership of underlying stream.
  40. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
  41. /// </summary>
  42. /// <remarks>The default value is true.</remarks>
  43. public bool IsStreamOwner {
  44. get { return buffer.IsStreamOwner; }
  45. set { buffer.IsStreamOwner = value; }
  46. }
  47. /// <summary>
  48. /// true if the stream supports reading; otherwise, false.
  49. /// </summary>
  50. public override bool CanRead {
  51. get {
  52. return outputStream.CanRead;
  53. }
  54. }
  55. /// <summary>
  56. /// true if the stream supports seeking; otherwise, false.
  57. /// </summary>
  58. public override bool CanSeek {
  59. get {
  60. return outputStream.CanSeek;
  61. }
  62. }
  63. /// <summary>
  64. /// true if stream supports writing; otherwise, false.
  65. /// </summary>
  66. public override bool CanWrite {
  67. get {
  68. return outputStream.CanWrite;
  69. }
  70. }
  71. /// <summary>
  72. /// length of stream in bytes
  73. /// </summary>
  74. public override long Length {
  75. get {
  76. return outputStream.Length;
  77. }
  78. }
  79. /// <summary>
  80. /// gets or sets the position within the current stream.
  81. /// </summary>
  82. public override long Position {
  83. get {
  84. return outputStream.Position;
  85. }
  86. set {
  87. outputStream.Position = value;
  88. }
  89. }
  90. /// <summary>
  91. /// set the position within the current stream
  92. /// </summary>
  93. /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek to</param>
  94. /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param>
  95. /// <returns>The new position in the stream.</returns>
  96. public override long Seek(long offset, SeekOrigin origin)
  97. {
  98. return outputStream.Seek(offset, origin);
  99. }
  100. /// <summary>
  101. /// Set the length of the current stream
  102. /// </summary>
  103. /// <param name="value">The new stream length.</param>
  104. public override void SetLength(long value)
  105. {
  106. outputStream.SetLength(value);
  107. }
  108. /// <summary>
  109. /// Read a byte from the stream and advance the position within the stream
  110. /// by one byte or returns -1 if at the end of the stream.
  111. /// </summary>
  112. /// <returns>The byte value or -1 if at end of stream</returns>
  113. public override int ReadByte()
  114. {
  115. return outputStream.ReadByte();
  116. }
  117. /// <summary>
  118. /// read bytes from the current stream and advance the position within the
  119. /// stream by the number of bytes read.
  120. /// </summary>
  121. /// <param name="buffer">The buffer to store read bytes in.</param>
  122. /// <param name="offset">The index into the buffer to being storing bytes at.</param>
  123. /// <param name="count">The desired number of bytes to read.</param>
  124. /// <returns>The total number of bytes read, or zero if at the end of the stream.
  125. /// The number of bytes may be less than the <paramref name="count">count</paramref>
  126. /// requested if data is not avialable.</returns>
  127. public override int Read(byte[] buffer, int offset, int count)
  128. {
  129. return outputStream.Read(buffer, offset, count);
  130. }
  131. /// <summary>
  132. /// All buffered data is written to destination
  133. /// </summary>
  134. public override void Flush()
  135. {
  136. outputStream.Flush();
  137. }
  138. /// <summary>
  139. /// Ends the TAR archive without closing the underlying OutputStream.
  140. /// The result is that the EOF block of nulls is written.
  141. /// </summary>
  142. public void Finish()
  143. {
  144. if (IsEntryOpen) {
  145. CloseEntry();
  146. }
  147. WriteEofBlock();
  148. }
  149. /// <summary>
  150. /// Ends the TAR archive and closes the underlying OutputStream.
  151. /// </summary>
  152. /// <remarks>This means that Finish() is called followed by calling the
  153. /// TarBuffer's Close().</remarks>
  154. protected override void Dispose(bool disposing)
  155. {
  156. if (!isClosed) {
  157. isClosed = true;
  158. Finish();
  159. buffer.Close();
  160. }
  161. }
  162. /// <summary>
  163. /// Get the record size being used by this stream's TarBuffer.
  164. /// </summary>
  165. public int RecordSize {
  166. get { return buffer.RecordSize; }
  167. }
  168. /// <summary>
  169. /// Get the record size being used by this stream's TarBuffer.
  170. /// </summary>
  171. /// <returns>
  172. /// The TarBuffer record size.
  173. /// </returns>
  174. [Obsolete("Use RecordSize property instead")]
  175. public int GetRecordSize()
  176. {
  177. return buffer.RecordSize;
  178. }
  179. /// <summary>
  180. /// Get a value indicating wether an entry is open, requiring more data to be written.
  181. /// </summary>
  182. bool IsEntryOpen {
  183. get { return (currBytes < currSize); }
  184. }
  185. /// <summary>
  186. /// Put an entry on the output stream. This writes the entry's
  187. /// header and positions the output stream for writing
  188. /// the contents of the entry. Once this method is called, the
  189. /// stream is ready for calls to write() to write the entry's
  190. /// contents. Once the contents are written, closeEntry()
  191. /// <B>MUST</B> be called to ensure that all buffered data
  192. /// is completely written to the output stream.
  193. /// </summary>
  194. /// <param name="entry">
  195. /// The TarEntry to be written to the archive.
  196. /// </param>
  197. public void PutNextEntry(TarEntry entry)
  198. {
  199. if (entry == null) {
  200. throw new ArgumentNullException("nameof(entry)");
  201. }
  202. if (entry.TarHeader.Name.Length > TarHeader.NAMELEN) {
  203. var longHeader = new TarHeader();
  204. longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME;
  205. longHeader.Name = longHeader.Name + "././@LongLink";
  206. longHeader.Mode = 420;//644 by default
  207. longHeader.UserId = entry.UserId;
  208. longHeader.GroupId = entry.GroupId;
  209. longHeader.GroupName = entry.GroupName;
  210. longHeader.UserName = entry.UserName;
  211. longHeader.LinkName = "";
  212. longHeader.Size = entry.TarHeader.Name.Length + 1; // Plus one to avoid dropping last char
  213. longHeader.WriteHeader(blockBuffer);
  214. buffer.WriteBlock(blockBuffer); // Add special long filename header block
  215. int nameCharIndex = 0;
  216. while (nameCharIndex < entry.TarHeader.Name.Length + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) {
  217. Array.Clear(blockBuffer, 0, blockBuffer.Length);
  218. TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); // This func handles OK the extra char out of string length
  219. nameCharIndex += TarBuffer.BlockSize;
  220. buffer.WriteBlock(blockBuffer);
  221. }
  222. }
  223. entry.WriteEntryHeader(blockBuffer);
  224. buffer.WriteBlock(blockBuffer);
  225. currBytes = 0;
  226. currSize = entry.IsDirectory ? 0 : entry.Size;
  227. }
  228. /// <summary>
  229. /// Close an entry. This method MUST be called for all file
  230. /// entries that contain data. The reason is that we must
  231. /// buffer data written to the stream in order to satisfy
  232. /// the buffer's block based writes. Thus, there may be
  233. /// data fragments still being assembled that must be written
  234. /// to the output stream before this entry is closed and the
  235. /// next entry written.
  236. /// </summary>
  237. public void CloseEntry()
  238. {
  239. if (assemblyBufferLength > 0) {
  240. Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength);
  241. buffer.WriteBlock(assemblyBuffer);
  242. currBytes += assemblyBufferLength;
  243. assemblyBufferLength = 0;
  244. }
  245. if (currBytes < currSize) {
  246. string errorText = string.Format(
  247. "Entry closed at '{0}' before the '{1}' bytes specified in the header were written",
  248. currBytes, currSize);
  249. throw new TarException(errorText);
  250. }
  251. }
  252. /// <summary>
  253. /// Writes a byte to the current tar archive entry.
  254. /// This method simply calls Write(byte[], int, int).
  255. /// </summary>
  256. /// <param name="value">
  257. /// The byte to be written.
  258. /// </param>
  259. public override void WriteByte(byte value)
  260. {
  261. Write(new byte[] { value }, 0, 1);
  262. }
  263. /// <summary>
  264. /// Writes bytes to the current tar archive entry. This method
  265. /// is aware of the current entry and will throw an exception if
  266. /// you attempt to write bytes past the length specified for the
  267. /// current entry. The method is also (painfully) aware of the
  268. /// record buffering required by TarBuffer, and manages buffers
  269. /// that are not a multiple of recordsize in length, including
  270. /// assembling records from small buffers.
  271. /// </summary>
  272. /// <param name = "buffer">
  273. /// The buffer to write to the archive.
  274. /// </param>
  275. /// <param name = "offset">
  276. /// The offset in the buffer from which to get bytes.
  277. /// </param>
  278. /// <param name = "count">
  279. /// The number of bytes to write.
  280. /// </param>
  281. public override void Write(byte[] buffer, int offset, int count)
  282. {
  283. if (buffer == null) {
  284. throw new ArgumentNullException("nameof(buffer)");
  285. }
  286. if (offset < 0) {
  287. throw new ArgumentOutOfRangeException("nameof(offset)", "Cannot be negative");
  288. }
  289. if (buffer.Length - offset < count) {
  290. throw new ArgumentException("offset and count combination is invalid");
  291. }
  292. if (count < 0) {
  293. throw new ArgumentOutOfRangeException("nameof(count)", "Cannot be negative");
  294. }
  295. if ((currBytes + count) > currSize) {
  296. string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes",
  297. count, this.currSize);
  298. throw new ArgumentOutOfRangeException("nameof(count)", errorText);
  299. }
  300. //
  301. // We have to deal with assembly!!!
  302. // The programmer can be writing little 32 byte chunks for all
  303. // we know, and we must assemble complete blocks for writing.
  304. // TODO REVIEW Maybe this should be in TarBuffer? Could that help to
  305. // eliminate some of the buffer copying.
  306. //
  307. if (assemblyBufferLength > 0) {
  308. if ((assemblyBufferLength + count) >= blockBuffer.Length) {
  309. int aLen = blockBuffer.Length - assemblyBufferLength;
  310. Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength);
  311. Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen);
  312. this.buffer.WriteBlock(blockBuffer);
  313. currBytes += blockBuffer.Length;
  314. offset += aLen;
  315. count -= aLen;
  316. assemblyBufferLength = 0;
  317. } else {
  318. Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
  319. offset += count;
  320. assemblyBufferLength += count;
  321. count -= count;
  322. }
  323. }
  324. //
  325. // When we get here we have EITHER:
  326. // o An empty "assembly" buffer.
  327. // o No bytes to write (count == 0)
  328. //
  329. while (count > 0) {
  330. if (count < blockBuffer.Length) {
  331. Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count);
  332. assemblyBufferLength += count;
  333. break;
  334. }
  335. this.buffer.WriteBlock(buffer, offset);
  336. int bufferLength = blockBuffer.Length;
  337. currBytes += bufferLength;
  338. count -= bufferLength;
  339. offset += bufferLength;
  340. }
  341. }
  342. /// <summary>
  343. /// Write an EOF (end of archive) block to the tar archive.
  344. /// The end of the archive is indicated by two blocks consisting entirely of zero bytes.
  345. /// </summary>
  346. void WriteEofBlock()
  347. {
  348. Array.Clear(blockBuffer, 0, blockBuffer.Length);
  349. buffer.WriteBlock(blockBuffer);
  350. buffer.WriteBlock(blockBuffer);
  351. }
  352. #region Instance Fields
  353. /// <summary>
  354. /// bytes written for this entry so far
  355. /// </summary>
  356. long currBytes;
  357. /// <summary>
  358. /// current 'Assembly' buffer length
  359. /// </summary>
  360. int assemblyBufferLength;
  361. /// <summary>
  362. /// Flag indicating wether this instance has been closed or not.
  363. /// </summary>
  364. bool isClosed;
  365. /// <summary>
  366. /// Size for the current entry
  367. /// </summary>
  368. protected long currSize;
  369. /// <summary>
  370. /// single block working buffer
  371. /// </summary>
  372. protected byte[] blockBuffer;
  373. /// <summary>
  374. /// 'Assembly' buffer used to assemble data before writing
  375. /// </summary>
  376. protected byte[] assemblyBuffer;
  377. /// <summary>
  378. /// TarBuffer used to provide correct blocking factor
  379. /// </summary>
  380. protected TarBuffer buffer;
  381. /// <summary>
  382. /// the destination stream for the archive contents
  383. /// </summary>
  384. protected Stream outputStream;
  385. #endregion
  386. }
  387. }