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