TarOutputStream.cs 13 KB

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