File: ZipWriter.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (340 lines) | stat: -rw-r--r-- 12,834 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressor;
#if BZIP2
using SharpCompress.Compressor.BZip2;
#endif
using SharpCompress.Compressor.Deflate;
#if LZMA
using SharpCompress.Compressor.LZMA;
#endif
#if PPMd
using SharpCompress.Compressor.PPMd;
#endif
using SharpCompress.IO;
#if DEFLATE
using DeflateStream = SharpCompress.Compressor.Deflate.DeflateStream;
#endif

namespace SharpCompress.Writer.Zip
{
    internal class ZipWriter : AbstractWriter
    {
        private readonly ZipCompressionMethod compression;
        private readonly CompressionLevel deflateCompressionLevel;

        private readonly List<ZipCentralDirectoryEntry> entries = new List<ZipCentralDirectoryEntry>();
        private readonly string zipComment;
        private long streamPosition;

#if PPMd
        private readonly PpmdProperties ppmdProperties; // Caching properties to speed up PPMd.
#endif

        public ZipWriter(Stream destination, CompressionInfo compressionInfo, string zipComment)
            : base(ArchiveType.Zip)
        {
            this.zipComment = zipComment ?? string.Empty;

            switch (compressionInfo.Type)
            {
                case CompressionType.None:
                    {
                        compression = ZipCompressionMethod.None;
                    }
                    break;
                case CompressionType.Deflate:
                    {
                        compression = ZipCompressionMethod.Deflate;
                        deflateCompressionLevel = compressionInfo.DeflateCompressionLevel;
                    }
                    break;
                case CompressionType.BZip2:
                    {
                        compression = ZipCompressionMethod.BZip2;
                    }
                    break;
#if LZMA
                case CompressionType.LZMA:
                    {
                        compression = ZipCompressionMethod.LZMA;
                    }
                    break;
#endif
#if PPMd
                case CompressionType.PPMd:
                    {
                        ppmdProperties = new PpmdProperties();
                        compression = ZipCompressionMethod.PPMd;
                    }
                    break;
#endif
                default:
                    throw new InvalidFormatException("Invalid compression method: " + compressionInfo.Type);
            }
            InitalizeStream(destination, false);
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                uint size = 0;
                foreach (ZipCentralDirectoryEntry entry in entries)
                {
                    size += entry.Write(OutputStream, compression);
                }
                WriteEndRecord(size);
            }
            base.Dispose(isDisposing);
        }

        public override void Write(string entryPath, Stream source, DateTime? modificationTime)
        {
            Write(entryPath, source, modificationTime, null);
        }

        public void Write(string entryPath, Stream source, DateTime? modificationTime, string comment)
        {
            using (Stream output = WriteToStream(entryPath, modificationTime, comment))
            {
                source.TransferTo(output);
            }
        }

        public Stream WriteToStream(string entryPath, DateTime? modificationTime, string comment)
        {
            entryPath = NormalizeFilename(entryPath);
            modificationTime = modificationTime ?? DateTime.Now;
            comment = comment ?? "";
            var entry = new ZipCentralDirectoryEntry
                            {
                                Comment = comment,
                                FileName = entryPath,
                                ModificationTime = modificationTime,
                                HeaderOffset = (uint) streamPosition,
                            };
            var headersize = (uint) WriteHeader(entryPath, modificationTime);
            streamPosition += headersize;
            return new ZipWritingStream(this, OutputStream, entry);
        }

        private string NormalizeFilename(string filename)
        {
            filename = filename.Replace('\\', '/');

            int pos = filename.IndexOf(':');
            if (pos >= 0)
                filename = filename.Remove(0, pos + 1);

            return filename;
        }

        private int WriteHeader(string filename, DateTime? modificationTime)
        {
            byte[] encodedFilename = Encoding.UTF8.GetBytes(filename);

            OutputStream.Write(BitConverter.GetBytes(ZipHeaderFactory.ENTRY_HEADER_BYTES), 0, 4);
            OutputStream.Write(new byte[] {63, 0}, 0, 2); //version
            HeaderFlags flags = HeaderFlags.UTF8;
            if (!OutputStream.CanSeek)
            {
                flags |= HeaderFlags.UsePostDataDescriptor;
                if (compression == ZipCompressionMethod.LZMA)
                {
                    flags |= HeaderFlags.Bit1; // eos marker
                }
            }
            OutputStream.Write(BitConverter.GetBytes((ushort) flags), 0, 2);
            OutputStream.Write(BitConverter.GetBytes((ushort) compression), 0, 2); // zipping method
            OutputStream.Write(BitConverter.GetBytes(modificationTime.DateTimeToDosTime()), 0, 4);
            // zipping date and time
            OutputStream.Write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 12);
            // unused CRC, un/compressed size, updated later
            OutputStream.Write(BitConverter.GetBytes((ushort) encodedFilename.Length), 0, 2); // filename length
            OutputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // extra length
            OutputStream.Write(encodedFilename, 0, encodedFilename.Length);

            return 6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length;
        }

        private void WriteFooter(uint crc, uint compressed, uint uncompressed)
        {
            OutputStream.Write(BitConverter.GetBytes(crc), 0, 4);
            OutputStream.Write(BitConverter.GetBytes(compressed), 0, 4);
            OutputStream.Write(BitConverter.GetBytes(uncompressed), 0, 4);
        }

        private void WriteEndRecord(uint size)
        {
            byte[] encodedComment = Encoding.UTF8.GetBytes(zipComment);

            OutputStream.Write(new byte[] {80, 75, 5, 6, 0, 0, 0, 0}, 0, 8);
            OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2);
            OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2);
            OutputStream.Write(BitConverter.GetBytes(size), 0, 4);
            OutputStream.Write(BitConverter.GetBytes((uint) streamPosition), 0, 4);
            OutputStream.Write(BitConverter.GetBytes((ushort) encodedComment.Length), 0, 2);
            OutputStream.Write(encodedComment, 0, encodedComment.Length);
        }

        #region Nested type: ZipWritingStream

        internal class ZipWritingStream : Stream
        {
            private readonly CRC32 crc = new CRC32();
            private readonly ZipCentralDirectoryEntry entry;
            private readonly Stream originalStream;
            private readonly Stream writeStream;
            private readonly ZipWriter writer;
            private CountingWritableSubStream counting;
            private uint decompressed;

            internal ZipWritingStream(ZipWriter writer, Stream originalStream, ZipCentralDirectoryEntry entry)
            {
                this.writer = writer;
                this.originalStream = originalStream;
                writeStream = GetWriteStream(originalStream);
                this.writer = writer;
                this.entry = entry;
            }

            public override bool CanRead
            {
                get { return false; }
            }

            public override bool CanSeek
            {
                get { return false; }
            }

            public override bool CanWrite
            {
                get { return true; }
            }

            public override long Length
            {
                get { throw new NotSupportedException(); }
            }

            public override long Position
            {
                get { throw new NotSupportedException(); }
                set { throw new NotSupportedException(); }
            }

            private Stream GetWriteStream(Stream writeStream)
            {
                counting = new CountingWritableSubStream(writeStream);
                Stream output = counting;
                switch (writer.compression)
                {
                    case ZipCompressionMethod.None:
                        {
                            return output;
                        }
                    case ZipCompressionMethod.Deflate:
                        {
                            return new System.IO.Compression.DeflateStream(counting,
                                System.IO.Compression.CompressionMode.Compress, true);
                        }
#if BZIP2
                    case ZipCompressionMethod.BZip2:
                        {
                            return new BZip2Stream(counting, CompressionMode.Compress, true);
                        }
#endif
#if LZMA
                    case ZipCompressionMethod.LZMA:
                        {
                            counting.WriteByte(9);
                            counting.WriteByte(20);
                            counting.WriteByte(5);
                            counting.WriteByte(0);

                            LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek),
                                                                   false, counting);
                            counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length);
                            return lzmaStream;
                        }
#endif
#if PPMd
                    case ZipCompressionMethod.PPMd:
                        {
                            counting.Write(writer.ppmdProperties.Properties, 0, 2);
                            return new PpmdStream(writer.ppmdProperties, counting, true);
                        }
#endif
                    default:
                        {
                            throw new NotSupportedException("CompressionMethod: " + writer.compression);
                        }
                }
            }

            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
                if (disposing)
                {
                    writeStream.Dispose();
                    entry.Crc = (uint) crc.Crc32Result;
                    entry.Compressed = counting.Count;
                    entry.Decompressed = decompressed;
                    if (originalStream.CanSeek)
                    {
                        originalStream.Position = entry.HeaderOffset + 6;
                        originalStream.WriteByte(0);
                        originalStream.Position = entry.HeaderOffset + 14;
                        writer.WriteFooter(entry.Crc, counting.Count, decompressed);
                        originalStream.Position = writer.streamPosition + entry.Compressed;
                        writer.streamPosition += entry.Compressed;
                    }
                    else
                    {
                        originalStream.Write(BitConverter.GetBytes(ZipHeaderFactory.POST_DATA_DESCRIPTOR), 0, 4);
                        writer.WriteFooter(entry.Crc, counting.Count, decompressed);
                        writer.streamPosition += entry.Compressed + 16;
                    }
                    writer.entries.Add(entry);
                }
            }

            public override void Flush()
            {
                writeStream.Flush();
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                throw new NotSupportedException();
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                throw new NotSupportedException();
            }

            public override void SetLength(long value)
            {
                throw new NotSupportedException();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                decompressed += (uint) count;
                crc.SlurpBlock(buffer, offset, count);
                writeStream.Write(buffer, offset, count);
            }
        }

        #endregion
    }
}