3 // Copyright (C) 2001 Mike Krueger
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 // Linking this library statically or dynamically with other modules is
20 // making a combined work based on this library. Thus, the terms and
21 // conditions of the GNU General Public License cover the whole
24 // As a special exception, the copyright holders of this library give you
25 // permission to link this library with independent modules to produce an
26 // executable, regardless of the license terms of these independent
27 // modules, and to copy and distribute the resulting executable under
28 // terms of your choice, provided that you also meet, for each linked
29 // independent module, the terms and conditions of the license of that
30 // module. An independent module is a module which is not derived from
31 // or based on this library. If you modify this library, you may extend
32 // this exception to your version of the library, but you are not
33 // obligated to do so. If you do not wish to do so, delete this
34 // exception statement from your version.
40 namespace ICSharpCode.SharpZipLib.Silverlight.Tar
43 /// The TarInputStream reads a UNIX tar archive as an InputStream.
44 /// methods are provided to position at each successive entry in
45 /// the archive, and the read each entry as a normal input stream
48 public class TarInputStream : Stream
53 /// Construct a TarInputStream with default block factor
55 /// <param name="inputStream">stream to source data from</param>
56 public TarInputStream(Stream inputStream)
57 : this(inputStream, TarBuffer.DefaultBlockFactor)
62 /// Construct a TarInputStream with user specified block factor
64 /// <param name="inputStream">stream to source data from</param>
65 /// <param name="blockFactor">block factor to apply to archive</param>
66 public TarInputStream(Stream inputStream, int blockFactor)
68 this.inputStream = inputStream;
69 _buffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor);
74 #region Stream Overrides
77 /// Gets a value indicating whether the current stream supports reading
79 public override bool CanRead
81 get { return inputStream.CanRead; }
85 /// Gets a value indicating whether the current stream supports seeking
86 /// This property always returns false.
88 public override bool CanSeek
94 /// Gets a value indicating if the stream supports writing.
95 /// This property always returns false.
97 public override bool CanWrite
103 /// The length in bytes of the stream
105 public override long Length
107 get { return inputStream.Length; }
111 /// Gets or sets the position within the stream.
112 /// Setting the Position is not supported and throws a NotSupportedExceptionNotSupportedException
114 /// <exception cref="NotSupportedException">Any attempt to set position</exception>
115 public override long Position
117 get { return inputStream.Position; }
118 set { throw new NotSupportedException("TarInputStream Seek not supported"); }
122 /// Flushes the baseInputStream
124 public override void Flush()
130 /// Set the streams position. This operation is not supported and will throw a NotSupportedException
132 /// <param name="offset">The offset relative to the origin to seek to.</param>
133 /// <param name="origin">The <see cref="SeekOrigin"/> to start seeking from.</param>
134 /// <returns>The new position in the stream.</returns>
135 /// <exception cref="NotSupportedException">Any access</exception>
136 public override long Seek(long offset, SeekOrigin origin)
138 throw new NotSupportedException("TarInputStream Seek not supported");
142 /// Sets the length of the stream
143 /// This operation is not supported and will throw a NotSupportedException
145 /// <param name="value">The new stream length.</param>
146 /// <exception cref="NotSupportedException">Any access</exception>
147 public override void SetLength(long value)
149 throw new NotSupportedException("TarInputStream SetLength not supported");
153 /// Writes a block of bytes to this stream using data from a buffer.
154 /// This operation is not supported and will throw a NotSupportedException
156 /// <param name="buffer">The buffer containing bytes to write.</param>
157 /// <param name="offset">The offset in the buffer of the frist byte to write.</param>
158 /// <param name="count">The number of bytes to write.</param>
159 /// <exception cref="NotSupportedException">Any access</exception>
160 public override void Write(byte[] buffer, int offset, int count)
162 throw new NotSupportedException("TarInputStream Write not supported");
166 /// Writes a byte to the current position in the file stream.
167 /// This operation is not supported and will throw a NotSupportedException
169 /// <param name="value">The byte value to write.</param>
170 /// <exception cref="NotSupportedException">Any access</exception>
171 public override void WriteByte(byte value)
173 throw new NotSupportedException("TarInputStream WriteByte not supported");
177 /// Reads a byte from the current tar archive entry.
179 /// <returns>A byte cast to an int; -1 if the at the end of the stream.</returns>
180 public override int ReadByte()
182 var oneByteBuffer = new byte[1];
183 var num = Read(oneByteBuffer, 0, 1);
186 // return -1 to indicate that no byte was read.
189 return oneByteBuffer[0];
193 /// Reads bytes from the current tar archive entry.
195 /// This method is aware of the boundaries of the current
196 /// entry in the archive and will deal with them appropriately
198 /// <param name="buffer">
199 /// The buffer into which to place bytes read.
201 /// <param name="offset">
202 /// The offset at which to place bytes read.
204 /// <param name="count">
205 /// The number of bytes to read.
208 /// The number of bytes read, or 0 at end of stream/EOF.
210 public override int Read(byte[] buffer, int offset, int count)
214 throw new ArgumentNullException("buffer");
219 if (entryOffset >= entrySize)
224 long numToRead = count;
226 if ((numToRead + entryOffset) > entrySize)
228 numToRead = entrySize - entryOffset;
231 if (readBuffer != null)
233 var sz = (numToRead > readBuffer.Length) ? readBuffer.Length : (int) numToRead;
235 Array.Copy(readBuffer, 0, buffer, offset, sz);
237 if (sz >= readBuffer.Length)
243 var newLen = readBuffer.Length - sz;
244 var newBuf = new byte[newLen];
245 Array.Copy(readBuffer, sz, newBuf, 0, newLen);
254 while (numToRead > 0)
256 var rec = _buffer.ReadBlock();
260 throw new TarException("unexpected EOF with " + numToRead + " bytes unread");
263 var sz = (int) numToRead;
264 var recLen = rec.Length;
268 Array.Copy(rec, 0, buffer, offset, sz);
269 readBuffer = new byte[recLen - sz];
270 Array.Copy(rec, sz, readBuffer, 0, recLen - sz);
275 Array.Copy(rec, 0, buffer, offset, recLen);
283 entryOffset += totalRead;
289 /// Closes this stream. Calls the TarBuffer's close() method.
290 /// The underlying stream is closed by the TarBuffer.
292 public override void Close()
300 /// Get the record size being used by this stream's TarBuffer.
302 public int RecordSize
304 get { return _buffer.RecordSize; }
308 /// Get the available data that can be read from the current
309 /// entry in the archive. This does not indicate how much data
310 /// is left in the entire archive, only in the current entry.
311 /// This value is determined from the entry's size header field
312 /// and the amount of data already read from the current entry.
315 /// The number of available bytes for the current entry.
317 public long Available
319 get { return entrySize - entryOffset; }
323 /// Return a value of true if marking is supported; false otherwise.
325 /// <remarks>Currently marking is not supported, the return value is always false.</remarks>
326 public bool IsMarkSupported
328 get { return false; }
332 /// Set the entry factory for this instance.
334 /// <param name="factory">The factory for creating new entries</param>
335 public void SetEntryFactory(IEntryFactory factory)
337 entryFactory = factory;
341 /// Get the record size being used by this stream's TarBuffer.
344 /// TarBuffer record size.
346 [Obsolete("Use RecordSize property instead")]
347 public int GetRecordSize()
349 return _buffer.RecordSize;
353 /// Skip bytes in the input buffer. This skips bytes in the
354 /// current entry's data, not the entire archive, and will
355 /// stop at the end of the current entry's data if the number
356 /// to skip extends beyond that point.
358 /// <param name="skipCount">
359 /// The number of bytes to skip.
361 public void Skip(long skipCount)
363 // TODO: REVIEW efficiency of TarInputStream.Skip
364 // This is horribly inefficient, but it ensures that we
365 // properly skip over bytes via the TarBuffer...
367 var skipBuf = new byte[8*1024];
369 for (var num = skipCount; num > 0;)
371 var toRead = num > skipBuf.Length ? skipBuf.Length : (int) num;
372 var numRead = Read(skipBuf, 0, toRead);
384 /// Since we do not support marking just yet, we do nothing.
386 /// <param name ="markLimit">
387 /// The limit to mark.
389 public void Mark(int markLimit)
394 /// Since we do not support marking just yet, we do nothing.
401 /// Get the next entry in this tar archive. This will skip
402 /// over any remaining data in the current entry, if there
403 /// is one, and place the input stream at the header of the
404 /// next entry, and read the header and instantiate a new
405 /// TarEntry from the header bytes and return that entry.
406 /// If there are no more entries in the archive, null will
407 /// be returned to indicate that the end of the archive has
411 /// The next TarEntry in the archive, or null.
413 public TarEntry GetNextEntry()
420 if (currentEntry != null)
425 var headerBuf = _buffer.ReadBlock();
427 if (headerBuf == null)
431 else if (_buffer.IsEOFBlock(headerBuf))
444 var header = new TarHeader();
445 header.ParseBuffer(headerBuf);
446 if (!header.IsChecksumValid)
448 throw new TarException("Header checksum is invalid");
451 entrySize = header.Size;
453 StringBuilder longName = null;
455 if (header.TypeFlag == TarHeader.LF_GNU_LONGNAME)
457 var nameBuffer = new byte[TarBuffer.BlockSize];
458 var numToRead = entrySize;
460 longName = new StringBuilder();
462 while (numToRead > 0)
464 var numRead = Read(nameBuffer, 0,
465 (numToRead > nameBuffer.Length ? nameBuffer.Length : (int) numToRead));
469 throw new InvalidHeaderException("Failed to read long name entry");
472 longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead).ToString());
473 numToRead -= numRead;
477 headerBuf = _buffer.ReadBlock();
479 else if (header.TypeFlag == TarHeader.LF_GHDR)
481 // POSIX global extended header
482 // Ignore things we dont understand completely for now
484 headerBuf = _buffer.ReadBlock();
486 else if (header.TypeFlag == TarHeader.LF_XHDR)
488 // POSIX extended header
489 // Ignore things we dont understand completely for now
491 headerBuf = _buffer.ReadBlock();
493 else if (header.TypeFlag == TarHeader.LF_GNU_VOLHDR)
495 // TODO: could show volume name when verbose
497 headerBuf = _buffer.ReadBlock();
499 else if (header.TypeFlag != TarHeader.LF_NORMAL &&
500 header.TypeFlag != TarHeader.LF_OLDNORM &&
501 header.TypeFlag != TarHeader.LF_DIR)
503 // Ignore things we dont understand completely for now
505 headerBuf = _buffer.ReadBlock();
508 if (entryFactory == null)
510 currentEntry = new TarEntry(headerBuf);
511 if (longName != null)
513 currentEntry.Name = longName.ToString();
518 currentEntry = entryFactory.CreateEntry(headerBuf);
521 // Magic was checked here for 'ustar' but there are multiple valid possibilities
522 // so this is not done anymore.
526 // TODO: Review How do we resolve this discrepancy?!
527 entrySize = currentEntry.Size;
529 catch (InvalidHeaderException ex)
534 var errorText = string.Format("Bad header in record {0} block {1} {2}",
535 _buffer.CurrentRecord, _buffer.CurrentBlock, ex.Message);
536 throw new InvalidHeaderException(errorText);
543 /// Copies the contents of the current tar archive entry directly into
544 /// an output stream.
546 /// <param name="outputStream">
547 /// The OutputStream into which to write the entry's data.
549 public void CopyEntryContents(Stream outputStream)
551 var tempBuffer = new byte[32*1024];
555 var numRead = Read(tempBuffer, 0, tempBuffer.Length);
560 outputStream.Write(tempBuffer, 0, numRead);
564 private void SkipToNextEntry()
566 var numToSkip = entrySize - entryOffset;
576 #region Nested type: EntryFactoryAdapter
579 /// Standard entry factory class creating instances of the class TarEntry
581 public class EntryFactoryAdapter : IEntryFactory
583 #region IEntryFactory Members
586 /// Create a <see cref="TarEntry"/> based on named
588 /// <param name="name">The name to use for the entry</param>
589 /// <returns>A new <see cref="TarEntry"/></returns>
590 public TarEntry CreateEntry(string name)
592 return TarEntry.CreateTarEntry(name);
596 /// Create a tar entry with details obtained from <paramref name="fileName">file</paramref>
598 /// <param name="fileName">The name of the file to retrieve details from.</param>
599 /// <returns>A new <see cref="TarEntry"/></returns>
600 public TarEntry CreateEntryFromFile(string fileName)
602 return TarEntry.CreateEntryFromFile(fileName);
606 /// Create an entry based on details in <paramref name="headerBuffer">header</paramref>
608 /// <param name="headerBuffer">The buffer containing entry details.</param>
609 /// <returns>A new <see cref="TarEntry"/></returns>
610 public TarEntry CreateEntry(byte[] headerBuffer)
612 return new TarEntry(headerBuffer);
620 #region Instance Fields
623 /// Stream used as the source of input data.
625 private readonly Stream inputStream;
630 protected TarBuffer _buffer;
633 /// Current entry being read
635 private TarEntry currentEntry;
638 /// Factory used to create TarEntry or descendant class instance
640 protected IEntryFactory entryFactory;
643 /// Number of bytes read for this entry so far
645 protected long entryOffset;
648 /// Size of this entry as recorded in header
650 protected long entrySize;
653 /// Flag set when last block has been read
655 protected bool hasHitEOF;
658 /// Buffer used with calls to <code>Read()</code>
660 protected byte[] readBuffer;
664 #region Nested type: IEntryFactory
667 /// This interface is provided, along with the method <see cref="SetEntryFactory"/>, to allow
668 /// the programmer to have their own <see cref="TarEntry"/> subclass instantiated for the
669 /// entries return from <see cref="GetNextEntry"/>.
671 public interface IEntryFactory
674 /// Create an entry based on name alone
676 /// <param name="name">
677 /// Name of the new EntryPointNotFoundException to create
679 /// <returns>created TarEntry or descendant class</returns>
680 TarEntry CreateEntry(string name);
683 /// Create an instance based on an actual file
685 /// <param name="fileName">
686 /// Name of file to represent in the entry
689 /// Created TarEntry or descendant class
691 TarEntry CreateEntryFromFile(string fileName);
694 /// Create a tar entry based on the header information passed
696 /// <param name="headerBuf">
697 /// Buffer containing header information to base entry on
700 /// Created TarEntry or descendant class
702 TarEntry CreateEntry(byte[] headerBuf);
709 /* The original Java file had this header:
710 ** Authored by Timothy Gerard Endres
711 ** <mailto:time@gjt.org> <http://www.trustice.com>
713 ** This work has been placed into the public domain.
714 ** You may use this work in any way and for any purpose you wish.
716 ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
717 ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
718 ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
719 ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
720 ** REDISTRIBUTION OF THIS SOFTWARE.